<?php

namespace Macymed\MacymedLinkTracker\Admin\Pages;

use Macymed\MacymedLinkTracker\Utils\Stats;
use Macymed\MacymedLinkTracker\Utils\TrackerHelper;
use Macymed\MacymedLinkTracker\Utils\Tracking;
use Macymed\MacymedLinkTracker\Utils\Utils;

if (! defined('ABSPATH')) {
    exit; // Sécurité
}

class Tools extends Page
{
    public static function init()
    {
        add_action(
            'admin_post_macymed_link_tracker_clear_database',
            function () {
                // Récupérer le nonce depuis l'URL
                $nonce = isset($_REQUEST['mtl_nonce']) ? sanitize_text_field(wp_unslash($_REQUEST['mtl_nonce'])) : '';

                // Vérifier le nonce
                if (!wp_verify_nonce($nonce, 'macymed-admin-script-ajax-nonce')) {
                    wp_die(esc_html__('Invalid nonce or expired link.', 'macymed-link-tracker'));
                }

                Tracking::deleteAllRecords();

                $nonce = wp_create_nonce('macymed-admin-script-ajax-nonce');

                wp_redirect(admin_url('admin.php?page=macymed-link-tracker-tools&status=success&mlta=clear_database&mtl_nonce=' . $nonce));
                exit;
            }
        );
        add_action(
            'admin_post_macymed_link_tracker_clear_url',
            function () {
                // Récupérer le nonce depuis l'URL
                $nonce = isset($_REQUEST['mtl_nonce']) ? sanitize_text_field(wp_unslash($_REQUEST['mtl_nonce'])) : '';

                // Vérifier le nonce
                if (!wp_verify_nonce($nonce, 'macymed-admin-script-ajax-nonce')) {
                    wp_die(esc_html__('Invalid nonce or expired link.', 'macymed-link-tracker'));
                }
                $cleanUrl = isset($_REQUEST['cleanUrl']) ? sanitize_text_field(wp_unslash($_REQUEST['cleanUrl'])) : '';
                if ($cleanUrl) {
                    Tracking::deleteAllRecordsFromUrl($cleanUrl);
                }
                $nonce = wp_create_nonce('macymed-admin-script-ajax-nonce');

                wp_redirect(admin_url('admin.php?page=macymed-link-tracker-tools&status=success&mlta=clear_url&mtl_nonce=' . $nonce));
                exit;
            }
        );
        add_action(
            'admin_post_macymed_link_tracker_clear_keyword',
            function () {
                // Récupérer le nonce depuis l'URL
                $nonce = isset($_REQUEST['mtl_nonce']) ? sanitize_text_field(wp_unslash($_REQUEST['mtl_nonce'])) : '';


                // Vérifier le nonce
                if (!wp_verify_nonce($nonce, 'macymed-admin-script-ajax-nonce')) {
                    wp_die(esc_html__('Invalid nonce or expired link.', 'macymed-link-tracker'));
                }

                $cleanKeyword = isset($_REQUEST['cleanKeyword']) ? sanitize_text_field(wp_unslash($_REQUEST['cleanKeyword'])) : '';
                if ($cleanKeyword) {
                    Tracking::deleteAllRecordsFromKeyword($cleanKeyword);
                }
                $nonce = wp_create_nonce('macymed-admin-script-ajax-nonce');

                $url_keyword = (admin_url('admin.php?page=macymed-link-tracker-tools&status=success&mlta=clear_keyword&mtl_nonce=' . $nonce));

                wp_redirect(($url_keyword));
                exit;
            }
        );
        add_action(
            'admin_init',
            function () {}
        );
    }
    public static function get_menu_structure()
    {
        $base_url = admin_url('admin.php?page=macymed-link-tracker-tools');

        return [
            esc_html__('Configuration', 'macymed-link-tracker') => [
                [
                    'label' => esc_html__('Import', 'macymed-link-tracker'),
                    'url' => $base_url . '&tab=import_configuration',
                    'tab' => 'import_configuration',
                ],
                [
                    'label' => esc_html__('Export', 'macymed-link-tracker'),
                    'url' => $base_url . '&tab=export_configuration',
                    'tab' => 'export_configuration',
                ],



            ],
            esc_html__('Base de données', 'macymed-link-tracker') => [
                [
                    'label' => esc_html__('Supprimer une url', 'macymed-link-tracker'),
                    'url' => $base_url . '&tab=database_delete_url',
                    'tab' => 'database_delete_url',
                ],
                [
                    'label' => esc_html__('Supprimer un mot clef', 'macymed-link-tracker'),
                    'url' => $base_url . '&tab=database_delete_keyword',
                    'tab' => 'database_delete_keyword',
                ],
                [
                    'label' => esc_html__('Purger', 'macymed-link-tracker'),
                    'url' => $base_url . '&tab=database_purge',
                    'tab' => 'database_purge',
                ],



            ],


        ];
    }
    public static function render()
    {

        $nonce = isset($_REQUEST['mtl_nonce']) ? sanitize_text_field(wp_unslash($_REQUEST['mtl_nonce'])) : '';

        // Vérifier le nonce
        if ($nonce && !wp_verify_nonce($nonce, 'macymed-admin-script-ajax-nonce')) {
            wp_die(esc_html__('Invalid nonce or expired link.', 'macymed-link-tracker'));
        }

        // $active_tab = isset($_GET['tab']) ? $_GET['tab'] : 'redirect_page'; // 'general';
        $success    = isset($_GET['status']) && ($_GET['status'] === 'success') ? 'success' : '';
        $mlta       = isset($_GET['mlta']) ? sanitize_text_field(wp_unslash($_GET['mlta'])) : '';

        $active_tab = isset($_GET['tab']) ? sanitize_text_field(wp_unslash($_GET['tab'])) : 'import_configuration';
        // Générer un nonce pour les onglets
        $nonce = wp_create_nonce('macymed-admin-script-ajax-nonce');
        // &status=success&mlta=clear_database
        if ($success && ($mlta == 'clear_database')) {

            self::renderNotice(esc_html__('Base de données purgée avec succès', 'macymed-link-tracker'), 'success');
        } elseif ($success && ($mlta == 'clear_url')) {
            self::renderNotice(esc_html__('Url purgée avec succès', 'macymed-link-tracker'), 'success');
        } elseif ($success && ($mlta == 'clear_keyword')) {
            self::renderNotice(esc_html__('Mot clef purgé avec succès', 'macymed-link-tracker'), 'success');
        }

        // $url_all = (add_query_arg([ 'action' => 'macymed_link_tracker_clear_database', 'mtl_nonce' => $nonce], menu_page_url('admin_post', false)));
        // $url_url = (add_query_arg([ 'action' => 'macymed_link_tracker_clear_url', 'mtl_nonce' => $nonce], menu_page_url('admin_post', false)));
        // $url_keyword = (add_query_arg([ 'action' => 'macymed_link_tracker_clear_keyword', 'mtl_nonce' => $nonce], menu_page_url('admin_post', false)));


        $url_keyword = admin_url('admin-post.php?action=macymed_link_tracker_clear_keyword&mtl_nonce=' . $nonce);
        $url_url = admin_url('admin-post.php?action=macymed_link_tracker_clear_url&mtl_nonce=' . $nonce);
        $url_all = admin_url('admin-post.php?action=macymed_link_tracker_clear_database&mtl_nonce=' . $nonce);

?>
        <div class="macymed-content">
            <?php
            // Ajout d'un nonce pour la sécurité
            $nonce_field = wp_nonce_field('macymed_action', 'macymed_nonce', true, false);

            if ($active_tab === 'import_configuration') {
            ?>
                <h2>Importer la configuration</h2>
                <form method="post" enctype="multipart/form-data">
                    <?php wp_nonce_field('macymed_action', 'macymed_nonce', true, false); ?>
                    <label for="config_file">Sélectionnez un fichier JSON :</label>
                    <input type="file" name="config_file" id="config_file" accept=".json" required>
                    <?php submit_button('Importer la configuration'); ?>
                </form>
                <?php
                if (TrackerHelper::get_request_method() === 'POST' && isset($_FILES['config_file']['tmp_name'])) {
                    check_admin_referer('macymed_action', 'macymed_nonce');
                    global $wp_filesystem;
                    if (empty($wp_filesystem)) {
                        require_once ABSPATH . 'wp-admin/includes/file.php';
                        WP_Filesystem();
                    }
                    $file = sanitize_text_field(wp_unslash($_FILES['config_file']['tmp_name']));
                    $json = '';
                    if (file_exists($file)) {
                        $json = $wp_filesystem->get_contents($file);
                    } else {
                        // Gérer l'erreur de fichier introuvable
                        wp_die('Fichier introuvable ou inaccessible.');
                    }
                    $data = json_decode($json, true);

                    if (isset($data['plugin'], $data['options']) && $data['plugin'] === 'macymed-link-tracker') {
                        foreach ($data['options'] as $key => $value) {
                            if (strpos($key, 'macymed_tracker_') === 0) {
                                update_option($key, $value);
                            }
                        }
                        echo '<div class="updated"><p>Configuration importée avec succès.</p></div>';
                    } else {
                        echo '<div class="error"><p>Fichier JSON invalide ou non compatible.</p></div>';
                    }
                }
            } elseif ($active_tab === 'export_configuration') {
                ?>
                <h2>Exporter la configuration</h2>
                <form method="post">
                    <?php wp_nonce_field('macymed_action', 'macymed_nonce', true, false); ?>
                    <?php submit_button('Exporter la configuration'); ?>
                </form>
                <?php
                if (TrackerHelper::get_request_method() === 'POST') {
                    check_admin_referer('macymed_action', 'macymed_nonce');

                    ob_clean();
                    $options = [];
                    foreach (wp_load_alloptions() as $key => $value) {
                        if (strpos($key, 'macymed_tracker_') === 0) {
                            $options[$key] = $value;
                        }
                    }
                    $json_data = [
                        'plugin' => 'macymed-link-tracker',
                        'date_generation' => gmdate('Y-m-d'),
                        'wordpress_version' => get_bloginfo('version'),
                        'plugin_version' => Utils::get_plugin_version(),
                        'options' => $options,
                    ];

                    header('Content-Type: application/json');
                    header('Content-Disposition: attachment; filename="configuration.json"');
                    echo wp_json_encode($json_data, JSON_PRETTY_PRINT);
                    exit;
                }
            } elseif ($active_tab === 'database_delete_url') {
                ?>
                <h2>Supprimer une URL</h2>
                <form method="post" id="delete-url-form" data-requires-confirmation>
                    <?php wp_nonce_field('macymed_action', 'macymed_nonce', true, false); ?>
                    <label for="url">Sélectionnez une URL :</label>
                    <select name="url" id="url" required>
                        <?php foreach (Stats::get_instance()->getListUrls() as $url) : ?>
                            <option value="<?php echo esc_attr($url['id']); ?>"><?php echo esc_html($url['url']); ?></option>
                        <?php endforeach; ?>
                    </select>
                    <?php submit_button('Supprimer l\'URL'); ?>
                </form>
                <?php
                if (TrackerHelper::get_request_method() === 'POST' && isset($_POST['url'])) {
                    check_admin_referer('macymed_action', 'macymed_nonce');
                    $url = sanitize_text_field(wp_unslash($_POST['url']));
                    Tracking::deleteAllRecordsFromUrl($url);
                    echo '<div class="updated"><p>URL supprimée avec succès.</p></div>';
                }
            } elseif ($active_tab === 'database_delete_keyword') {
                ?>
                <h2>Supprimer un mot clé</h2>
                <form method="post" data-requires-confirmation>
                    <?php wp_nonce_field('macymed_action', 'macymed_nonce', true, false); ?>
                    <label for="keyword">Entrez le mot clé :</label>
                    <input type="text" name="keyword" id="keyword" required>
                    <?php submit_button('Supprimer le mot clé'); ?>
                </form>
                <?php
                if (TrackerHelper::get_request_method() === 'POST' && isset($_POST['keyword'])) {
                    check_admin_referer('macymed_action', 'macymed_nonce');
                    $keyword = sanitize_text_field(wp_unslash($_POST['keyword']));
                    Tracking::deleteAllRecordsFromKeyword($keyword);
                    echo '<div class="updated"><p>Mot clé supprimé avec succès.</p></div>';
                }
            } else if ($active_tab === 'database_purge') {
                ?>
                <h2>Purger la base de données</h2>
                <p class="warning" style="color: red; font-weight: bold;">Cette action supprimera toutes les données !</p>
                <form method="post" id="purge-database-form" data-requires-confirmation>
                    <?php wp_nonce_field('macymed_action', 'macymed_nonce', true, false); ?>
                    <?php submit_button('Purger la base de données', 'delete'); ?>
                </form>
            <?php
                if (TrackerHelper::get_request_method() === 'POST') {
                    check_admin_referer('macymed_action', 'macymed_nonce');
                    Tracking::deleteAllRecords();
                    echo '<div class="updated"><p>Base de données purgée avec succès.</p></div>';
                }
            }
            ?>
        </div>
        <!-- Modal de confirmation pour tous les formulaires -->
        <div id="confirmation-modal" class="confirmation-modal" style="display: none;">
            <div class="modal-content">
                <h2>Confirmation requise</h2>
                <p>Êtes-vous sûr de vouloir effectuer cette action ? Cette opération est irréversible.</p>
                <button id="confirm-action" class="button button-primary">Confirmer</button>
                <button id="cancel-action" class="button button-secondary">Annuler</button>
            </div>
        </div>

        <script type="text/javascript">
            function handleFormConfirmation(form) {
                const modal = document.getElementById('confirmation-modal');
                const confirmButton = document.getElementById('confirm-action');
                const cancelButton = document.getElementById('cancel-action');

                return new Promise((resolve, reject) => {
                    // Show modal
                    modal.style.display = 'flex';

                    const confirmHandler = () => {
                        modal.style.display = 'none';
                        cleanup();
                        resolve();
                    };

                    const cancelHandler = () => {
                        modal.style.display = 'none';
                        cleanup();
                        reject();
                    };

                    // Attach event listeners
                    confirmButton.addEventListener('click', confirmHandler);
                    cancelButton.addEventListener('click', cancelHandler);

                    function cleanup() {
                        confirmButton.removeEventListener('click', confirmHandler);
                        cancelButton.removeEventListener('click', cancelHandler);
                    }
                });
            }

            function initFormSubmit(form, event) {
                event.preventDefault();
                handleFormConfirmation(form).then(() => {
                    // Prevent re-triggering confirmation on submit
                    form.setAttribute('data-confirmed', 'true');
                    if (typeof form.requestSubmit === 'function') {
                        form.requestSubmit();
                    } else {
                        form.submit();
                    }
                    return true;
                }).catch(() => {
                    console.log('Action annulée par l\'utilisateur.');
                    return false;
                });
            }

            document.addEventListener('DOMContentLoaded', function() {
                const forms = document.querySelectorAll('form[data-requires-confirmation]');
                forms.forEach(function(form) {
                    form.addEventListener('submit', function(event) {
                        // Skip confirmation if already confirmed
                        if (form.getAttribute('data-confirmed') === 'true') {
                            form.removeAttribute('data-confirmed');
                            return;
                        }
                        initFormSubmit(form, event);
                    });
                });
            });
        </script>

        <style>
            .confirmation-modal {
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0, 0, 0, 0.5);
                display: flex;
                justify-content: center;
                align-items: center;
                z-index: 1000;
            }

            .modal-content {
                background: #fff;
                padding: 20px;
                border-radius: 8px;
                box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
                text-align: center;
                width: 400px;
                max-width: 90%;
            }

            .modal-content h2 {
                margin-bottom: 10px;
                font-size: 18px;
                color: #333;
            }

            .modal-content p {
                margin-bottom: 20px;
                font-size: 14px;
                color: #555;
            }

            .modal-content .button {
                margin: 5px;
                padding: 8px 16px;
                font-size: 14px;
            }
        </style>

<?php
    }
}
