<?php

namespace Sibs2;

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 = sibsConstants::SIBS_PLUGIN_PREFIX . '_general';
    public const SIBS_STYLE_CONFIG   = sibsConstants::SIBS_PLUGIN_PREFIX . '_style';
    public const REPORT_BUG_BASE_URL = 'https://plugin-stargate.store/bug-report';
    public const PAYMENTS            = [
        sibsConstants::SIBS_PAYMENT_METHOD_ORDER_CREDIT_CARD,
        sibsConstants::SIBS_PAYMENT_METHOD_ORDER_BLIK,
        sibsConstants::SIBS_PAYMENT_METHOD_ORDER_PAY_BY_LINK,
        sibsConstants::SIBS_PAYMENT_METHOD_ORDER_PAY_BY_LINK_KEVIN,
        sibsConstants::SIBS_PAYMENT_METHOD_ORDER_XPAY,
    ];

    // URLS

    /**
     * @return string
     */
    public static function getSibsSettingsURL(): string
    {
        return admin_url('admin.php?page=sibs');
    }

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

    /**
     * @return string
     */
    public static function getPaymentsURL(): string
    {
        return admin_url('admin.php?page=wc-settings&tab=checkout');
    }

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

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

    // SETTINGS

    /**
     * @param int
     */
    public static function setTerminalId(int $terminalId)
    {
        self::setGeneralOption('merchant_no', $terminalId);
    }

    /**
     * @return ?int
     */
    public static function getTerminalId(): ?int
    {
        $terminalId = self::getGeneralOption('merchant_no');

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

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

    /**
     * @return string
     */
    public static function getClientId(): string
    {
        return self::getGeneralOption('client_id') ?? '';
    }

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

    /**
     * @return string
     */
    public static function getToken(): string
    {
        return self::getGeneralOption('bearer_token') ?? '';
    }

    /**
     * @param string
     */
    public static function setEnvironment(string $environment)
    {
        self::setGeneralOption('environment', $environment);
    }

    /**
     * @return string
     */
    public static function getEnvironment(): string
    {
        return self::getGeneralOption('environment') ?? 'CER';
    }

    /**
     * @param string
     */
    public static function setWebhookSecret(string $webhookSecret)
    {
        self::setGeneralOption('webhook_secret', $webhookSecret);
    }

    /**
     * @return string
     */
    public static function getWebhookSecret(): string
    {
        return self::getGeneralOption('webhook_secret') ?? '';
    }

    /**
     * @param string
     */
    public static function getLanguageDefault(): string
    {
        return self::getGeneralOption('language') ?? 'en';
    }

    /**
     * @param string
     */
    public static function setLanguageDefault(string $language)
    {
        self::setGeneralOption('language', $language);
    }

    /**
     * @return bool
     */
    public static function getMoto(): bool
    {
        return false;
    }

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

    // CREDITCARD

    /**
     * @return string
     */
    public static function getCreditCardURL(): string
    {
        return self::getPaymentsURL() . '&section=' . sibsConstants::SIBS_PAYMENT_METHOD_ORDER_CREDIT_CARD;
    }

    /**
     * @return bool
     */
    public static function getCreditCardEnabled(): bool
    {
        return (bool) (self::getPaymentOption(sibsConstants::SIBS_PAYMENT_METHOD_ORDER_CREDIT_CARD, 'enabled') == 'yes') ?? false;
    }

    /**
     * @return string
     */
    public static function getCreditCardTitle(): string
    {
        return self::getPaymentOption(sibsConstants::SIBS_PAYMENT_METHOD_ORDER_CREDIT_CARD, 'title') ?? 'false';
    }

    /**
     * @return string
     */
    public static function getCreditCardDescription(): string
    {
        return self::getPaymentOption(sibsConstants::SIBS_PAYMENT_METHOD_ORDER_CREDIT_CARD, 'description') ?? 'false';
    }

    /**
     * @return string
     */
    public static function getCreditCardTransactionMode(): string
    {
        return self::getPaymentOption(sibsConstants::SIBS_PAYMENT_METHOD_ORDER_CREDIT_CARD, 'transaction_mode') ?? '';
    }

    /**
     * @return array
     */
    public static function getCreditCardCardTypes(): array
    {
        return json_decode(self::getPaymentOption(sibsConstants::SIBS_PAYMENT_METHOD_ORDER_CREDIT_CARD, 'card_types'), true) ?? [];
    }

    // BLIK

    /**
     * @return string
     */
    public static function getBlikURL(): string
    {
        return self::getPaymentsURL() . '&section=' . sibsConstants::SIBS_PAYMENT_METHOD_ORDER_BLIK;
    }

    /**
     * @return bool
     */
    public static function getBlikEnabled(): bool
    {
        return (bool) (self::getPaymentOption(sibsConstants::SIBS_PAYMENT_METHOD_ORDER_BLIK, 'enabled') == 'yes') ?? false;
    }

    /**
     * @return string
     */
    public static function getBlikTitle(): string
    {
        return self::getPaymentOption(sibsConstants::SIBS_PAYMENT_METHOD_ORDER_BLIK, 'title') ?? '';
    }

    /**
     * @return string
     */
    public static function getBlikDescription(): string
    {
        return self::getPaymentOption(sibsConstants::SIBS_PAYMENT_METHOD_ORDER_BLIK, 'description') ?? '';
    }

    /**
     * @return string
     */
    public static function getBlikTransactionMode(): string
    {
        return self::getPaymentOption(sibsConstants::SIBS_PAYMENT_METHOD_ORDER_BLIK, 'transaction_mode') ?? '';
    }

    /**
     * @return string
     */
    public static function getBlikMandateType(): string
    {
        return self::getPaymentOption(sibsConstants::SIBS_PAYMENT_METHOD_ORDER_BLIK, 'mandate_type') ?? '';
    }

    // PAY BY LINK

    /**
     * @return string
     */
    public static function getPayByLinkURL(): string
    {
        return self::getPaymentsURL() . '&section=' . sibsConstants::SIBS_PAYMENT_METHOD_ORDER_PAY_BY_LINK_KEVIN;
    }

    /**
     * @return bool
     */
    public static function getPayByLinkEnabled(): bool
    {
        return (bool) (self::getPaymentOption(sibsConstants::SIBS_PAYMENT_METHOD_ORDER_PAY_BY_LINK_KEVIN, 'enabled') == 'yes') ?? false;
    }

    public static function getPayByLink2Enabled(): bool
    {
        return (bool) (self::getPaymentOption(sibsConstants::SIBS_PAYMENT_METHOD_ORDER_PAY_BY_LINK, 'enabled') == 'yes') ?? false;
    }

    /**
     * @return string
     */
    public static function getPayByLinkTitle(): string
    {
        return self::getPaymentOption(sibsConstants::SIBS_PAYMENT_METHOD_ORDER_PAY_BY_LINK_KEVIN, 'title') ?? '';
    }

    /**
     * @return string
     */
    public static function getPayByLinkDescription(): string
    {
        return self::getPaymentOption(sibsConstants::SIBS_PAYMENT_METHOD_ORDER_PAY_BY_LINK_KEVIN, 'description') ?? '';
    }

    // XPAY

    /**
     * @return string
     */
    public static function getXpayURL(): string
    {
        return self::getPaymentsURL() . '&section=' . sibsConstants::SIBS_PAYMENT_METHOD_ORDER_XPAY;
    }

    /**
     * @return bool
     */
    public static function getXpayEnabled(): bool
    {
        return (bool) (self::getPaymentOption(sibsConstants::SIBS_PAYMENT_METHOD_ORDER_XPAY, 'enabled') == 'yes') ?? false;
    }

    /**
     * @return string
     */
    public static function getXpayTitle(): string
    {
        return self::getPaymentOption(sibsConstants::SIBS_PAYMENT_METHOD_ORDER_XPAY, 'title') ?? '';
    }

    /**
     * @return string
     */
    public static function getXpayDescription(): string
    {
        return self::getPaymentOption(sibsConstants::SIBS_PAYMENT_METHOD_ORDER_XPAY, 'description') ?? '';
    }

    // PLUGIN

    /**
     * @param bool $format
     * @param int|bool $timestamp
     * @param bool $gmt
     * @return string
     */
    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 = $timestamp !== false ? $timestamp : time();

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

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

    /**
     * @return string
     */
    public static function getSibsProject(): string
    {
        return self::SIBS_PROJECT;
    }

    /**
     * @return string
     */
    public static function getPluginVersion(): string
    {
        return constant('SIBS_VERSION') ?? '';
    }

    /**
     * @return string
     */
    public static function getEcommerceName(): string
    {
        return self::SIBS_ECOMMERCE;
    }

    /**
     * @return string
     */
    public static function getEcommerceVersion(): string
    {
        return constant('WC_VERSION') ?? '';
    }

    /**
     * @return string
     */
    public static function getFrameworkVersion(): string
    {
        return get_bloginfo('version') ?? '';
    }

    /**
     * @return string
     */
    public static function getPhpVersion(): string
    {
        return phpversion() ?? '';
    }

    /**
     * @return string
     */
    public static function getMysqlVersion(): string
    {
        global $wpdb;

        return $wpdb->get_var('SELECT VERSION() AS version') ?? '';
    }

    /**
     * @param string $version
     * @return string
     */
    public static function getWebhookURL(): string
    {
        return rest_url(sibsConstants::SIBS_WEBHOOK_ENDPOINT);
    }

    /**
     * Get Report a Bug URL.
     *
     * @return string
     */
    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();
    }

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

    /**
     * set plugin woocomerce configuration option.
     *
     * @param string $fieldId
     * @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 string $fieldId
     * @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 string $fieldId
     * @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(sibsConstants::SIBS_PLUGIN_PREFIX . '_' . $fieldId);
            add_option(sibsConstants::SIBS_PLUGIN_PREFIX . '_' . $fieldId, $sanitizedValue);
        } else {
            update_option(sibsConstants::SIBS_PLUGIN_PREFIX . '_' . $fieldId, $sanitizedValue);
        }

        return true;
    }

    /**
     * Get plugin configuration option.
     *
     * @param string $fieldId
     * @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(sibsConstants::SIBS_PLUGIN_PREFIX . '_' . $fieldId, $default) ?? null;
    }

    /**
     * Set plugin style configuration option.
     *
     * @param string $fieldId
     * @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 string $fieldId
     * @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 string $fieldId
     * @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 string $fieldId
     * @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 string $paymentId
     * @param string $fieldId
     * @param mixed value
     * @return mixed
     *
     * @see https://developer.wordpress.org/reference/functions/get_option/
     */
    public static function setPaymentOption(string $paymentId, string $fieldId = null, $value)
    {
        $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 string $fieldId
     * @param string $groupId Possible values:
     *                              - sibs_stg_cc
     *                              - sibs_stg_blik
     *                              - sibs_stg_pblkv
     *                              - sibs_stg_xpay
     * @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.
     *
     * @param string $tableName
     * @return string
     */
    public static function makeTableName(string $tableName): string
    {
        global $wpdb;
        $tablePrefix = $wpdb->prefix . sibsConstants::SIBS_PLUGIN_PREFIX;

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

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

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

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

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

    /**
     * Check Database Health.
     *
     * @param string $tableName
     * @return bool
     */
    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;
    }
}
