<?php

namespace Sibs\Stargate\Admin;

use Exception;
use Sibs\Stargate\Config\SibsConfig;
use Sibs\Stargate\Constants\IntegrationTypes;
use Sibs\Stargate\Constants\Languages;
use Sibs\Stargate\Constants\Logs;
use Sibs\Stargate\Constants\Plugin;
use Sibs\Stargate\Exceptions\SibsException;
use Sibs\Stargate\Loggers\SibsLogger;
use Sibs\Stargate\Utils\SibsBrowser;
use Sibs\Stargate\Utils\SibsEnvironment;
use Sibs\Stargate\Webhooks\SibsWebhookDecryptor;

defined('ABSPATH') || exit;

class SibsGeneralSettings
{
    /**
     * Page Hook.
     */
    private string $page_hook;

    /**
     * Init.
     */
    public function init()
    {
        // Register menu
        add_action('admin_menu', [$this, 'registerMenu']);
    }

    /**
     * Register Menu.
     */
    public function registerMenu()
    {
        $this->page_hook = add_submenu_page(
            'woocommerce',
            __('SIBS Settings', 'sibs-woo-stg'),
            __('SIBS Settings', 'sibs-woo-stg'),
            'manage_options',
            'sibs_settings',
            [$this, 'renderPage'],
            3
        );

        add_action('admin_enqueue_scripts', [$this, 'enqueueAssets']);
    }

    /**
     * Enqueue Assets.
     *
     * @param mixed $hook
     */
    public function enqueueAssets($hook)
    {
        if ($hook !== $this->page_hook) {
            return;
        }

        // Bootstrap CSS
        wp_enqueue_style(
            'sibs_bootstrap_css',
            'https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css',
            [],
            '5.3.3'
        );

        // Bootstrap JS
        wp_enqueue_script(
            'sibs_bootstrap_js',
            'https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js',
            ['jquery'],
            '5.3.3',
            true
        );

        // Adiciona o arquivo de CSS personalizado
        wp_enqueue_style('admin_style', constant('SIBS_PLUGIN_URL').'assets/css/admin-style.css', []);
        wp_enqueue_style('sibs_admin_style', constant('SIBS_PLUGIN_URL').'assets/css/sibs-admin-style.css', []);
    }

    /**
     * Save Data.
     *
     * @param mixed $post
     */
    public function saveData($post)
    {
        SibsConfig::setTerminalId($post[SibsConfig::SIBS_GENERAL_CONFIG.'_merchant_no']);
        SibsConfig::setClientId($post[SibsConfig::SIBS_GENERAL_CONFIG.'_client_id']);
        SibsConfig::setToken($post[SibsConfig::SIBS_GENERAL_CONFIG.'_bearer_token']);
        SibsConfig::setEnvironment($post[SibsConfig::SIBS_GENERAL_CONFIG.'_environment']);
        SibsConfig::setWebhookSecret($post[SibsConfig::SIBS_GENERAL_CONFIG.'_webhook_secret']);
        SibsConfig::setForceDisableClickToPay($post[SibsConfig::SIBS_GENERAL_CONFIG.'_force_disable_click_to_pay']);
        SibsConfig::setLanguageDefault($post[SibsConfig::SIBS_GENERAL_CONFIG.'_language']);
        // SibsConfig::setIntegrationType($post[SibsConfig::SIBS_GENERAL_CONFIG.'_integration_type']);

        return true;
    }

    /**
     * Render Page.
     */
    public function renderPage()
    {
        $saved = (isset($_POST['sibs_save'])) ? $this->saveData($_POST) : false;

        $environment_file = new SibsEnvironment();
        $environments = $environment_file->get_environments();

        $this->handleApplePayUpload();

        ?>
        <script type="text/javascript">
           urlAPISIBS = "<?php echo plugins_url('sibs-woo-stg'); ?>";
           urlStore = "<?php echo site_url(); ?>";
           prefix = "<?php echo Plugin::PLUGIN_PREFIX; ?>";
           ambiente = "<?php echo implode(',', $environments); ?>";
        </script>

        <div class="container px-3 py-4">

            <?php $this->renderHeader(); ?>
            <?php $this->renderSuccessMessage($saved); ?>

            <div class="row">
                <div class="col-lg-7">
                    <?php $this->renderForm($environments); ?>
                </div>

                <div class="col-lg-5 small">
                    <?php $this->renderSidebar(); ?>
                </div>
            </div>
        </div>

        <div class="lds-ring"></div>
        <?php
    }

    /**
     * Webhook Description.
     *
     * @return string
     */
    public static function webhookDescription()
    {
        return sprintf(
            // translators: Webhook Url
            __(
                'Provide this WebHook URL %s to your SIBS point of contact.',
                'sibs-woo-stg'
            ),
            '<code>'.SibsConfig::getWebhookURL().'</code>'
        );
    }

    /**
     * Add SIBS Settings page report feedback.
     */
    public function reportFeedback()
    {
        ?>
            <div class="report_feedback">
                <script type="text/javascript">
                    window.SIBS_VERSION = "<?php echo SibsConfig::getFrameworkVersion(); ?>";
                    window.SIBS_PLUGIN_VERSION = "<?php echo SibsConfig::getPluginVersion(); ?>";
                    window.SIBS_PHP_VERSION = "<?php echo SibsConfig::getPhpVersion(); ?>";
                    window.SIBS_CLIENT = "<?php echo SibsConfig::getClientId(); ?>";
                    window.SIBS_FRAMEWORK = "<?php echo SibsConfig::getEcommerceName(); ?>";
                    window.SIBS_PROJECT = "<?php echo SibsConfig::getSibsProject(); ?>";
                    window.SIBS_URL_REPORT = "<?php echo SibsConfig::getReportBugUrl(); ?>";
                </script>
                <script src="<?php echo SibsConfig::getReportBugScriptUrl(); ?>" id="sibs_bug_report_script-js"></script>
                <button class="button-secondary modal__button" id="sibs-open-modal">
                    <?php echo __('Report', 'sibs-woo-stg'); ?>
                </button>
            </div>
        <?php
    }

    /**
     * Get Test Decryptor.
     */
    public function getTestDecryptor(): SibsWebhookDecryptor
    {
        $iv = '000000000000000000000000';
        $authTag = 'CE573FB7A41AB78E743180DC83FF09BD';
        $content = '0A3471C72D9BE49A8520F79C66BBD9A12FF9';
        $secret = '000102030405060708090a0b0c0d0e0f000102030405060708090a0b0c0d0e0f';

        $sibsWebhookDecryptor = new SibsWebhookDecryptor($content, $iv, $authTag, $secret);

        return $sibsWebhookDecryptor->setSuppressLog(true);
    }

    /**
     * Get Entity Available.
     */
    public function getEntityAvailable(string $entity): bool
    {
        $testDecryptor = $this->getTestDecryptor();

        switch ($entity) {
            case 'sodium':
                return $testDecryptor->canSodiumUseAeadAes256Gcm();

            case 'libsodium':
                return $testDecryptor->canLibSodiumUseAeadAes256Gcm();

            case 'sodium_compact':
                return $testDecryptor->canSodiumCompactUseAeadAes256Gcm();

            case 'open_ssl':
                return $testDecryptor->canOpenSSLUseAeadAes256Gcm();

            case 'all':
            default:
                return $testDecryptor->canUseAes256Gcm();
        }
    }

    /**
     * Get Entity Enable.
     */
    public function getEntityEnable(string $entity): bool
    {
        switch ($entity) {
            case 'creditcard':
                return SibsConfig::getCreditCardEnabled();

            case 'blik':
                return SibsConfig::getBlikEnabled();

            case 'pblkv':
                return SibsConfig::getPayByLinkKevinEnabled();

            case 'pbl':
                return SibsConfig::getPayByLinkEnabled();

            case 'xpay':
                return SibsConfig::getXpayEnabled();

            default:
                return false;
        }
    }

    /**
     * Available Message.
     */
    public function availableMessage(string $entity)
    {
        $isAvailable = $this->getEntityAvailable($entity);

        return $isAvailable
            ? $this->statusBadge(__('Available', 'sibs-woo-stg'), 'green')
            : $this->statusBadge(__('Not Available', 'sibs-woo-stg'), 'red');
    }

    /**
     * Deprecation Message.
     */
    public function deprecationMessage(string $message, bool $isDeprecated = false)
    {
        if ($isDeprecated) {
            return $this->statusBadge(
                "{$message} (".__('Deprecated', 'sibs-woo-stg').')',
                'red'
            );
        }

        return $this->statusBadge($message, 'blue');
    }

    /**
     * Get Enable Message.
     */
    public function enabledMessage(string $entity)
    {
        $isEnable = $this->getEntityEnable($entity);

        return $isEnable
            ? $this->statusBadge(__('Enabled', 'sibs-woo-stg'), 'green')
            : $this->statusBadge(__('Not Enabled', 'sibs-woo-stg'), 'gray');
    }

    /**
     * Get Table Ok Message.
     */
    public function tableOkMessage(string $tableName)
    {
        $isTableOk = SibsConfig::checkDatabaseHealth($tableName);

        return $isTableOk
            ? $this->statusBadge(__('Ok', 'sibs-woo-stg'), 'green')
            : $this->statusBadge(__('Not Ok', 'sibs-woo-stg'), 'red');
    }

    /**
     * Add SIBS Settings page sodium description.
     */
    public function getDecryptionTest()
    {
        $testDecryptor = $this->getTestDecryptor();

        try {
            $testDecryptor->execute();

            return $this->statusBadge(
                __('Decrypt Success', 'sibs-woo-stg'),
                'green'
            );
        } catch (SibsException $e) {
            return $this->statusBadge(
                __('Error to decrypt', 'sibs-woo-stg'),
                'red'
            );
        }
    }

    /**
     * MySQL Deprecation Message.
     *
     * @return bool
     */
    public function mysqlVersionDeprecated()
    {
        return version_compare(SibsConfig::getMysqlVersion(), Plugin::DEPRECATION_MYSQL_VERSION, '<');
    }

    /**
     * PHP Deprecation Message.
     *
     * @return bool
     */
    public function phpVersionDeprecated()
    {
        return version_compare(SibsConfig::getPhpVersion(), Plugin::DEPRECATION_PHP_VERSION, '<');
    }

    /**
     * Wordpress Deprecation Message.
     *
     * @return bool
     */
    public function wordpressVersionDeprecated()
    {
        return version_compare(SibsConfig::getFrameworkVersion(), Plugin::DEPRECATION_WORDPRESS_VERSION, '<');
    }

    /**
     * Woocommerce Deprecation Message.
     *
     * @return bool
     */
    public function woocommerceVersionDeprecated()
    {
        return version_compare(SibsConfig::getEcommerceVersion(), Plugin::DEPRECATION_WOOCOMMERCE_VERSION, '<');
    }

    /**
     * Wizard Login Section.
     */
    public function wizardLogin()
    {
        ?>
            <div id="div-login-sibs" class="sibs-section-content">
                <div id="divLoginSibs">
                    <form id="formLoginSibs">
                        <table class="form-table" role="presentation">
                            <thead>
                                <tr>
                                    <th scope="row" colspan="2">
                                        <h2><?php echo __('Login to your SIBS Backoffice', 'sibs-woo-stg'); ?></h2>
                                    </th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td scope="row">
                                        <label for="loginSibs">
                                            <?php echo __('E-mail', 'sibs-woo-stg'); ?>
                                        </label> 
                                        <input type="text" value="" placeholder="<?php echo __('Type your e-mail', 'sibs-woo-stg'); ?>"
                                            id="loginSibs"/>
                                        <span id="errorLoginSibs" class="error"></span>
                                    </td>
                                    <td scope="row">
                                        <label for="passwordSibs">
                                            <?php echo __('Password', 'sibs-woo-stg'); ?>
                                        </label>
                                        <input type="password" value="" placeholder="<?php echo __('Enter your password', 'sibs-woo-stg'); ?>"
                                            id="passwordSibs"/>
                                        <span id="errorPassSibs" class="error"></span>
                                    </td>
                                </tr>
                                <tr>
                                    <td scope="row" colspan="2">
                                        <label for="fenvironment">
                                            <?php echo __('Environment', 'sibs-woo-stg'); ?>
                                        </label> 
                                        <select name="fenvironment" id="fenvironment"></select>
                                        <span id="errorEnvironmentSibs" class="error"></span>
                                    </td>
                                </tr>
                            </tbody>
                            <tfoot>
                                <tr>
                                    <td scope="row" colspan="2">
                                        <button type="button" class="button button-primary" id="firstLoginSibs">
                                            <?php echo __('Login', 'sibs-woo-stg'); ?>
                                        </button>
                                    </td>
                                </tr>
                            </tfoot>
                        </table>
                    </form>
                </div>
                <div id="activateLoginSibs">
                    <form id="formActvateLoginSibs">
                        <table class="form-table" role="presentation">
                            <thead>
                                <tr>
                                    <th scope="row">
                                        <h2><?php echo __('Enter the activation code you received via SMS', 'sibs-woo-stg'); ?></h2>
                                    </th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td scope="row">
                                        <label for="activationCode">
                                            <?php echo __('Activation Code', 'sibs-woo-stg'); ?>
                                        </label>
                                        <input type="text" value="" placeholder="<?php echo __('Enter your activation code', 'sibs-woo-stg'); ?>"
                                            id="activationCode"/>
                                        <span id="errorActivationCode" class="error"> </span>
                                    </td>
                                </tr>
                            </tbody>
                            <tfoot>
                                <tr>
                                    <td scope="row">
                                        <button type="button" class="button button-secondary" id="requestNewcode" class="whiteButton">
                                            <?php echo __('Request new code', 'sibs-woo-stg'); ?>
                                        </button>
                                        <button type="button" class="button button-primary" id="secondLoginSibs">
                                            <?php echo __('Confirm', 'sibs-woo-stg'); ?>
                                        </button>
                                    </td>
                                </tr>
                            </tfoot>
                        </table>
                    </form>
                </div>
            </div>
        <?php
    }

    /**
     * Wizard Terminal Section.
     */
    public function wizardTerminal()
    {
        ?>
            <div id="div-terminal-sibs" class="sibs-section-content">
                <table class="form-table" role="presentation">
                    <thead>
                        <tr>
                            <th scope="row">
                                <h2><?php echo __('Select the terminal you want to configure', 'sibs-woo-stg'); ?></h2>
                            </th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td scope="row">
                                <select id="selectTerminalOptions">
                                    <option value=""><?php echo __('Loading', 'sibs-woo-stg'); ?>...</option>
                                </select>
                                <span id="errorSelectTerminalOptions" class="error"> </span>
                            </td>
                        </tr>
                    </tbody>
                    <tfoot>
                        <tr>
                            <td scope="row">
                                <button type="button" class="button button-primary" id="terminalTabButton">
                                    <?php echo __('Next', 'sibs-woo-stg'); ?>
                                </button>
                            </td>
                        </tr>
                    </tfoot>
                </table>
            </div>
        <?php
    }

    /**
     * Wizard Webhook Section.
     */
    public function wizardWebhooks()
    {
        ?>
            <div id="div-webhooks-sibs" class="sibs-section-content">
                <table class="form-table" role="presentation">
                    <thead>
                        <tr>
                            <th scope="row" colspan="2">
                                <h2><?php echo __('Check the data and change the Webhook if necessary', 'sibs-woo-stg'); ?></h2>
                            </th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td scope="row" colspan="2">
                                <select id="selectClientIDWebhookSecret" class="sibsWizardSelectField">
                                    <option value=""><?php echo __('Loading', 'sibs-woo-stg'); ?>...</option>
                                </select>
                                <span id="errorSelectClientIDWebhookSecret" class="error"> </span>
                            </td>
                        </tr>
                        <tr>
                            <td scope="row">
                                <label for="unconfirmedIdTerminal"><?php echo __('Terminal ID', 'sibs-woo-stg'); ?></label>
                                <input type="text" placeholder="<?php echo __('Terminal ID', 'sibs-woo-stg'); ?>"
                                    id="unconfirmedIdTerminal" class="sibsBlockedField"/>
                            </td>
                            <td scope="row">
                                <label for="unconfirmedClientId"><?php echo __('Client ID', 'sibs-woo-stg'); ?></label>
                                <input type="text" placeholder="<?php echo __('Client ID', 'sibs-woo-stg'); ?>"
                                    id="unconfirmedClientId" class="sibsBlockedField"/>
                            </td>
                        </tr>
                        <tr>
                            <td scope="row">
                                <label for="unconfirmedBearerToken"><?php echo __('Bearer Token', 'sibs-woo-stg'); ?></label>
                                <textarea placeholder="<?php echo __('Bearer Token', 'sibs-woo-stg'); ?>"
                                    id="unconfirmedBearerToken" class="sibsBlockedField" rows="7"></textarea>
                            </td>
                            <td scope="row" class="sibsWizardTdWithTextArea">
                                <label for="unconfirmedWebhookSecret"><?php echo __('WebHook Secret', 'sibs-woo-stg'); ?></label>
                                <input type="text" placeholder="<?php echo __('WebHook Secret', 'sibs-woo-stg'); ?>"
                                    id="unconfirmedWebhookSecret" class="sibsBlockedField"/>
                            </th>
                        </tr>
                    </tbody>
                    <tfoot>
                        <tr>
                            <td scope="row" colspan="2">
                                <button type="button" class="button button-secondary" class="previousWizard whiteButton">
                                    <?php echo __('Back', 'sibs-woo-stg'); ?>
                                </button>
                                <button type="button" class="button button-primary" id="unconfirmedData">
                                    <?php echo __('Finish', 'sibs-woo-stg'); ?>
                                </button>
                            </td>
                        </tr>
                    </tfoot>
                </table>
            </div>
        <?php
    }

    /**
     * Render Header.
     */
    private function renderHeader()
    {
        ?>
        <div class="row align-items-center mb-4">
            <div class="col-md-2 col-12 text-center text-md-start">
                <img src="<?php echo esc_attr(plugins_url('sibs-woo-stg/assets/images/logo.png')); ?>" class="img-fluid" style="max-height:60px;">
            </div>
            <div class="col-md-10 col-12 text-center text-md-start">
                <h2><?php echo __('Settings', 'sibs-woo-stg'); ?></h2>
            </div>
        </div>
        <?php
    }

    /**
     * Render Success Message.
     *
     * @param mixed $saved
     */
    private function renderSuccessMessage($saved)
    {
        if (isset($_POST['sibs_save']) && $saved) {
            ?>
            <div class="notice notice-success mb-3">
                <p><strong><?php echo __('Your settings have been saved.', 'sibs-woo-stg'); ?></strong></p>
            </div>
            <?php
        }
    }

    /**
     * Render Form.
     *
     * @param mixed $environment
     */
    private function renderForm($environment)
    {
        ?>
        <form method="POST" enctype="multipart/form-data" class="sibs-settings-form">
            <?php $this->renderTerminalSettings($environment); ?>
            <?php $this->renderFormSettings(); ?>
            <?php $this->renderApplePaySettings(); ?>

            <p class="text-center">
                <button class="button button-primary" type="submit" name="sibs_save">
                    <?php echo __('Save Changes', 'sibs-woo-stg'); ?>
                </button>
            </p>
        </form>
        <?php
    }

    /**
     * Render Terminal Settings.
     *
     * @param mixed $environment
     */
    private function renderTerminalSettings($environment)
    {
        ?>
        <div class="postbox p-3 mb-3 border rounded-3 bg-light">
            <h3 class="mb-3">
                <?php echo __('Terminal Settings', 'sibs-woo-stg'); ?>
            </h3>

            <hr/>

            <!-- Terminal Code -->
            <?php $this->formGroupStart(__('Terminal Code', 'sibs-woo-stg')); ?>
                <input type="text"
                    class="form-control"
                    name="<?php echo SibsConfig::SIBS_GENERAL_CONFIG.'_merchant_no'; ?>"
                    value="<?php echo esc_attr(SibsConfig::getTerminalId()); ?>"
                    required>
            <?php $this->formGroupEnd(); ?>

            <!-- Client ID -->
            <?php $this->formGroupStart(__('Client ID', 'sibs-woo-stg')); ?>
                <input type="text"
                    class="form-control"
                    name="<?php echo SibsConfig::SIBS_GENERAL_CONFIG.'_client_id'; ?>"
                    value="<?php echo esc_attr(SibsConfig::getClientId()); ?>"
                    required>
            <?php $this->formGroupEnd(); ?>

            <!-- Bearer Token -->
            <?php $this->formGroupStart(__('Bearer Token', 'sibs-woo-stg')); ?>
                <textarea class="form-control"
                        rows="4"
                        name="<?php echo SibsConfig::SIBS_GENERAL_CONFIG.'_bearer_token'; ?>"
                        required><?php echo esc_textarea(SibsConfig::getToken()); ?></textarea>
            <?php $this->formGroupEnd(); ?>

            <!-- Environment -->
            <?php $this->formGroupStart(__('Environment', 'sibs-woo-stg')); ?>
                <select class="form-select"
                        name="<?php echo SibsConfig::SIBS_GENERAL_CONFIG.'_environment'; ?>">
                    <?php foreach ($environment as $key => $value) { ?>
                        <option value="<?php echo esc_attr($key); ?>"
                            <?php selected($key, SibsConfig::getEnvironment()); ?>>
                            <?php echo esc_html($value); ?>
                        </option>
                    <?php } ?>
                </select>
            <?php $this->formGroupEnd(); ?>

            <!-- SIBS WebHook Secret -->
            <?php $this->formGroupStart(__('SIBS WebHook Secret', 'sibs-woo-stg')); ?>
                <input class="form-control" type="text"
                    id="<?php echo SibsConfig::SIBS_GENERAL_CONFIG.'_webhook_secret'; ?>"
                    name="<?php echo SibsConfig::SIBS_GENERAL_CONFIG.'_webhook_secret'; ?>"
                    value="<?php echo esc_attr(SibsConfig::getWebhookSecret()); ?>">
                <div class="form-text mt-3">
                    <?php echo $this->webhookDescription(); ?>
                </div>
            <?php $this->formGroupEnd(); ?>

            <!-- Force Disable Click To Pay -->
            <?php $this->formGroupStart(__('Force Disable Click to Pay', 'sibs-woo-stg')); ?>
                <select id="<?php echo SibsConfig::SIBS_GENERAL_CONFIG.'_force_disable_click_to_pay'; ?>"
                        name="<?php echo SibsConfig::SIBS_GENERAL_CONFIG.'_force_disable_click_to_pay'; ?>"
                        class="form-control">
                    <option value="0" <?php echo '0' == SibsConfig::getForceDisableClickToPay() ? 'selected' : ''; ?>>
                        <?php echo __('No', 'sibs-woo-stg'); ?>
                    </option>
                    <option value="1" <?php echo '1' == SibsConfig::getForceDisableClickToPay() ? 'selected' : ''; ?>>
                        <?php echo __('Yes', 'sibs-woo-stg'); ?>
                    </option>
                </select>
                <div class="form-text mt-3">
                    <?php echo __('If enabled, Click to Pay will be forcibly disabled for this terminal.', 'sibs-woo-stg'); ?>
                </div>
            <?php $this->formGroupEnd(); ?>
        </div>
        <?php
    }

    /**
     * Render Form Settings.
     */
    private function renderFormSettings()
    {
        $languages = [
            Languages::ENGLISH => __('English', 'sibs-woo-stg'),
            Languages::CZECH => __('Czech', 'sibs-woo-stg'),
            Languages::GERMAN => __('German', 'sibs-woo-stg'),
            Languages::FRENCH => __('French', 'sibs-woo-stg'),
            Languages::DUCTH => __('Dutch', 'sibs-woo-stg'),
            Languages::POLISH => __('Polish', 'sibs-woo-stg'),
        ];
        $integrationType = [
            IntegrationTypes::REDIRECT => __('Redirect', 'sibs-woo-stg'),
            IntegrationTypes::INLINE => __('Inline', 'sibs-woo-stg'),
        ];
        ?>
        <div class="postbox p-3 mb-3 border rounded-3 bg-light">
            <h3 class="mb-3">
                <?php echo __('Form Settings', 'sibs-woo-stg'); ?>
            </h3>

            <hr/>

            <!-- Language -->
            <?php $this->formGroupStart(__('Language', 'sibs-woo-stg')); ?>
                <select class="form-select"
                        name="<?php echo SibsConfig::SIBS_GENERAL_CONFIG.'_language'; ?>">
                    <?php foreach ($languages as $key => $value) { ?>
                        <option value="<?php echo esc_attr($key); ?>"
                            <?php selected($key, SibsConfig::getLanguageDefault()); ?>>
                            <?php echo esc_html($value); ?>
                        </option>
                    <?php } ?>
                </select>
            <?php $this->formGroupEnd(); ?>

            <!-- Integration Type -->
            <!--<?php $this->formGroupStart(__('Integration Type', 'sibs-woo-stg')); ?>
                <select class="form-select"
                        name="<?php echo SibsConfig::SIBS_GENERAL_CONFIG.'_integration_type'; ?>">
                    <?php foreach ($integrationType as $key => $value) { ?>
                        <option value="<?php echo esc_attr($key); ?>"
                            <?php selected($key, SibsConfig::getIntegrationType()); ?>>
                            <?php echo esc_html($value); ?>
                        </option>
                    <?php } ?>
                </select>
                <div class="form-text mt-3">                    
                    <?php echo __('Choose how the payment form is displayed.', 'sibs-woo-stg'); ?>
                </div>
            <?php $this->formGroupEnd(); ?>-->
        </div>
        <?php
    }

    /**
     * Render Apple Pay Settings.
     */
    private function renderApplePaySettings()
    {
        ?>
        <div class="postbox p-3 mb-3 border rounded-3 bg-light">
            <h3 class="mb-3">
                <?php echo __('Apple Pay Settings', 'sibs-woo-stg'); ?>
            </h3>

            <hr/>

            <div class="mb-3">
                <p class="text-muted mb-1">
                    <?php echo __('To learn more about how to do this, visit our', 'sibs-woo-stg'); ?>
                    <a href="https://www.docs.pay.sibs.com/payment-methods/apple-pay/" target="_blank">
                        <?php echo __('documentation', 'sibs-woo-stg'); ?>
                    </a>.
                </p>
            </div>

            <?php $this->formGroupStart(__('Merchant Domain Association', 'sibs-woo-stg')); ?>
                <input type="file"
                    class="form-control mb-3"
                    name="<?php echo SibsConfig::SIBS_GENERAL_CONFIG.'_merchant_domain_association'; ?>">
                <p class="text-muted mb-0">
                    <?php echo __('Please add the file provided by Apple for the validation of payments via Apple Pay on the site.', 'sibs-woo-stg'); ?>
                </p>
            <?php $this->formGroupEnd(); ?>
        </div>
        <?php
    }

    /**
     * Render Sidebar.
     */
    private function renderSidebar()
    {
        $browser = new SibsBrowser($_SERVER['HTTP_USER_AGENT'] ?? '');

        $this->renderInfoBox(
            __('System Informations', 'sibs-woo-stg'),
            function () {
                $this->renderVersionInfo();
            }
        );

        $this->renderInfoBox(
            __('Decryption Informations', 'sibs-woo-stg'),
            function () {
                $this->renderDecryptionInfo();
            }
        );

        $this->renderInfoBox(
            __('Other Informations', 'sibs-woo-stg'),
            function () {
                $this->renderOtherInfo();
            }
        );

        $this->renderInfoBox(
            __('Browser Informations', 'sibs-woo-stg'),
            function () use ($browser) {
                $this->renderBrowserInfo($browser);
            }
        );
    }

    /**
     * Render Version Info.
     */
    private function renderVersionInfo()
    {
        $data = [
            __('MySQL Version', 'sibs-woo-stg') => $this->deprecationMessage(SibsConfig::getMysqlVersion(), $this->mysqlVersionDeprecated()) ?? '—',
            __('PHP Version', 'sibs-woo-stg') => $this->deprecationMessage(SibsConfig::getPhpVersion(), $this->phpVersionDeprecated()) ?? '—',
            __('Wordpress Version', 'sibs-woo-stg') => $this->deprecationMessage(SibsConfig::getFrameworkVersion(), $this->wordpressVersionDeprecated()) ?? '—',
            __('Woocommerce Version', 'sibs-woo-stg') => $this->deprecationMessage(SibsConfig::getEcommerceVersion(), $this->woocommerceVersionDeprecated()) ?? '—',
            __('SIBS Plugin Version', 'sibs-woo-stg') => $this->deprecationMessage(SibsConfig::getPluginVersion(), false) ?? '—',
            __('Wordpress Universal hour', 'sibs-woo-stg') => SibsConfig::getStoreCurrentTime('Y-m-d H:i:s', false, true) ?? '—',
            __('Wordpress Local hour', 'sibs-woo-stg') => wp_date('Y-m-d H:i:s') ?? '—',
            __('Wordpress Local hour for SIBS', 'sibs-woo-stg') => wp_date('Y-m-d\TH:i:s.vP') ?? '—',
        ];

        foreach ($data as $label => $value) {
            $this->infoRow($label, $value);
        }
    }

    /**
     * Render Other Info.
     */
    private function renderOtherInfo()
    {
        ?>
        <h6 class="mb-3">
            <?php echo __('Enabled Payment Methods', 'sibs-woo-stg'); ?>
            <a href="<?php echo SibsConfig::getPaymentsURL(); ?>">
                <span class="dashicons dashicons-money-alt"
                    style="text-decoration: none;vertical-align: middle; font-size: 17px;">
                </span>
            </a>
        </h6>
        <?php

        $data = [
            __('Credit Card', 'sibs-woo-stg') => [
                $this->enabledMessage('creditcard'),
                SibsConfig::getCreditCardURL(),
            ],
            __('BLIK', 'sibs-woo-stg') => [
                $this->enabledMessage('blik'),
                SibsConfig::getBlikURL(),
            ],
            /* __('Pay by Link kevin', 'sibs-woo-stg') => [
                $this->enabledMessage('pblkv'),
                SibsConfig::getPayByLinkURL()
            ],*/
            __('Pay by Link', 'sibs-woo-stg') => [
                $this->enabledMessage('pbl'),
                SibsConfig::getPayByLinkURL(),
            ],
            __('Xpay', 'sibs-woo-stg') => [
                $this->enabledMessage('xpay'),
                SibsConfig::getXpayURL(),
            ],
        ];

        foreach ($data as $label => $item) {
            $this->infoRow($label, $item[0] ?? '—', $item[1] ?? null);
        }

        ?>
        <h6 class="mt-3 mb-3">
            <?php echo __('Database Health', 'sibs-woo-stg'); ?>
        </h6>
        <?php

        $data = [
            SibsConfig::getTransactionTableName() => $this->tableOkMessage(SibsConfig::getTransactionTableName()) ?? '—',
            SibsConfig::getPaymentInformationTableName() => $this->tableOkMessage(SibsConfig::getPaymentInformationTableName()) ?? '—',
            SibsConfig::getTokenizationTableName() => $this->tableOkMessage(SibsConfig::getTokenizationTableName()) ?? '—',
            SibsConfig::getWebhookCallTableName() => $this->tableOkMessage(SibsConfig::getWebhookCallTableName()) ?? '—',
        ];

        foreach ($data as $label => $value) {
            $this->infoRow($label, $value);
        }

        ?>
        <!--<h6 class="mt-3 mb-3">
            <?php echo __('Report a Feedback or a Bug', 'sibs-woo-stg'); ?>
        </h6>
        <?php $this->reportFeedback(); ?>-->
        <?php
    }

    /**
     * Render Decryption Info.
     */
    private function renderDecryptionInfo()
    {
        ?>
        <h6 class="mb-3">
            <?php echo __('Decryption Methods', 'sibs-woo-stg'); ?>
        </h6>
        <?php

        $data = [
            __('Sodium Extension', 'sibs-woo-stg') => $this->availableMessage('sodium') ?? '—',
            __('LibSodium Extension', 'sibs-woo-stg') => $this->availableMessage('libsodium') ?? '—',
            __('Sodium Compact', 'sibs-woo-stg') => $this->availableMessage('sodium_compact') ?? '—',
            __('Open SSL Extension', 'sibs-woo-stg') => $this->availableMessage('open_ssl') ?? '—',
        ];

        foreach ($data as $label => $value) {
            $this->infoRow($label, $value);
        }

        ?>
        <h6 class="mt-3 mb-3">
            <?php echo __('Decryption Availability', 'sibs-woo-stg'); ?>
        </h6>
        <?php

        $data = [
            __('Webhook Decryption', 'sibs-woo-stg') => $this->availableMessage('all') ?? '—',
            __('Webhook Decryption Test', 'sibs-woo-stg') => $this->getDecryptionTest() ?? '—',
        ];

        foreach ($data as $label => $value) {
            $this->infoRow($label, $value);
        }
    }

    /**
     * Render Browser Info.
     */
    private function renderBrowserInfo(SibsBrowser $browser)
    {
        $data = [
            __('Browser', 'sibs-woo-stg') => $browser->getBrowser() ?? '—',
            __('Version', 'sibs-woo-stg') => $browser->getVersion() ?? '—',
            __('Platform', 'sibs-woo-stg') => $browser->getPlatform() ?? '—',
            __('User Agent', 'sibs-woo-stg') => $_SERVER['HTTP_USER_AGENT'] ?? '—',
        ];

        foreach ($data as $label => $value) {
            $this->infoRow($label, $value);
        }
    }

    /**
     * Handle Apple Pay Upload.
     */
    private function handleApplePayUpload()
    {
        if (!isset($_FILES[SibsConfig::SIBS_GENERAL_CONFIG.'_merchant_domain_association'])) {
            return;
        }

        $dir = untrailingslashit(ABSPATH).'/.well-known';
        $file = $dir.'/apple-developer-merchantid-domain-association';

        try {
            if (!file_exists($dir)) {
                wp_mkdir_p($dir);
            }

            move_uploaded_file(
                $_FILES[SibsConfig::SIBS_GENERAL_CONFIG.'_merchant_domain_association']['tmp_name'],
                $file
            );
        } catch (Exception $e) {
            SibsLogger::error($e->getMessage(), [
                'source' => Logs::ADMIN,
            ]);
        }
    }

    /**
     * Form Group Start.
     *
     * @param mixed      $label
     * @param null|mixed $for
     */
    private function formGroupStart($label, $for = null)
    {
        ?>
        <div class="mb-3">
            <label class="form-label fw-semibold mb-3" <?php echo $for ? 'for="'.$for.'"' : ''; ?>>
                <?php echo esc_html($label); ?>
            </label>
        <?php
    }

    /**
     * Form Group End.
     */
    private function formGroupEnd()
    {
        echo '</div>';
    }

    /**
     * Render Info Box.
     *
     * @param mixed $title
     */
    private function renderInfoBox($title, callable $callback)
    {
        ?>
        <div class="postbox p-3 mb-3 border rounded-3 mb-3 bg-primary-subtle">
            <h3 class="mb-3"><?php echo esc_html($title); ?></h3>

            <hr/>

            <div class="sibs-info-box">
                <?php $callback(); ?>
            </div>
        </div>
        <?php
    }

    /**
     * Info Row.
     *
     * @param mixed      $label
     * @param mixed      $value
     * @param null|mixed $url
     */
    private function infoRow($label, $value, $url = null)
    {
        $content = '
            <div class="d-flex justify-content-between align-items-start py-2 sibs-row">
                <div class="fw-semibold text-muted" style="min-width: 40%;">'
                    .esc_html($label)
                .'</div>
                <div class="text-end" style="word-break: break-word;">'
                    .wp_kses_post($value)
                    .($url ? '<span class="dashicons dashicons-arrow-right-alt2 ms-1"></span>' : '')
                .'</div>
            </div>';

        if ($url) {
            echo '<a href="'.esc_url($url).'" class="text-decoration-none sibs-clickable-row" target="_self">'
                .$content
            .'</a>';
        } else {
            echo $content;
        }
    }

    /**
     * Add Status Badge.
     */
    private function statusBadge(string $text, string $type)
    {
        $map = [
            'green' => 'success',
            'red' => 'danger',
            'gray' => 'secondary',
            'blue' => 'primary',
        ];

        $class = $map[$type] ?? 'secondary';

        return '<span class="badge rounded-pill bg-'.$class.' px-2 py-1">'
            .esc_html($text)
        .'</span>';
    }
}
