<?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 AdminTable 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 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 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>';
    }


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

        // Afficher les clics dans une liste
        if (! empty($clicks)) {
            echo '<table class="widefat striped">';

            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>' . esc_html('full_url') . ':</strong></td>';
                $outputData .= '<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>' . esc_html($key) . ':</strong></td>';
                        $outputData .= '<td style="padding:0px 10px 0px 0px;">' . esc_html($value) . '</td>';
                        $outputData .= '</tr>';
                    }
                }

                $outputData .= '</table>';
                echo '<td>' . wp_kses(
                    $outputData,
                    [
                        'table'  => [],
                        'tr'     => [],
                        'td'     => ['style' => []],
                        'strong' => [],
                    ]
                ) . '</td>';
                echo '<td>' . esc_attr($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

    }

    public 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;
    }
    public function column_info($item)
    {
        // Bouton pour afficher/masquer les sous-lignes
        $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 get_columns()
    {
        return [
            'id'      => __('Id', 'macymed-link-tracker'),
            'url'     => __('Url', 'macymed-link-tracker'),
            'clicks'  => __('Nombre d\'affichage', 'macymed-link-tracker'),
            'details' => __('Liste', 'macymed-link-tracker'),
            'info'    => __('Détails', 'macymed-link-tracker'),

        ];
    }

    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>';

            do_action('macymed_link_tracker_list_url_render_actions');
            do_action('macymed_link_tracker_pro_list_url_render_actions', 'Export CSV','page-datterrissage');
        }
    }
    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
        $this->per_page = $this->set_items_per_page();
        // Capture the search term
        $search     = isset($_REQUEST['s']) ? sanitize_text_field(wp_unslash($_REQUEST['s'])) : '';
        $queryCount = "SELECT COUNT(*) FROM $table_name_main";
        if (!empty($search)) {
            $queryCount .= ' WHERE url LIKE %s';
            // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $total_items = $wpdb->get_var($wpdb->prepare($queryCount, '%' . $wpdb->esc_like($search) . '%'));
        } else {
            // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $total_items = $wpdb->get_var($queryCount);
        }

        // Définir les paramètres de pagination
        $this->set_pagination_args(
            [
                'total_items' => $total_items,
                'per_page'    => $this->per_page,
                'total_pages' => ceil($total_items / $this->per_page),
            ]
        );

        // Obtenir les données pour la page courante
        $current_page = $this->get_pagenum();
        $offset       = ($current_page - 1) * $this->per_page;

        $orderby = (! empty($_GET['orderby'])) ? sanitize_text_field(wp_unslash($_GET['orderby'])) : 'id';

        // If no order, default to asc
        $order = (! empty($_GET['order'])) ? sanitize_text_field(wp_unslash($_GET['order'])) : 'desc';


        $sql = "SELECT l.*, COUNT(c.id) AS clicks
        FROM $table_name_main l
        LEFT JOIN $table_name_clicks c ON l.id = c.url_id";

        $parameters = []; // Tableau pour stocker les paramètres sécurisés.

        if (!empty($search)) {
            $sql .= ' WHERE l.url LIKE %s';
            $parameters[] = '%' . $wpdb->esc_like($search) . '%';
        }

        $sql .= "
GROUP BY l.id
ORDER BY $orderby $order
LIMIT %d OFFSET %d";

        $parameters[] = $this->per_page; // Ajout de la limite au tableau des paramètres.
        $parameters[] = $offset;        // Ajout de l'offset au tableau des paramètres.

        // Préparation et exécution de la requête
        // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        return $wpdb->get_results($wpdb->prepare($sql, $parameters), ARRAY_A);
    }
    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 column_default($item, $column_name)
    {

        switch ($column_name) {
            case 'url':
                $toggle_button = '';
                return esc_html($item['url']) . ' ' . $toggle_button;

            default:
                return isset($item[$column_name]) ? esc_html($item[$column_name]) : '';
        }
    }
    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") && (! in_array($column_name, ['info', 'details']))) {
                echo esc_html(call_user_func([$this, "column_$column_name"], $item));
            } elseif (in_array($column_name, ['info', 'details'])) {
                echo wp_kses(
                    call_user_func([$this, "column_$column_name"], $item),
                    [
                        'button' => [
                            'type'         => [],
                            'class'        => [],
                            'data-referer' => [],
                            'data-url'     => [],
                            'data-id'      => [],
                            'data-referer' => [],
                            'data-row'     => [],
                        ],
                        'a'      => [
                            'type'         => [],
                            'class'        => [],
                            'data-referer' => [],
                            'data-url'     => [],
                            'href'         => [],
                            'data-id'      => [],
                            'data-referer' => [],
                            'data-row'     => [],
                        ],
                        'table'  => [],
                        'tr'     => [],
                        'td'     => ['style' => []],
                        'strong' => [],
                        'span'   => ['class' => []],
                    ]
                );
            } else {

                echo wp_kses(
                    ($this->column_default($item, $column_name)),
                    [
                        'button' => [
                            '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],

        ];
        return $sortable_columns;
    }
}
