<?php

namespace Sibs\Stargate\Config;

use Sibs\Stargate\Constants\Environments;
use Sibs\Stargate\Constants\IntegrationTypes;
use Sibs\Stargate\Constants\Plugin;
use Sibs\Stargate\Constants\WebhookVersions;
use Sibs\Stargate\Constants\WoocommercePaymentMethods;
use Sibs\Stargate\Models\WordpressOptions;

defined('ABSPATH') || exit;

class SibsConfig
{
    public const SIBS_CHANNEL = 'web';
    public const SIBS_PROJECT = 'stargate';
    public const SIBS_ECOMMERCE = 'Woocommerce';
    public const SIBS_GENERAL_CONFIG = Plugin::PLUGIN_PREFIX.'_general';
    public const SIBS_STYLE_CONFIG = Plugin::PLUGIN_PREFIX.'_style';
    public const REPORT_BUG_BASE_URL = 'https://plugin-stargate.store/bug-report';
    public const PAYMENTS = [
        WoocommercePaymentMethods::CARD,
        WoocommercePaymentMethods::BLIK,
        WoocommercePaymentMethods::PAY_BY_LINK,
        WoocommercePaymentMethods::PAY_BY_LINK_KEVIN,
        WoocommercePaymentMethods::XPAY,
    ];

    // URLS

    /**
     * Get SIBS Settings URL.
     */
    public static function getSibsSettingsURL(): string
    {
        return admin_url('admin.php?page=sibs_settings');
    }

    /**
     * Get SIBS Styles URL.
     */
    public static function getSibsStylesURL(): string
    {
        return admin_url('admin.php?page=sibs_style');
    }

    /**
     * Get Payments Url.
     */
    public static function getPaymentsUrl(string $section = ''): string
    {
        return admin_url('admin.php?page=wc-settings&tab=checkout').(!empty($section) ? '&section='.$section : '');
    }

    /**
     * Get Docs URL.
     */
    public static function getDocsURL(): string
    {
        return 'https://www.docs.pay.sibs.com/integrations/plugins/woocommerce/';
    }

    /**
     * Get Logs URL.
     */
    public static function getLogsURL(): string
    {
        return admin_url('admin.php?page=wc-status&tab=logs');
    }

    // SETTINGS

    /**
     * Set terminal ID.
     */
    public static function setTerminalId(int $terminalId)
    {
        self::setGeneralOption('merchant_no', $terminalId);
    }

    /**
     * Get Terminal ID.
     */
    public static function getTerminalId(): ?int
    {
        $terminalId = self::getGeneralOption('merchant_no');

        return !is_null($terminalId) ? (int) $terminalId : null;
    }

    /**
     * Set Client.
     */
    public static function setClientId(string $clientId)
    {
        self::setGeneralOption('client_id', $clientId);
    }

    /**
     * Get Client.
     */
    public static function getClientId(): string
    {
        return self::getGeneralOption('client_id', '');
    }

    /**
     * Set Token.
     */
    public static function setToken(string $token)
    {
        self::setGeneralOption('bearer_token', $token);
    }

    /**
     * Get Token.
     */
    public static function getToken(): string
    {
        return self::getGeneralOption('bearer_token', '');
    }

    /**
     * Set Environment.
     */
    public static function setEnvironment(string $environment)
    {
        self::setGeneralOption('environment', $environment);
    }

    /**
     * Get Environment.
     */
    public static function getEnvironment(): string
    {
        return self::getGeneralOption('environment', Environments::default());
    }

    /**
     * Set Webhook Secret.
     */
    public static function setWebhookSecret(string $webhookSecret)
    {
        self::setGeneralOption('webhook_secret', $webhookSecret);
    }

    /**
     * Get Webhook Secret.
     */
    public static function getWebhookSecret(): string
    {
        return self::getGeneralOption('webhook_secret', '');
    }

    /**
     * Set Force Disable Click To Pay.
     */
    public static function setForceDisableClickToPay(bool $value)
    {
        self::setGeneralOption('force_disable_click_to_pay', $value);
    }

    /**
     * Get Force Disable Ckick To Pay.
     *
     * @return string
     */
    public static function getForceDisableClickToPay()
    {
        return self::getGeneralOption('force_disable_click_to_pay', '0');
    }

    /**
     * Set Language Default.
     */
    public static function setLanguageDefault(string $language)
    {
        self::setGeneralOption('language', $language);
    }

    /**
     * Get Language Default.
     */
    public static function getLanguageDefault(): string
    {
        return self::getGeneralOption('language', 'en');
    }

    /**
     * Set Integration Type.
     */
    public static function setIntegrationType(string $integrationType)
    {
        self::setGeneralOption('integration_type', $integrationType);
    }

    /**
     * Get Integration Type.
     */
    public static function getIntegrationType(): string
    {
        return self::getGeneralOption('integration_type') ?? IntegrationTypes::default();
    }

    /**
     * Get Moto.
     */
    public static function getMoto(): bool
    {
        return false;
    }

    /**
     * Get Channel.
     */
    public static function getChannel(): string
    {
        return self::SIBS_CHANNEL;
    }

    // CREDITCARD

    /**
     * Get Creditcard URL.
     */
    public static function getCreditCardURL(): string
    {
        return self::getPaymentsURL(WoocommercePaymentMethods::CARD);
    }

    /**
     * Get Creditcard Enabled.
     */
    public static function getCreditCardEnabled(): bool
    {
        return (bool) ('yes' == self::getPaymentOption(WoocommercePaymentMethods::CARD, 'enabled')) ?? false;
    }

    /**
     * Get Creditcard Title.
     */
    public static function getCreditCardTitle(): string
    {
        return self::getPaymentOption(WoocommercePaymentMethods::CARD, 'title') ?? 'false';
    }

    /**
     * Get Creditcard Description.
     */
    public static function getCreditCardDescription(): string
    {
        return self::getPaymentOption(WoocommercePaymentMethods::CARD, 'description') ?? 'false';
    }

    /**
     * Get Creditcard Transaction Mode.
     */
    public static function getCreditCardTransactionMode(): string
    {
        return self::getPaymentOption(WoocommercePaymentMethods::CARD, 'trans_mode') ?? '';
    }

    /**
     * Get Creditcard Types.
     */
    public static function getCreditCardCardTypes(): array
    {
        return json_decode(self::getPaymentOption(WoocommercePaymentMethods::CARD, 'card_types'), true) ?? [];
    }

    // BLIK

    /**
     * Get BLIK URL.
     */
    public static function getBlikURL(): string
    {
        return self::getPaymentsURL(WoocommercePaymentMethods::BLIK);
    }

    /**
     * GET BLIK Enabled.
     */
    public static function getBlikEnabled(): bool
    {
        return (bool) ('yes' == self::getPaymentOption(WoocommercePaymentMethods::BLIK, 'enabled')) ?? false;
    }

    /**
     * Get BLIK Title.
     */
    public static function getBlikTitle(): string
    {
        return self::getPaymentOption(WoocommercePaymentMethods::BLIK, 'title') ?? '';
    }

    /**
     * Get BLIK Description.
     */
    public static function getBlikDescription(): string
    {
        return self::getPaymentOption(WoocommercePaymentMethods::BLIK, 'description') ?? '';
    }

    /**
     * Get BLIK Transaction Mode.
     */
    public static function getBlikTransactionMode(): string
    {
        return self::getPaymentOption(WoocommercePaymentMethods::BLIK, 'trans_mode') ?? '';
    }

    /**
     * Get BLIK Mandate Type.
     */
    public static function getBlikMandateType(): string
    {
        return self::getPaymentOption(WoocommercePaymentMethods::BLIK, 'mandate_type') ?? '';
    }

    // PAY BY LINK KEVIN

    /**
     * Get Pay By Link Kevin.
     */
    public static function getPayByLinkKevinURL(): string
    {
        return self::getPaymentsURL(WoocommercePaymentMethods::PAY_BY_LINK_KEVIN);
    }

    /**
     * Get Pay by Link Kevin Enabled.
     */
    public static function getPayByLinkKevinEnabled(): bool
    {
        return (bool) ('yes' == self::getPaymentOption(WoocommercePaymentMethods::PAY_BY_LINK_KEVIN, 'enabled')) ?? false;
    }

    /**
     * Get Pay By Link Kevin Title.
     */
    public static function getPayByLinkKevinTitle(): string
    {
        return self::getPaymentOption(WoocommercePaymentMethods::PAY_BY_LINK_KEVIN, 'title') ?? '';
    }

    /**
     * Get Pay By Link Kevin Description.
     */
    public static function getPayByLinkKevinDescription(): string
    {
        return self::getPaymentOption(WoocommercePaymentMethods::PAY_BY_LINK_KEVIN, 'description') ?? '';
    }

    // PAY BY LINK

    /**
     * Get Pay By Link URL.
     */
    public static function getPayByLinkURL(): string
    {
        return self::getPaymentsURL(WoocommercePaymentMethods::PAY_BY_LINK);
    }

    /**
     * Get Pay By Link Enabled.
     */
    public static function getPayByLinkEnabled(): bool
    {
        return (bool) ('yes' == self::getPaymentOption(WoocommercePaymentMethods::PAY_BY_LINK, 'enabled')) ?? false;
    }

    /**
     * Get Pay By Link Title.
     */
    public static function getPayByLinkTitle(): string
    {
        return self::getPaymentOption(WoocommercePaymentMethods::PAY_BY_LINK, 'title') ?? '';
    }

    /**
     * Get Pay By Link Description.
     */
    public static function getPayByLinkDescription(): string
    {
        return self::getPaymentOption(WoocommercePaymentMethods::PAY_BY_LINK, 'description') ?? '';
    }

    // XPAY

    /**
     * Get XPay URL.
     */
    public static function getXpayURL(): string
    {
        return self::getPaymentsURL(WoocommercePaymentMethods::XPAY);
    }

    /**
     * Get XPay Enabled.
     */
    public static function getXpayEnabled(): bool
    {
        return (bool) ('yes' == self::getPaymentOption(WoocommercePaymentMethods::XPAY, 'enabled')) ?? false;
    }

    /**
     * Get XPay Title.
     */
    public static function getXpayTitle(): string
    {
        return self::getPaymentOption(WoocommercePaymentMethods::XPAY, 'title') ?? '';
    }

    /**
     * Get XPay Description.
     */
    public static function getXpayDescription(): string
    {
        return self::getPaymentOption(WoocommercePaymentMethods::XPAY, 'description') ?? '';
    }

    // PLUGIN

    /**
     * Get Store Current Time.
     *
     * @param bool|int $timestamp
     */
    public static function getStoreCurrentTime(
        string $format = 'Y-m-d H:i:s',
        $timestamp = false,
        bool $gmt = false,
        int $daysToAdd = 0,
        int $hoursToAdd = 0
    ): string {
        // Usa o timestamp atual se não for fornecido
        $adjustedTimestamp = false !== $timestamp ? $timestamp : time();

        // Ajusta o timestamp com dias e horas adicionais
        if (0 !== $daysToAdd || 0 !== $hoursToAdd) {
            $adjustedTimestamp = strtotime("+{$daysToAdd} days +{$hoursToAdd} hours", $adjustedTimestamp);
        }

        // Retorna o horário ajustado
        return date_i18n($format, $adjustedTimestamp, $gmt);
    }

    /**
     * Get SIBS Project.
     */
    public static function getSibsProject(): string
    {
        return self::SIBS_PROJECT;
    }

    /**
     * Get Plugin Version.
     */
    public static function getPluginVersion(): string
    {
        return constant('SIBS_VERSION') ?? '';
    }

    /**
     * Get Ecommerce Name.
     */
    public static function getEcommerceName(): string
    {
        return self::SIBS_ECOMMERCE;
    }

    /**
     * Get Ecommerce Version.
     */
    public static function getEcommerceVersion(): string
    {
        return constant('WC_VERSION') ?? '';
    }

    /**
     * Get Framework Version.
     */
    public static function getFrameworkVersion(): string
    {
        return get_bloginfo('version') ?? '';
    }

    /**
     * Get PHP Version.
     */
    public static function getPhpVersion(): string
    {
        return phpversion() ?? '';
    }

    /**
     * Get MSQL Version.
     */
    public static function getMysqlVersion(): string
    {
        return (new WordpressOptions())->getDatabaseVersion();
    }

    /**
     * Get Webhook URL.
     *
     * @param null|mixed $version
     */
    public static function getWebhookURL($version = null): string
    {
        if (in_array($version, WebhookVersions::all())) {
            return rest_url(Plugin::PLUGIN_PREFIX_NAME.'/'.$version.'/webhook');
        }

        return rest_url(Plugin::PLUGIN_PREFIX_NAME.'/webhook');
    }

    /**
     * Get Report a Bug URL.
     */
    public static function getReportBugUrl(): string
    {
        return self::REPORT_BUG_BASE_URL.'?plugin='.self::getFrameworkVersion()
            .'&plugin_version='.self::getPluginVersion()
            .'&php_version='.self::getPhpVersion()
            .'&client='.self::getClientId()
            .'&framework='.self::getEcommerceName()
            .'&project='.self::getSibsProject();
    }

    /**
     * Get Report Bug Script.
     */
    public static function getReportBugScriptUrl(): string
    {
        return self::REPORT_BUG_BASE_URL.'/src/assets/js/main.js';
    }

    /**
     * Set plugin woocomerce configuration option.
     *
     * @param mixed $value
     *
     * @return mixed
     *
     * @see https://developer.wordpress.org/reference/functions/get_option/
     */
    public static function setWoocommerceOption(string $fieldId, $value)
    {
        $sanitizedValue = sanitize_text_field($value);

        if (empty(get_option($fieldId))) {
            delete_option($fieldId);
            add_option($fieldId, $sanitizedValue);
        } else {
            update_option($fieldId, $sanitizedValue);
        }

        return true;
    }

    /**
     * Get plugin woocomerce configuration option.
     *
     * @param mixed $default
     *
     * @return mixed
     *
     * @see https://developer.wordpress.org/reference/functions/get_option/
     */
    public static function getWoocommerceOption(string $fieldId, $default = null)
    {
        // sibs woocommerce options
        return get_option($fieldId, $default) ?? null;
    }

    /**
     * Set plugin configuration option.
     *
     * @param mixed $value
     *
     * @return mixed
     *
     * @see https://developer.wordpress.org/reference/functions/get_option/
     */
    public static function setPluginOption(string $fieldId, $value)
    {
        $sanitizedValue = sanitize_text_field($value);

        if (empty(get_option($fieldId))) {
            delete_option(Plugin::PLUGIN_PREFIX.'_'.$fieldId);
            add_option(Plugin::PLUGIN_PREFIX.'_'.$fieldId, $sanitizedValue);
        } else {
            update_option(Plugin::PLUGIN_PREFIX.'_'.$fieldId, $sanitizedValue);
        }

        return true;
    }

    /**
     * Get plugin configuration option.
     *
     * @param mixed $default
     *
     * @return mixed
     *
     * @see https://developer.wordpress.org/reference/functions/get_option/
     */
    public static function getPluginOption(string $fieldId, $default = null)
    {
        // sibs plugin options
        return get_option(Plugin::PLUGIN_PREFIX.'_'.$fieldId, $default) ?? null;
    }

    /**
     * Set plugin style configuration option.
     *
     * @param mixed $value
     *
     * @return mixed
     *
     * @see https://developer.wordpress.org/reference/functions/get_option/
     */
    public static function setStyleOption(string $fieldId, $value)
    {
        $sanitizedValue = sanitize_text_field($value);

        if (empty(get_option($fieldId))) {
            delete_option(self::SIBS_STYLE_CONFIG.'_'.$fieldId);
            add_option(self::SIBS_STYLE_CONFIG.'_'.$fieldId, $sanitizedValue);
        } else {
            update_option(self::SIBS_STYLE_CONFIG.'_'.$fieldId, $sanitizedValue);
        }

        return true;
    }

    /**
     * Get plugin style configuration value.
     *
     * @param mixed $default
     *
     * @return mixed
     *
     * @see https://developer.wordpress.org/reference/functions/get_option/
     */
    public static function getStyleOption(string $fieldId, $default = null)
    {
        // sibs general options
        return get_option(self::SIBS_STYLE_CONFIG.'_'.$fieldId, $default) ?? null;
    }

    /**
     * Set plugin general configuration option.
     *
     * @param mixed $value
     *
     * @return mixed
     *
     * @see https://developer.wordpress.org/reference/functions/get_option/
     */
    public static function setGeneralOption(string $fieldId, $value)
    {
        $sanitizedValue = sanitize_text_field($value);

        if (empty(get_option($fieldId))) {
            delete_option(self::SIBS_GENERAL_CONFIG.'_'.$fieldId);
            add_option(self::SIBS_GENERAL_CONFIG.'_'.$fieldId, $sanitizedValue);
        } else {
            update_option(self::SIBS_GENERAL_CONFIG.'_'.$fieldId, $sanitizedValue);
        }

        return true;
    }

    /**
     * Get plugin general configuration value.
     *
     * @param mixed $default
     *
     * @return mixed
     *
     * @see https://developer.wordpress.org/reference/functions/get_option/
     */
    public static function getGeneralOption(string $fieldId, $default = null)
    {
        // sibs general options
        return get_option(self::SIBS_GENERAL_CONFIG.'_'.$fieldId, $default) ?? null;
    }

    /**
     * Set plugin payment configuration option.
     *
     * @param mixed $value
     *
     * @return mixed
     *
     * @see https://developer.wordpress.org/reference/functions/get_option/
     */
    public static function setPaymentOption(string $paymentId, ?string $fieldId = null, $value = null)
    {
        $sanitizedValue = sanitize_text_field($value);

        if (!in_array($paymentId, self::PAYMENTS)) {
            return null;
        }

        // TODO

        // sibs payment options
        // if (empty($fieldId)) {
        //     if (empty(get_option('woocommerce_' . $paymentId . '_settings'))) {
        //         delete_option('woocommerce_' . $paymentId . '_settings');
        //         add_option('woocommerce_' . $paymentId . '_settings', $sanitizedValue);
        //     } else {
        //         update_option('woocommerce_' . $paymentId . '_settings', $sanitizedValue);
        //     }
        // }

        // sibs payment specific option
        // if (empty(get_option('woocommerce_' . $paymentId . '_settings'))) {
        //     delete_option('woocommerce_' . $paymentId . '_settings');
        //     add_option('woocommerce_' . $paymentId . '_settings', $sanitizedValue);
        // } else {
        //     update_option('woocommerce_' . $paymentId . '_settings', $sanitizedValue);
        // }

        return false;
    }

    /**
     * Get plugin payment configuration value.
     *
     * @param mixed $default
     *
     * @return mixed
     *
     * @see https://developer.wordpress.org/reference/functions/get_option/
     */
    public static function getPaymentOption(string $paymentId, ?string $fieldId = null, $default = null)
    {
        if (!in_array($paymentId, self::PAYMENTS)) {
            return null;
        }

        // sibs payment options
        if (empty($fieldId)) {
            return get_option('woocommerce_'.$paymentId.'_settings', $default) ?? null;
        }

        // sibs payment specific option
        return get_option('woocommerce_'.$paymentId.'_settings', $default)[$fieldId] ?? null;
    }

    /**
     * Make Table name.
     */
    public static function makeTableName(string $tableName): string
    {
        global $wpdb;
        $tablePrefix = $wpdb->prefix.Plugin::PLUGIN_PREFIX;

        return $tablePrefix.'_'.$tableName;
    }

    /**
     * Get Transaction Table name.
     */
    public static function getTransactionTableName(): string
    {
        return self::makeTableName('transaction');
    }

    /**
     * Get Payment Information Table name.
     */
    public static function getPaymentInformationTableName(): string
    {
        return self::makeTableName('payment_information');
    }

    /**
     * Get Tokenization Table name.
     */
    public static function getTokenizationTableName(): string
    {
        return self::makeTableName('card_tokens');
    }

    /**
     * Get Webhook Call Table name.
     */
    public static function getWebhookCallTableName(): string
    {
        return self::makeTableName('webhook_retry');
    }

    /**
     * Check Database Health.
     */
    public static function checkDatabaseHealth(string $tableName): bool
    {
        global $wpdb;
        $query = $wpdb->prepare('SHOW TABLES LIKE %s', $wpdb->esc_like($tableName));
        $response = $wpdb->get_var($query);

        $isTableOk = !is_null($response);

        return $isTableOk;
    }

    /**
     * Get Plugin URL.
     *
     * @return string
     */
    public static function getPluginUrl(string $endpoint = '')
    {
        return constant('SIBS_PLUGIN_URL').$endpoint;
    }

    /**
     * Get Test Mode.
     *
     * @return string
     */
    public static function getTestMode()
    {
        if (Environments::PRD === self::getEnvironment()) {
            return false;
        }

        return 'EXTERNAL';
    }
}
