<?php

namespace Macymed\MacymedLinkTracker\Admin\Pages;

use Macymed\MacymedLinkTracker\Admin\Pages\Components\AdminTable;
use Macymed\MacymedLinkTracker\Admin\Pages\Components\AdminTableClicks;
use Macymed\MacymedLinkTracker\Admin\Pages\Components\AdminTableReferer;
use Macymed\MacymedLinkTracker\Utils\Report;
use Macymed\MacymedLinkTracker\Utils\Stats;

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

class ListClicks extends Page
{
    public static function init()
    {
        add_action(
            'wp_ajax_get_details',
            function () {
                global $wpdb;
                // Récupérer le nonce depuis l'URL
                $nonce = isset($_POST['mtl_nonce']) ? sanitize_text_field(wp_unslash($_POST['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'));
                }

                $id = intval(!empty($_POST['id']) ? $_POST['id'] : 0);

                $url_table   = $wpdb->prefix . MACYMED_LINK_TRACKER_TABLE_NAME;
                // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                $url_data    = $wpdb->get_row($wpdb->prepare("SELECT id, url FROM " . $url_table . " WHERE id = %d", [$id]));

                if (! $url_data) {
                    wp_send_json_error(['message' => 'URL introuvable']);
                    return;
                }

                $result = Report::renderDetailsUrl($id, $url_data->url, true);

                wp_send_json_success($result);
            }
        );

        add_action(
            'wp_ajax_get_referer_details',
            function () {
                global $wpdb;
                // Récupérer le nonce depuis l'URL
                $nonce = isset($_POST['mtl_nonce']) ? sanitize_text_field(wp_unslash($_POST['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'));
                }
                $referer = sanitize_text_field(!empty($_POST['referer']) ? wp_unslash($_POST['referer']) : '');

                // Récupérer les détails
                $table   = new AdminTableReferer();
                $details = $table->get_details_for_referer($referer);

                // Construire une sous-table HTML
                echo '<table class="wp-list-table widefat fixed striped">';
                echo '<thead><tr><th>' . esc_html(__('Linked URL', 'macymed-link-tracker')) . '</th><th>' . esc_html(__('Occurrences', 'macymed-link-tracker')) . '</th></tr></thead>';
                echo '<tbody>';
                foreach ($details as $detail) {
                    echo '<tr>';
                    echo '<td>' . esc_html($detail['linked_url']) . '</td>';
                    echo '<td>' . intval($detail['occurrence']) . '</td>';
                    echo '</tr>';
                }
                echo '</tbody>';
                echo '</table>';

                wp_die(); // Terminer la réponse AJAX
            }
        );
    }

    public static function render()
    {

        // Vérification du nonce dans l'URL
        $nonce = isset($_GET['tab_nonce']) ? sanitize_text_field(wp_unslash($_GET['tab_nonce'])) : '';
        if ($nonce && !wp_verify_nonce($nonce, 'tab_navigation')) {
            wp_die(esc_html__('Invalid nonce or expired link.', 'macymed-link-tracker'));
        }

        // Récupérer l'onglet actif
        $active_tab = isset($_GET['tab']) ? sanitize_text_field(wp_unslash($_GET['tab'])) : 'url';

        // Générer un nonce pour les onglets
        $nonce = wp_create_nonce('tab_navigation');

        // Générer les URLs des onglets
        $tab_url = (add_query_arg(['tab' => 'url', 'tab_nonce' => $nonce], menu_page_url('macymed-link-tracker-clicks', false)));
        $tab_referer = (add_query_arg(['tab' => 'referer', 'tab_nonce' => $nonce], menu_page_url('macymed-link-tracker-clicks', false)));
        $tab_history = (add_query_arg(['tab' => 'history', 'tab_nonce' => $nonce], menu_page_url('macymed-link-tracker-clicks', false)));

        ?>
        <div class="wrap macymed_link_tracker_table">
            <?php self::renderTitle(esc_html__('Tracking', 'macymed-link-tracker')); ?>
            <h2 class="nav-tab-wrapper">
                <a href="<?php echo esc_url($tab_url); ?>" class="nav-tab <?php echo $active_tab == 'url' ? 'nav-tab-active' : ''; ?>">
                    <?php esc_html_e('Page(s) d\'atterrissage', 'macymed-link-tracker'); ?>
                </a>
                <a href="<?php echo esc_url($tab_referer); ?>" class="nav-tab <?php echo $active_tab == 'referer' ? 'nav-tab-active' : ''; ?>">
                    <?php esc_html_e('Page(s) référente', 'macymed-link-tracker'); ?>
                </a>
                <a href="<?php echo esc_url($tab_history); ?>" class="nav-tab <?php echo $active_tab == 'history' ? 'nav-tab-active' : ''; ?>">
                    <?php esc_html_e('Historique', 'macymed-link-tracker'); ?>
                </a>
            </h2>
            <div id="poststuff">
                <div id="post-body" class="metabox-holder columns-3">

                    <div id="post-body-content">
                        <div class="meta-box-sortables">
                            <div class="postbox">

                                <div class="inside">
                                    <?php

                                            $displayGraph = false;

        if ($active_tab == 'url') {
            $table = new AdminTable();
            $table->prepare_items();

            ?>
                                        <form method="post">
                                            <input type="hidden" name="page" value="macymed-link-tracker-clicks" />
                                            <?php
                    $table->search_box('Search', 'search_id');
            ?>
                                            <?php $table->display(); ?>
                                        </form>
                                    <?php
        } elseif ($active_tab == 'history') {
            $table = new AdminTableClicks();
            $table->prepare_items();

            ?>
                                        <form method="post">
                                            <input type="hidden" name="page" value="macymed-link-tracker-clicks" />
                                            <?php $table->search_box('Search', 'search_id'); ?>
                                            <?php $table->display(); ?>
                                        </form>
                                    <?php
        } elseif ($active_tab == 'referer') {
            $table = new AdminTableReferer();
            $table->prepare_items();

            ?>
                                        <form method="post">
                                            <input type="hidden" name="page" value="macymed-link-tracker-clicks" />
                                            <?php $table->search_box('Search', 'search_id'); ?>
                                            <?php $table->display(); ?>
                                        </form>
                                    <?php
        }
        ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

            </div>

            <div class="modal-link-tracker">
                <div id="details-modal" style="display:none;">
                    <div class="modal-content">
                        <div class="modal-header" id="modal-details-header">
                            <h2 id="modal-details-title"></h2>
                            <span id="modal-close">&times;</span>
                        </div>

                        <div class="modal-body" id="modal-details-content">

                        </div>

                    </div>
                </div>
            </div>


        </div>
<?php
    }
}
