<?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 AdminTableClicks 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)
    {

        $this->display_clicks_details($item);
    }

    public function print_column_headers($with_id = true)
    {
        // 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 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(wp_unslash($_GET['orderby'])) : '';
        $order   = isset($_GET['order']) && in_array(sanitize_text_field(wp_unslash($_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";
            } elseif ($key === 'data') {
                $colspan = "3";
            }

            // 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  colspan=" . esc_attr($colspan) . " scope='col' class='" . esc_attr($class) . "'>" . esc_html($label) . '</th>';
            }
        }

        echo '</tr>';
    }


    private function display_clicks_details($item)
    {

        echo '<tr>';
        echo '<td >' . esc_html($item['id']) . '</td>';
        echo '<td colspan=2> ' . esc_html($item['url']) . '</td>';

        $data       = json_decode($item['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($item['full_url']) . '</td>';
        $outputData .= '</tr>';
        foreach ($data as $key => $value) {
            if (! $key) {
                continue;
            }
            if (! $value) {
                continue;
            }
            if (is_array($value)) {
                $value = wp_json_encode($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 colspan=3>' . wp_kses(
            $outputData,
            [
                'table'  => [],
                'tr'     => [],
                'td'     => ['style' => []],
                'strong' => [],
            ]
        ) . '</td>';
        // echo '<td>' . esc_html($item['data']) . '</td>';
        echo '<td>' . esc_html($item['type_click']) . '</td>';
        echo '<td>' . esc_html($item['type_url']) . '</td>';

        echo '<td>' . esc_html($item['last_click']) . '</td>';
        echo '</tr>';
    }
    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();
    }
    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 les clics
                   </a>';
        return $button;
    }
    public function get_columns()
    {
        return [
            'id'         => __('Id', 'macymed-link-tracker'),
            'url'        => __('Url', 'macymed-link-tracker'),
            'data'       => __('Données', 'macymed-link-tracker'),
            'type_click' => __('Type', 'macymed-link-tracker'),
            'type_url'   => __('Tracking', 'macymed-link-tracker'),
            'last_click' => __('Date', '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();
        // usort($this->table_data, array(&$this, 'usort_reorder'));
        $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

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

            $current_filter = isset($_REQUEST['type_url']) ? sanitize_text_field(wp_unslash($_REQUEST['type_url'])) : '';
            $date_from      = isset($_REQUEST['date_from']) ? esc_attr(sanitize_text_field(wp_unslash($_REQUEST['date_from']))) : '';
            $date_to        = isset($_REQUEST['date_to']) ? esc_attr(sanitize_text_field(wp_unslash($_REQUEST['date_to']))) : '';
?>
            <div class="alignleft actions">
                <select name="type_url">
                    <option value=""><?php esc_html_e('Tous les types', 'macymed-link-tracker'); ?></option>
                    <option value="internal" <?php selected($current_filter, 'internal'); ?>>
                        <?php esc_html_e('Interne', 'macymed-link-tracker'); ?>
                    </option>
                    <option value="external" <?php selected($current_filter, 'external'); ?>>
                        <?php esc_html_e('Externe', 'macymed-link-tracker'); ?>
                    </option>
                    <option value="inbound" <?php selected($current_filter, 'inbound'); ?>>
                        <?php esc_html_e('Entrant', 'macymed-link-tracker'); ?>
                    </option>
                    <option value="404" <?php selected($current_filter, '404'); ?>>
                        <?php esc_html_e('404', 'macymed-link-tracker'); ?>
                    </option>
                    <option value="excluded_ip" <?php selected($current_filter, 'excluded ip'); ?>>
                        <?php esc_html_e('Ips Exclues', 'macymed-link-tracker'); ?>
                    </option>
                    <option value="direct_access" <?php selected($current_filter, 'direct access'); ?>>
                        <?php esc_html_e('Accès direct', 'macymed-link-tracker'); ?>
                    </option>

                </select>

                <!-- Filtre par date -->
                <input type="date" name="date_from" value="<?php echo esc_attr($date_from); ?>" placeholder="<?php esc_html_e('Date de début', 'macymed-link-tracker'); ?>">
                <input type="date" name="date_to" value="<?php echo esc_attr($date_to); ?>" placeholder="<?php esc_html_e('Date de fin', 'macymed-link-tracker'); ?>">

                <input type="submit" name="filter_action" id="post-query-submit" class="button" value="<?php esc_html_e('Filtrer', 'macymed-link-tracker'); ?>">

                <?php

                do_action('macymed_link_tracker_list_history_render_actions');
                do_action('macymed_link_tracker_pro_list_history_render_actions', 'Export CSV', 'historique');
                ?>

            </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
        $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_clicks c  JOIN $table_name_main l ON c.url_id = l.id ";

        $where = [];
        if (! empty($_REQUEST['type_url'])) {
            $type_url = esc_sql(sanitize_text_field(wp_unslash($_REQUEST['type_url'])));
            $where[]  = "type_url = '$type_url'";
        }
        if (! empty($_REQUEST['date_from'])) {
            $date_from = esc_sql(sanitize_text_field(wp_unslash($_REQUEST['date_from'])));
            $where[]   = "last_click >= '$date_from'";
        }
        if (! empty($_REQUEST['date_to'])) {
            $date_to = esc_sql(sanitize_text_field(wp_unslash($_REQUEST['date_to'])));
            $where[] = "last_click <= '$date_to'";
        }
        if (! empty($search)) {
            $where[] = $wpdb->prepare('url LIKE %s', '%' . $wpdb->esc_like($search) . '%');
        }

        if (! empty($where)) {
            $queryCount .= ' WHERE ' . implode(' AND ', $where);
        }
        // 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'])) : 'last_click';

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

        $sql = "SELECT c.*, l.url
FROM  $table_name_clicks c  JOIN $table_name_main l ON c.url_id = l.id
    
    ";
        if (! empty($where)) {
            $sql .= ' WHERE ' . implode(' AND ', $where);
        }
        $sql .= "


ORDER BY $orderby $order LIMIT " . $this->per_page . ' OFFSET ' . $offset . ';';


        // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        return $wpdb->get_results(
            // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $sql,
            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")) {

                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'     => [],
                        ],
                        'table'  => [],
                        'tr'     => [],
                        'td'     => ['style' => []],
                        'strong' => [],
                    ]
                );
            }
            echo '</td>';
        }
    }


    protected function get_sortable_columns()
    {
        $sortable_columns = [
            'id'         => ['id', true],
            'url'        => ['url', true],
            'type_click' => ['type_click', true],
            'last_click' => ['last_click', true],
        ];
        return $sortable_columns;
    }
}
