<?php

/**
 * sibs Admin Page.
 */
require_once plugin_dir_path(realpath(__DIR__ . '/')) . '/vendor/autoload.php';

use Sibs2\sibsConfig;
use Sibs2\sibsConstants;
use Sibs2\sibsFunctions;
use Sibs2\sibsLogger;
use Sibs2\sibsPayments;

function sibs_admin_menu()
{
    add_submenu_page(
        'woocommerce',
        'SIBS ' . __('General Settings', sibsConstants::SIBS_TRANSLATE),
        'SIBS ' . __('General Settings', sibsConstants::SIBS_TRANSLATE),
        'manage_options',
        'sibs',
        'sibs_page_content',
        3
    );
}

add_action('admin_menu', 'sibs_admin_menu');

function successMessage($saved = false)
{
    ?>
    <?php if (isset($_POST['sibs_save']) && $saved) { ?>
        <div class="row align-items-center mb-4">
            <div class="col-12">
                <div class="sibs-notice notice notice-success">
                    <p>
                        <strong><?= __('Settings saved', sibsConstants::SIBS_TRANSLATE) ?></strong>
                    </p>
                </div>
            </div>
        </div>
    <?php } ?>
<?php
}

function download_onboarding_file()
{
    $domain_onboarding_file_name        = 'apple-developer-merchantid-domain-association';
    $domain_onboarding_file_directory   = '.well-known';
    $onboarding_file_dir                = untrailingslashit(ABSPATH) . '/' . $domain_onboarding_file_directory;
    $onboarding_file_path               = $onboarding_file_dir . '/' . $domain_onboarding_file_name;

    sibsLogger::debug('_FILES: ' . sibsLogger::prettify($_FILES), sibsConstants::SIBS_ADMIN_LOG);

    if (isset($_FILES[sibsConfig::SIBS_GENERAL_CONFIG . '_merchant_domain_association'])) {
        // code...
        sibsLogger::debug('_FILES: TRUE', sibsConstants::SIBS_ADMIN_LOG);

        try {
            if (! file_exists($onboarding_file_dir) && ! mkdir($onboarding_file_dir, 0755)) {
                sibsLogger::debug(__('Can not on-boarding Apple Pay merchant: Can not create directory', sibsConstants::SIBS_TRANSLATE), sibsConstants::SIBS_ADMIN_LOG);

                return false;
            }

            global $wp_filesystem;

            if (empty($wp_filesystem)) {
                require_once ABSPATH . '/wp-admin/includes/file.php';
                WP_Filesystem();
            }

            if (! move_uploaded_file($_FILES[sibsConfig::SIBS_GENERAL_CONFIG . '_merchant_domain_association']['tmp_name'], $onboarding_file_path)) { // phpcs:ignore
                sibsLogger::debug(__('Can not on-boarding Apple Pay merchant: Can not locate on-boarding file', sibsConstants::SIBS_TRANSLATE), sibsConstants::SIBS_ADMIN_LOG);

                return false;
            }

            return true;
        } catch (Exception $e) {
            sibsLogger::error($e->getMessage(), sibsConstants::SIBS_ADMIN_LOG);

            return false;
        }
    }
}

function sibs_page_sidebar()
{
    ?>
    <div class="col-12">
        <div class="row border rounded-3 mb-3 bg-primary-subtle p-4">
            <div class="col-12 text-black">
                <h4><?= __('System Informations', sibsConstants::SIBS_TRANSLATE) ?></h4>
            </div>
            <hr/>
            <div class="col-12">
                <?= sibsPayments::version_description() ?>
            </div>
        </div>
        <div class="row border rounded-3 mt-2 mb-3 bg-primary-subtle p-4">
            <div class="col-12">
                <h4><?= __('Decryption Informations', sibsConstants::SIBS_TRANSLATE) ?></h4>
            </div>
            <hr/>
            <div class="col-12">
                <?= sibsPayments::decrypt_description() ?>
            </div>
        </div>
        <div class="row border rounded-3 mt-2 mb-3 bg-primary-subtle p-4">
            <div class="col-12">
                <h4><?= __('Other Informations', sibsConstants::SIBS_TRANSLATE) ?></h4>
            </div>
            <hr/>
            <div class="col-12">
                <?= sibsPayments::other_description() ?>
            </div>
        </div>
        <div class="row border rounded-3 mt-2 mb-3 bg-primary-subtle p-4">
            <div class="col-12">
                <h4><?= __('Browser Informations', sibsConstants::SIBS_TRANSLATE) ?></h4>
            </div>

            <hr/>

            <div class="col-12">
                <?php
                    $browser = new Sibs2\sibsBrowser($_SERVER['HTTP_USER_AGENT']);
                    
                    echo $browser->__toString();

                    if ($browser->getBrowser() == Sibs2\sibsBrowser::BROWSER_SAFARI) {
                        echo __('You have Safari', sibsConstants::SIBS_TRANSLATE);
                    }
                ?>
            </div>
        </div>
</div>
    <?php
}

function sibs_page_content()
{
    $saved = (isset($_POST['sibs_save'])) ? sibsPayments::saveData($_POST) : false;

    $environment_file = sibsFunctions::get_environment();
    $environment      = $environment_file['environment'];

    $languages = sibsConstants::SIBS_LANGUAGES;

    download_onboarding_file();

    ?>
    <script type="text/javascript">
       urlAPISIBS = "<?= plugins_url(sibsConstants::SIBS_TRANSLATE); ?>";
       urlStore = "<?= site_url()?>";
       prefix = "<?= sibsConstants::SIBS_PLUGIN_PREFIX . '' ?>";
       ambiente = "<?= implode(',', $environment)?>";
    </script>

    <div class="container px-3 py-4">
        <!-- Header -->
        <div class="row align-items-center mb-4">
            <!-- Logo -->
            <div class="col-md-2 col-12 mb-2 mb-md-0 text-md-start text-center">
                <img src="<?= esc_attr(plugins_url(sibsConstants::SIBS_TRANSLATE . '/assets/images/logo.png')) ?>" alt="Sibs" class="img-fluid" style="max-height: 60px;">
            </div>

            <!-- Title -->
            <div class="col-md-10 col-12 text-md-start text-center">
                <h2 class="mb-0"><?= __('General Settings', sibsConstants::SIBS_TRANSLATE) ?></h2>
            </div>
        </div>
        
        <?php successMessage($saved); ?>

        <!-- Main Content -->
        <div class="row">
            <!-- Settings Form -->
            <div class="col-lg-7">
                <!-- div id="divSibsRadioConfiguration">
                        <div class="toggle"> 
                            <input type="radio" name="sibsconfigurationRadio" value="Manually" id="sizeDimensions" checked="checked" /> 
                            <label for="sizeDimensions"><?= __('Manual Configuration', sibsConstants::SIBS_TRANSLATE) ?></label> 
                            <input type="radio" name="sibsconfigurationRadio" value="Automatic" id="sizeWeight" /> 
                            <label for="sizeWeight"><?= __('Automatic Configuration', sibsConstants::SIBS_TRANSLATE) ?></label> 
                        </div>
                    </div -->

                <form method="POST" action="" enctype="multipart/form-data">
                    <!-- General Settings -->
                    <div class="border rounded-3 p-4 mb-4 bg-light">
                        <h4 class="mb-3">
                            <?= __('Terminal Settings', sibsConstants::SIBS_TRANSLATE) ?>
                        </h4>

                        <hr/>

                        <div class="mb-3">
                            <label for="<?= sibsConfig::SIBS_GENERAL_CONFIG . '_merchant_no' ?>" class="form-label">
                                <?= __('Terminal Code', sibsConstants::SIBS_TRANSLATE) ?> *
                            </label>
                            <input type="text" class="form-control"
                                id="<?= sibsConfig::SIBS_GENERAL_CONFIG . '_merchant_no' ?>"
                                name="<?= sibsConfig::SIBS_GENERAL_CONFIG . '_merchant_no' ?>"
                                value="<?= esc_attr(sibsConfig::getTerminalId()) ?>" required>
                        </div>

                        <div class="mb-3">
                            <label for="<?= sibsConfig::SIBS_GENERAL_CONFIG . '_client_id' ?>" class="form-label">
                                <?= __('Client ID', sibsConstants::SIBS_TRANSLATE) ?> *
                            </label>
                            <input type="text" class="form-control"
                                id="<?= sibsConfig::SIBS_GENERAL_CONFIG . '_client_id' ?>"
                                name="<?= sibsConfig::SIBS_GENERAL_CONFIG . '_client_id' ?>"
                                value="<?= esc_attr(sibsConfig::getClientId()) ?>" required>
                        </div>

                        <div class="mb-3">
                            <label for="<?= sibsConfig::SIBS_GENERAL_CONFIG . '_bearer_token' ?>" class="form-label">
                                <?= __('Bearer Token', sibsConstants::SIBS_TRANSLATE) ?> *
                            </label>
                            <textarea class="form-control"
                                    id="<?= sibsConfig::SIBS_GENERAL_CONFIG . '_bearer_token' ?>"
                                    name="<?= sibsConfig::SIBS_GENERAL_CONFIG . '_bearer_token' ?>"
                                    rows="7" required><?= esc_attr(sibsConfig::getToken()) ?></textarea>
                        </div>

                        <div class="mb-3">
                            <label for="<?= sibsConfig::SIBS_GENERAL_CONFIG . '_environment' ?>" class="form-label">
                                <?= __('SIBS Environment', sibsConstants::SIBS_TRANSLATE) ?>
                            </label>
                            <select id="<?= sibsConfig::SIBS_GENERAL_CONFIG . '_environment' ?>" class="form-control"
                                    name="<?= sibsConfig::SIBS_GENERAL_CONFIG . '_environment' ?>">
                                <?php foreach ($environment as $key => $value): ?>
                                    <option value="<?= $key ?>" <?= $key == sibsConfig::getEnvironment() ? 'selected' : '' ?>>
                                        <?= $value ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="mb-3">
                            <label for="<?= sibsConfig::SIBS_GENERAL_CONFIG . '_webhook_secret' ?>" class="form-label">
                                <?= __('SIBS WebHook Secret', sibsConstants::SIBS_TRANSLATE) ?>
                            </label>
                            <input class="form-control" type="text"
                                id="<?= sibsConfig::SIBS_GENERAL_CONFIG . '_webhook_secret' ?>"
                                name="<?= sibsConfig::SIBS_GENERAL_CONFIG . '_webhook_secret' ?>"
                                value="<?= esc_attr(sibsConfig::getWebhookSecret()) ?>">
                            <div class="form-text">
                                <?= sibsPayments::webhook_description() ?>
                            </div>
                        </div>
                    </div>

                    <!-- Language Settings -->
                    <div class="border rounded-3 p-4 mb-4 bg-light">
                        <h4 class="mb-3">
                            <?= __('Form Settings', sibsConstants::SIBS_TRANSLATE) ?>
                        </h4>

                        <hr/>

                        <div class="mb-3">
                            <label for="<?= sibsConfig::SIBS_GENERAL_CONFIG . '_language' ?>" class="form-label">
                                <?= __('Form Language', sibsConstants::SIBS_TRANSLATE) ?>
                            </label>
                            <select id="<?= sibsConfig::SIBS_GENERAL_CONFIG . '_language' ?>" class="form-control"
                                    name="<?= sibsConfig::SIBS_GENERAL_CONFIG . '_language' ?>">
                                <?php foreach ($languages as $key => $value): ?>
                                    <option value="<?= $key ?>" <?= $key == sibsConfig::getLanguageDefault() ? 'selected' : '' ?>>
                                        <?= $value ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>

                    <!-- Apple Pay Section -->
                    <div class="border rounded-3 p-4 mb-4 bg-light">
                        <h4 class="mb-3">
                            <?= __('Apple Pay Settings', sibsConstants::SIBS_TRANSLATE) ?>
                        </h4>

                        <hr/>

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

                        <div class="mb-3">
                            <label for="<?= sibsConfig::SIBS_GENERAL_CONFIG . '_merchant_domain_association' ?>" class="form-label">
                                <?= __('MerchantId Domain Association', sibsConstants::SIBS_TRANSLATE) ?> *
                            </label>
                            <input type="file" class="form-control"
                                id="<?= sibsConfig::SIBS_GENERAL_CONFIG . '_merchant_domain_association' ?>"
                                name="<?= sibsConfig::SIBS_GENERAL_CONFIG . '_merchant_domain_association' ?>">
                        </div>

                        <p class="text-muted mb-0">
                            <?= __('Please add the file provided by Apple for the validation of payments via Apple Pay on the site.', sibsConstants::SIBS_TRANSLATE) ?>
                        </p>
                    </div>

                    <!-- Submit Button -->
                    <div class="text-center mb-4">
                        <button class="btn btn-primary" type="submit" name="sibs_save"
                                value="<?= __('Save Changes', sibsConstants::SIBS_TRANSLATE) ?>">
                            <?= __('Save Changes', sibsConstants::SIBS_TRANSLATE) ?>
                        </button>
                    </div>
                </form>
            </div>

            <!-- Sidebar -->
            <div class="col-lg-5 small">
                <?= sibs_page_sidebar() ?>
            </div>
        </div>
    </div>


    <div class="sibs-settings">
        
    </div>

    <!-- div id="sibsConfigurationWizard">
        <div id="wizard" class="wizard">
            <h2><?= __('Login', sibsConstants::SIBS_TRANSLATE) ?></h2>
            <section>
                <?= sibsPayments::sibs_page_content_wizard_login() ?>
            </section>
            <h2><?= __('Configure Terminal', sibsConstants::SIBS_TRANSLATE) ?></h2>
            <section>
                <?= sibsPayments::sibs_page_content_wizard_terminal() ?>
            </section>
            <h2><?= __('Webhooks', sibsConstants::SIBS_TRANSLATE) ?></h2>
            <section>
                <?= sibsPayments::sibs_page_content_wizard_webhooks() ?>
            </section>
        </div>
    </div-->

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

?>