<?php

namespace Macymed\MacymedLinkTracker\Admin\Pages\Components;

if (! class_exists('WP_List_Table')) {
    require_once ABSPATH . 'wp-admin/includes/class-wp-list-table.php';
}
if (! defined('ABSPATH')) {
    exit; // Sécurité
}

class AdminTableReferer extends \WP_List_Table
{
    private $table_data;
    public function __construct()
    {
        parent::__construct(
            [
                'singular' => 'click',
                'plural'   => 'clicks',
                'ajax'     => false,
            ]
        );
        add_filter(
            'set-screen-option',
            function ($status, $option, $value) {
                if ($option === 'macymed_clicks_per_page') {
                    return $value;
                }
                return $status;
            },
            10,
            3
        );

        add_screen_option(
            'per_page',
            [
                'label'   => 'Nombre d’éléments par page',
                'default' => 10,
                'option'  => 'macymed_clicks_per_page',
            ]
        );
    }
    private $per_page = 10; // Nombre d’éléments par page

    public function print_column_headers($with_id = true)
    {
        // Récupérer les colonnes et colonnes triables
        $columns          = $this->get_columns();
        $sortable_columns = $this->get_sortable_columns();

        // Récupérer le nonce depuis l'URL
        $nonce = isset($_GET['mtl_nonce']) ? sanitize_text_field(wp_unslash($_GET['mtl_nonce'])) : '';

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

        // Récupérer les paramètres actuels de tri
        $orderby = isset($_GET['orderby']) ? sanitize_text_field(wp_unslash($_GET['orderby'])) : '';
        $order   = isset($_GET['order']) && in_array($_GET['order'], ['asc', 'desc']) ? sanitize_text_field(wp_unslash($_GET['order'])) : 'asc';

        echo '<tr>';

        foreach ($columns as $key => $label) {
            $class   = 'manage-column';
            $colspan = '1';

            // Gestion de la colonne "url" avec colspan
            if ($key === 'url') {
                // $colspan = '2';
            }

            // Si la colonne est triable
            if (isset($sortable_columns[$key])) {
                $new_order = ($orderby === $key && $order === 'asc') ? 'desc' : 'asc';
                $sort_url  = add_query_arg(
                    [
                        'orderby' => $key,
                        'order'   => $new_order,
                    ]
                );

                $is_sorted = ($orderby === $key);
                $class    .= $is_sorted ? " sorted $order" : ' sortable desc';


                echo '<th colspan=' . esc_attr($colspan) . ' scope="col" class="' . esc_attr($class) . '">
        <a href="' . esc_url($sort_url) . '">
            <span>' . esc_html($label) . '</span>
            <span class="sorting-indicator"></span>
        </a>
      </th>';
            } else {
                // Colonne non triable
                echo "<th  scope='col' class='" . esc_attr($class) . "'>" . esc_html($label) . '</th>';
            }
        }

        echo '</tr>';
    }
    // public function single_row($item)
    // {
    // Afficher la ligne principale
    // echo '<tr id="record-' . esc_attr($item['id']) . '">';
    // $this->single_row_columns($item);
    // echo '</tr>';

    // Ajouter la sous-ligne avec les clics
    // echo '<tr id="details-' . esc_attr($item['id']) . '" class="hidden-row" style="display: none;">';
    // echo '<td colspan="6">'; // Nombre total de colonnes

    // Appel à une méthode pour récupérer les détails des clics
    // $this->display_clicks_details($item['id']);

    // echo '</td>';
    // echo '</tr>';
    // }
    // public function print_column_headers($with_id = true)
    // {
    // Récupérer les colonnes et colonnes triables
    // $columns = $this->get_columns();
    // $sortable_columns = $this->get_sortable_columns();

    // Récupérer les paramètres actuels de tri
    // $orderby = isset($_GET['orderby']) ? sanitize_text_field($_GET['orderby']) : '';
    // $order = isset($_GET['order']) && in_array($_GET['order'], ['asc', 'desc']) ? sanitize_text_field($_GET['order']) : 'asc';

    // echo '<tr>';

    // foreach ($columns as $key => $label) {
    // $class = 'manage-column';
    // $colspan = '';

    // Gestion de la colonne "url" avec colspan
    // if ($key === 'url') {
    // $colspan = " colspan='2' ";
    // }

    // Si la colonne est triable
    // if (isset($sortable_columns[$key])) {
    // $new_order = ($orderby === $key && $order === 'asc') ? 'desc' : 'asc';
    // $sort_url = add_query_arg([
    // 'orderby' => $key,
    // 'order'   => $new_order,
    // ]);

    // $is_sorted = ($orderby === $key);
    // $class .= $is_sorted ? " sorted $order" : ' sortable desc';

    // echo "<th {$colspan} scope='col' class='{$class}'>
    // <a href='" . esc_url($sort_url) . "'>
    // <span>" . esc_html($label) . "</span>
    // <span class='sorting-indicator'></span>
    // </a>
    // </th>";
    // } else {
    // Colonne non triable
    // echo "<th {$colspan} scope='col' class='{$class}'>" . esc_html($label) . "</th>";
    // }
    // }

    // echo '</tr>';
    // }


    private function display_clicks_details($url_id)
    {
        global $wpdb;
        $table_name_clicks = $wpdb->prefix . MACYMED_LINK_TRACKER_CLICKS_TABLE_NAME;
        // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $clicks = $wpdb->get_results(
            $wpdb->prepare("SELECT * FROM %s WHERE url_id = %d ORDER BY last_click desc", [$table_name_clicks, $url_id]),
            ARRAY_A
        );

        // Afficher les clics dans une liste
        if (! empty($clicks)) {
            echo '<table class="widefat striped">';
            // <th>Full URL</th>
            echo '<thead><tr><th>ID</th><th>Data</th><th>Type</th><th>Dernier clic</th></tr></thead>';
            echo '<tbody>';

            foreach ($clicks as $click) {
                echo '<tr>';
                echo '<td>' . esc_html($click['id']) . '</td>';
                // echo '<td>' . esc_html($click['full_url']) . '</td>';
                $data       = json_decode($click['data'], true);
                $outputData = '<table><tr>';

                $outputData .= '<td style="padding:0px 10px 0px 0px;"><strong>' . htmlspecialchars('full_url') . ':</strong></td><td style="padding:0px 10px 0px 0px;">' . esc_html($click['full_url']) . '</td>';
                $outputData .= '</tr>';
                foreach ($data as $key => $value) {
                    if ($key && $value) {
                        $outputData .= '<tr>';
                        $outputData .= '<td style="padding:0px 10px 0px 0px;"><strong>' . htmlspecialchars($key) . ':</strong></td><td style="padding:0px 10px 0px 0px;">' . htmlspecialchars($value) . '</td>';
                        $outputData .= '</tr>';
                    }
                }
                $outputData .= '</table>';
                echo '<td>' . wp_kses(
                    $outputData,
                    [
                        'table'  => [],
                        'tr'     => [],
                        'td'     => ['style' => []],
                        'strong' => [],
                    ]
                ) . '</td>';
                echo '<td>' . esc_html($click['type_click']) . '</td>';
                echo '<td>' . esc_html($click['last_click']) . '</td>';
                echo '</tr>';
            }

            echo '</tbody>';
            echo '</table>';
        } else {
            echo '<p>Aucun clic enregistré pour cette URL.</p>';
        }
    }
    public function get_items_per_page($option, $default = 10)
    {
        // Récupère l'option d'écran associée à cet utilisateur
        $screen      = get_current_screen();
        $option_name = $screen->id . '_per_page';

        // Vérifie si l'utilisateur a déjà défini une préférence
        $per_page = get_user_meta(get_current_user_id(), $option_name, true);

        // Si aucune préférence n'est définie, retourne la valeur par défaut
        return $per_page ? intval($per_page) : $default;
    }
    public function display()
    {

        parent::display(); // Appelle l'affichage de la table
        // parent::display();
        // $this->pagination('top'); // Pagination en haut
        // parent::display_rows();
        // $this->pagination('bottom'); // Pagination en bas
    }

    // function column_details($item)
    // {
    // Bouton pour afficher/masquer les sous-lignes
    // $button = '<a href="#" class="toggle-details button" data-row="' . esc_attr($item['id']) . '">
    // <span class="dashicons dashicons-arrow-down"></span> '.__('Voir', 'macymed-link-tracker').'
    // </a>';
    // return $button;
    // }
    // function column_info($item)
    // {
    // Bouton pour afficher/masquer les sous-lignes
    // $button = '<button class="view-details" data-id="' . esc_attr($item['id']) . '">Voir les détails</button>';
    // $button = '<a href="#" class="view-details button" data-id="' . esc_attr($item['id']) . '">
    // ' .__('Voir les détails', 'macymed-link-tracker').'
    // </a>';
    // return $button;
    // }

    public function prepare_items()
    {
        global $wpdb;
        $table_name = $wpdb->prefix . MACYMED_LINK_TRACKER_TABLE_NAME;

        $this->table_data = $this->get_table_data();
        $this->items      = [];
        $this->items      = $this->table_data;

        $columns               = $this->get_columns();
        $hidden                = [];
        $sortable              = $this->get_sortable_columns();
        $this->_column_headers = [$columns, $hidden, $sortable];
    }
    public function extra_tablenav($which)
    {
        if ($which == 'top') { // Afficher uniquement en haut
            $per_page_options = [10, 20, 50, 100]; // Options de sélection
            $current_value    = $this->get_items_per_page('macymed_clicks_per_page', 10); // Valeur actuelle

            echo '<div class="alignleft actions">';
            // echo '<label for="per_page_select">Afficher par page : </label>';
            echo '<select name="per_page" id="per_page_select" onchange="this.form.submit()">';
            foreach ($per_page_options as $option) {
                $selected = $current_value == $option ? 'selected' : '';
                echo "<option value='" . esc_attr($option) . "' " . esc_html($selected) . '>' . esc_html($option) . '</option>';
            }
            echo '</select>';
            echo '</div>';

            ?>
            <div class="alignleft actions">

                <?php

                            do_action('macymed_link_tracker_list_referer_render_actions');
            do_action('macymed_link_tracker_pro_list_referer_render_actions', 'Export CSV','page-referente');
            ?>

            </div>
<?php
        }
    }
    private function get_table_data()
    {
        global $wpdb;

        // Récupérer le nonce depuis l'URL
        $nonce = isset($_GET['mtl_nonce']) ? sanitize_text_field(wp_unslash($_GET['mtl_nonce'])) : '';

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

        $table_name_main   = $wpdb->prefix . MACYMED_LINK_TRACKER_TABLE_NAME;
        $table_name_clicks = $wpdb->prefix . MACYMED_LINK_TRACKER_CLICKS_TABLE_NAME;
        // Récupérer le nombre d'éléments par page depuis la sélection utilisateur

        // Requête principale


        // Pagination
        $this->per_page = $this->set_items_per_page();
        $per_page       = $this->per_page;
        $current_page   = $this->get_pagenum();
        $offset         = ($current_page - 1) * $per_page;

        // Calcul du nombre total d'éléments
        $total_items_query = "
SELECT COUNT(DISTINCT JSON_UNQUOTE(JSON_EXTRACT(h.data, '$.referer')))
FROM {$table_name_clicks} h
WHERE JSON_EXTRACT(h.data, '$.referer') IS NOT NULL
";

        // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $total_items = $wpdb->get_var($total_items_query);
        // ajout du order by
        $orderby = (! empty($_GET['orderby'])) ? sanitize_text_field(wp_unslash($_GET['orderby'])) : 'referer';

        // If no order, default to asc
        $order = (! empty($_GET['order'])) ? sanitize_text_field(wp_unslash($_GET['order'])) : 'desc';
        $query = "
SELECT 
    JSON_UNQUOTE(JSON_EXTRACT(h.data, '$.referer')) AS referer,
    COUNT(h.id) AS total_count
FROM 
    {$table_name_clicks} h
WHERE 
    JSON_EXTRACT(h.data, '$.referer') IS NOT NULL
GROUP BY 
    JSON_UNQUOTE(JSON_EXTRACT(h.data, '$.referer'))
ORDER BY {$orderby} {$order}
LIMIT %d OFFSET %d
";




        // Préparation et exécution de la requête principale
        // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $results = $wpdb->get_results(
            // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $wpdb->prepare($query, $per_page, $offset),
            ARRAY_A
        );

        // Définir les colonnes
        $columns  = $this->get_columns();
        $hidden   = [];
        $sortable = $this->get_sortable_columns();

        $this->_column_headers = [$columns, $hidden, $sortable];

        // Pagination
        $this->set_pagination_args(
            [
                'total_items' => $total_items,
                'per_page'    => $per_page,
                'total_pages' => ceil($total_items / $per_page),
            ]
        );

        return $results;
    }
    public function get_columns()
    {
        return [
            'referer'     => __('Referer', 'macymed-link-tracker'),
            'total_count' => __('Total Count', 'macymed-link-tracker'),
            'details'     => __('Details', 'macymed-link-tracker'),
        ];
    }
    public function get_details_for_referer($referer)
    {
        global $wpdb;
        $table_name_main   = $wpdb->prefix . MACYMED_LINK_TRACKER_TABLE_NAME;
        $table_name_clicks = $wpdb->prefix . MACYMED_LINK_TRACKER_CLICKS_TABLE_NAME;

        $query = "
            SELECT 
                t.url AS linked_url,
                COUNT(h.id) AS occurrence
            FROM 
                {$table_name_clicks} h
            JOIN 
                {$table_name_main} t
            ON 
                h.url_id = t.id
            WHERE 
                JSON_UNQUOTE(JSON_EXTRACT(h.data, '$.referer')) = %s
            GROUP BY 
                t.url
        ";
        // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        return $wpdb->get_results($wpdb->prepare($query, $referer), ARRAY_A);
    }
    // Affichage des colonnes
    public function column_default($item, $column_name)
    {
        switch ($column_name) {
            case 'referer':
                return esc_html($item['referer']);
            case 'total_count':
                return intval($item['total_count']);
            case 'details':
                $button = '<button type="button" class="button details-button details-button-referer" data-referer="' . esc_attr($item['referer']) . '">
                <span class="dashicons dashicons-arrow-down"></span> ' . __('Voir les détails', 'macymed-link-tracker') .  '
            </button>';
                return $button;
                // return '<button type="button" class="button details-button details-button-referer" data-referer="' . esc_attr($item['referer']) . '">
                // <span class="dashicons dashicons-arrow-down"></span>' .
                //  __('Voir les détails', 'macymed-link-tracker') .
                //  '</button>';
            default:
                return isset($item[$column_name]) ? $item[$column_name] : false; // Pour le débogage
        }
    }
    // public function column_details($item)
    // {
    //     // Bouton pour afficher/masquer les sous-lignes
    //     $button = '<button type="button" class="button details-button details-button-referer"" data-referer="' . esc_attr($item['referer']) . '">
    //                    <span class="dashicons dashicons-arrow-down"></span> ' . __('Voir les détails', 'macymed-link-tracker') .  '
    //                </button>';
    //     return $button;
    // }
    public function set_items_per_page()
    {
        // Récupérer le nonce depuis l'URL
        $nonce = isset($_GET['mtl_nonce']) ? sanitize_text_field(wp_unslash($_GET['mtl_nonce'])) : '';

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

        $per_page = isset($_REQUEST['per_page']) ? intval($_REQUEST['per_page']) : $this->get_items_per_page('macymed_clicks_per_page', 10);

        // Sauvegarder dans les options utilisateur
        $screen      = get_current_screen();
        $option_name = $screen->id . '_per_page';
        update_user_meta(get_current_user_id(), $option_name, $per_page);

        return $per_page;
    }

    public function single_row_columns($item)
    {
        list($columns, $hidden) = $this->get_column_info();

        foreach ($columns as $column_name => $column_display_name) {
            $classes    = "class='$column_name column-$column_name'";
            $style      = in_array($column_name, $hidden) ? 'style="display:none;"' : '';
            $attributes = "$classes $style";

            echo '<td ' . esc_attr($attributes) . ' ' . ($column_name === 'url' ? 'colspan="' . 2 . '"' : '') . '>';
            if (method_exists($this, "column_$column_name")) {
                // echo wp_kses(
                //     (call_user_func([$this, "column_$column_name"], $item)),
                //     [
                //         'button' => [
                //             'type'         => [],
                //             'class'        => [],
                //             'data-referer' => [],
                //             'data-url'     => [],
                //             'span'         => [],
                //         ],
                //         'a' => [
                //             'type'         => [],
                //             'class'        => [],
                //             'data-referer' => [],
                //             'data-url'     => [],
                //         ],
                //         'table'  => [],
                //         'tr'     => [],
                //         'td'     => ['style' => []],
                //         'strong' => [],
                //     ]
                // );
                echo esc_html(call_user_func([$this, "column_$column_name"], $item));
            } else {
                echo wp_kses(
                    ($this->column_default($item, $column_name)),
                    [
                        'button' => [
                            'type'         => [],
                            'class'        => [],
                            'data-referer' => [],
                            'data-url'     => [],
                            'span'         => [
                                'class' => []
                            ],
                        ],
                        'span'         => [
                                'class' => []
                            ],
                        'a' => [
                            'type'         => [],
                            'class'        => [],
                            'data-referer' => [],
                            'data-url'     => [],
                        ],
                        'table'  => [],
                        'tr'     => [],
                        'td'     => ['style' => []],
                        'strong' => [],
                    ]
                );
            }
            echo '</td>';
        }
    }

    protected function get_sortable_columns()
    {
        $sortable_columns = [
            'id'     => ['id', true],
            'url'    => ['url', true],
            'clicks' => ['clicks', true],
            'referer' => ['referer', true],
            'total_count' => ['total_count', true],

            // 'last_click'   => array('last_click', true),
            // 'full_url'   => array('full_url', true),
            // 'type_click'   => array('type_click', true),
        ];
        return $sortable_columns;
    }
}
