<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit; // Salir si se accede directamente
}

/**
 * Agregar menús al panel de administración de WordPress.
 */
function clickbutton_add_admin_menu() {
    add_menu_page(
        __( 'Click Button', 'clickbutton' ), // Título de la página
        __( 'Click Button', 'clickbutton' ), // Título del menú
        'manage_options',
        'clickbutton',
        'clickbutton_dashboard_page',
        'dashicons-admin-links',
        6
    );

    // Submenú: Estadísticas (Reemplaza el submenú predeterminado)
    add_submenu_page(
        'clickbutton',
        __( 'Estadísticas', 'clickbutton' ),
        __( 'Estadísticas', 'clickbutton' ),
        'manage_options',
        'clickbutton',
        'clickbutton_dashboard_page'
    );

    // Submenú: Gestión
    add_submenu_page(
        'clickbutton',
        __( 'Gestión', 'clickbutton' ),
        __( 'Gestión', 'clickbutton' ),
        'manage_options',
        'clickbutton_buttons',
        'clickbutton_buttons_page'
    );
}
add_action( 'admin_menu', 'clickbutton_add_admin_menu' );

/**
 * Página del Dashboard con Estadísticas de Botones.
 */
function clickbutton_dashboard_page() {
    if ( ! current_user_can( 'manage_options' ) ) {
        return;
    }

    global $wpdb;
    $table_buttons = $wpdb->prefix . 'clickbutton_buttons';
    $table_clicks  = $wpdb->prefix . 'clickbutton_clicks';

    // Verificar si se está solicitando una vista detallada
    $button_id = isset( $_GET['button_id'] ) ? intval( $_GET['button_id'] ) : 0;

    if ( $button_id > 0 ) {
        display_clickbutton_details( $button_id );
    } else {
        display_clickbutton_dashboard();
    }
}

/**
 * Función para mostrar la vista principal del dashboard.
 */
function display_clickbutton_dashboard() {
    global $wpdb;
    $table_buttons = $wpdb->prefix . 'clickbutton_buttons';
    $table_clicks  = $wpdb->prefix . 'clickbutton_clicks';

    // Parámetros de búsqueda para estadísticas (si aplica)
    $search_date = isset( $_GET['search_date'] ) ? sanitize_text_field( $_GET['search_date'] ) : '';
    $search_name = isset( $_GET['search_name'] ) ? sanitize_text_field( $_GET['search_name'] ) : '';

    // Parámetros de paginación
    $current_page = isset( $_GET['paged'] ) && is_numeric( $_GET['paged'] ) ? intval( $_GET['paged'] ) : 1;
    $per_page     = 20; // Número de elementos por página
    $offset       = ( $current_page - 1 ) * $per_page;

    // Construir la consulta con filtros de búsqueda
    $where  = "WHERE 1=1";
    $params = array();
    
    if ( ! empty( $search_date ) ) {
        $where  .= " AND DATE(c.click_time) = %s";
        $params[] = $search_date;
    }
    
    if ( ! empty( $search_name ) ) {
        $where  .= " AND b.name LIKE %s";
        $params[] = '%' . $wpdb->esc_like( $search_name ) . '%';
    }

    // Obtener el total de botones filtrados
    if ( ! empty( $search_date ) ) {
        $total_items_query = "SELECT COUNT(*) 
                              FROM (
                                  SELECT b.id
                                  FROM $table_buttons b
                                  LEFT JOIN $table_clicks c ON b.id = c.button_id
                                  $where
                                  GROUP BY b.id, b.css_id, b.name
                                  HAVING DATE(c.click_time) = %s
                              ) as filtered_buttons";
        $total_items = $wpdb->get_var( $wpdb->prepare( $total_items_query, $search_date ) );
    } else {
        if ( ! empty( $search_name ) ) {
            $total_items_query = "SELECT COUNT(*) 
                                  FROM (
                                      SELECT b.id
                                      FROM $table_buttons b
                                      LEFT JOIN $table_clicks c ON b.id = c.button_id
                                      $where
                                      GROUP BY b.id, b.css_id, b.name
                                  ) as filtered_buttons";
            $total_items = $wpdb->get_var( $wpdb->prepare( $total_items_query, $params ) );
        } else {
            // Sin filtros, contar todos los botones
            $total_items_query = "SELECT COUNT(*) FROM $table_buttons";
            $total_items = $wpdb->get_var( $total_items_query );
        }
    }

    // Calcular el total de páginas
    $total_pages = ceil( $total_items / $per_page );

    // Consulta para obtener los registros con filtros y paginación
    $results_query = "SELECT b.id, b.css_id, b.name, COUNT(c.id) as clics, MAX(c.click_time) as ultimo_clic
                     FROM $table_buttons b
                     LEFT JOIN $table_clicks c ON b.id = c.button_id
                     $where
                     GROUP BY b.id, b.css_id, b.name
                     ORDER BY clics DESC
                     LIMIT %d OFFSET %d";

    $params_with_pagination = $params;
    $params_with_pagination[] = $per_page;
    $params_with_pagination[] = $offset;

    if ( ! empty( $search_date ) ) {
        $results = $wpdb->get_results( $wpdb->prepare( $results_query, array_merge( $params, array( $per_page, $offset ) ) ) );
    } elseif ( ! empty( $search_name ) ) {
        $results = $wpdb->get_results( $wpdb->prepare( $results_query, array_merge( $params, array( $per_page, $offset ) ) ) );
    } else {
        $results = $wpdb->get_results( $wpdb->prepare( $results_query, array( $per_page, $offset ) ) );
    }

    // Usar el slug correcto 'clickbutton'
    $base_url = admin_url( 'admin.php?page=clickbutton' );

    // Depuración: Registrar la URL base
    error_log( 'CLICKBUTTON DEBUG: base_url = ' . $base_url );

    ?>
    <div class="wrap">
        <h1><?php esc_html_e( 'Estadísticas de Botones', 'clickbutton' ); ?></h1>

        <!-- Barra de Herramientas: Exportación y Buscador -->
        <div class="clickbutton-toolbar" style="display: flex; justify-content: space-between; margin-bottom: 20px; flex-wrap: wrap;">
            <!-- Exportación a la Izquierda -->
            <div class="export-buttons" style="margin-bottom: 10px;">
                <a href="<?php echo esc_url( add_query_arg( array( 'clickbutton_export' => 'csv', 'search_date' => $search_date, 'search_name' => $search_name ), $base_url ) ); ?>" class="button"><b><?php _e( '<i class="fas fa-file-csv"></i> Exportar a CSV', 'clickbutton' ); ?></b></a>
                <a href="<?php echo esc_url( add_query_arg( array( 'clickbutton_export' => 'pdf', 'search_date' => $search_date, 'search_name' => $search_name ), $base_url ) ); ?>" class="button"><b><?php _e( '<i class="fas fa-file-pdf"></i> Exportar a PDF', 'clickbutton' ); ?></b></a>
                <a href="<?php echo esc_url( add_query_arg( array( 'clickbutton_export' => 'excel', 'search_date' => $search_date, 'search_name' => $search_name ), $base_url ) ); ?>" class="button"><b><?php _e( '<i class="fas fa-file-excel"></i> Exportar a Excel', 'clickbutton' ); ?></b></a>
            </div>

            <!-- Buscador a la Derecha -->
            <div class="search-box">
                <form method="get" action="<?php echo esc_url( $base_url ); ?>">
                    <input type="hidden" name="page" value="clickbutton">
                    <label for="search_date" style="margin-right: 10px;"><?php _e( 'Fecha:', 'clickbutton' ); ?></label>
                    <input type="date" id="search_date" name="search_date" value="<?php echo esc_attr( $search_date ); ?>" style="margin-right: 20px;">

                    <label for="search_name" style="margin-right: 10px;"><?php _e( 'Nombre:', 'clickbutton' ); ?></label>
                    <input type="text" id="search_name" name="search_name" value="<?php echo esc_attr( $search_name ); ?>" placeholder="<?php esc_attr_e( 'Buscar por Nombre', 'clickbutton' ); ?>" style="margin-right: 20px;">

                    <input type="submit" value="<?php esc_attr_e( 'Buscar', 'clickbutton' ); ?>" class="button button-primary">
                </form>
            </div>
        </div>

        <!-- Mostrar Total de Clics -->
        <h2><?php esc_html_e( 'Total de Clics:', 'clickbutton' ); ?> <span style="color:green"><strong><?php echo esc_html( $total_items ); ?></strong></span></h2>

        <!-- Tabla de Estadísticas -->
        <table class="wp-list-table widefat fixed striped">
            <thead>
                <tr>
                    <th><center><?php esc_html_e( 'ID', 'clickbutton' ); ?></center></th>
                    <th><center><?php esc_html_e( 'Nombre', 'clickbutton' ); ?></center></th>
                    <th><center><?php esc_html_e( 'Clics', 'clickbutton' ); ?></center></th>
                    <th><center><?php esc_html_e( 'Último Clic (Fecha)', 'clickbutton' ); ?></center></th>
                    <th><center><?php esc_html_e( 'Último Clic (Hora)', 'clickbutton' ); ?></center></th>
                    <th><center><?php esc_html_e( 'Acciones', 'clickbutton' ); ?></center></th>
                </tr>
            </thead>
            <tbody>
                <?php if ( ! empty( $results ) ) : ?>
                    <?php foreach ( $results as $row ) : ?>
                        <tr>
                            <td><center><?php echo esc_html( $row->css_id ); ?></center></td>
                            <td><center><?php echo esc_html( $row->name ); ?></center></td>
                            <td><center><?php echo esc_html( $row->clics ); ?></center></td>
                            <td><center><?php echo esc_html( get_date_from_gmt( $row->ultimo_clic, get_option( 'date_format' ) ) ); ?></center></td>
                            <td><center><?php echo esc_html( get_date_from_gmt( $row->ultimo_clic, get_option( 'time_format' ) ) ); ?></center></td>
                            <td><center>
                                <!-- Enlace a la vista detallada -->
                                <a href="<?php echo esc_url( add_query_arg( array( 'page' => 'clickbutton', 'button_id' => $row->id ), admin_url( 'admin.php' ) ) ); ?>" class="button view-details-button">
                                    <i class="fa-solid fa-circle-info"></i> <b><?php esc_html_e( 'Ver Detalles', 'clickbutton' ); ?></b>
                                </a>
                                </center>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php else : ?>
                    <tr>
                        <td colspan="6"><?php esc_html_e( 'No se encontraron estadísticas.', 'clickbutton' ); ?></td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>

        <!-- Paginación -->
        <?php
        if ( $total_pages > 1 ) {
            // Mantener los parámetros de búsqueda en la paginación
            $pagination_args = array(
                'base'      => add_query_arg( 'paged', '%#%' ),
                'format'    => '',
                'prev_text' => __( '&laquo;', 'clickbutton' ),
                'next_text' => __( '&raquo;', 'clickbutton' ),
                'total'     => $total_pages,
                'current'   => $current_page,
                'add_args'  => array(
                    'search_date' => $search_date,
                    'search_name' => $search_name,
                ),
            );

            // En algunos casos, WordPress puede remover ciertos argumentos
            if ( strpos( $base_url, '?' ) === false ) {
                $pagination_args['base'] = $base_url . '?paged=%#%';
            }

            $page_links = paginate_links( $pagination_args );

            if ( $page_links ) {
                echo '<div class="tablenav top">';
                echo '<div class="tablenav-pages">';
                echo $page_links;
                echo '</div>';
                echo '</div>';
            }
        }
        ?>
    </div>
    <?php
}

/**
 * Función para mostrar detalles de clics de un botón específico
 */
function display_clickbutton_details( $button_id ) {
    global $wpdb;
    $table_buttons = $wpdb->prefix . 'clickbutton_buttons';
    $table_clicks  = $wpdb->prefix . 'clickbutton_clicks';

    // Obtener información del botón
    $button = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $table_buttons WHERE id = %d", $button_id ) );

    if ( ! $button ) {
        echo '<div class="error"><p>' . esc_html__( 'Botón no encontrado.', 'clickbutton' ) . '</p></div>';
        return;
    }

    // Parámetros de filtro por fecha
    $filter_date = isset( $_GET['filter_date'] ) ? sanitize_text_field( $_GET['filter_date'] ) : '';

    // Parámetros de paginación
    $current_page = isset( $_GET['paged'] ) && is_numeric( $_GET['paged'] ) ? intval( $_GET['paged'] ) : 1;
    $per_page     = 20; // Número de elementos por página
    $offset       = ( $current_page - 1 ) * $per_page;

    // Construir la consulta con filtros
    $where  = "WHERE c.button_id = %d";
    $params = array( $button_id );

    if ( ! empty( $filter_date ) ) {
        $where  .= " AND DATE(c.click_time) = %s";
        $params[] = $filter_date;
    }

    // Consulta para obtener el total de registros filtrados
    $total_items_query = "SELECT COUNT(*) FROM $table_clicks c $where";

    $total_items = $wpdb->get_var( $wpdb->prepare( $total_items_query, $params ) );

    // Calcular el total de páginas
    $total_pages = ceil( $total_items / $per_page );

    // Construir la consulta para obtener los clics con filtros y paginación
    $results_query = "SELECT * FROM $table_clicks c $where ORDER BY click_time DESC LIMIT %d OFFSET %d";
    $params_with_pagination = $params;
    $params_with_pagination[] = $per_page;
    $params_with_pagination[] = $offset;

    $clicks = $wpdb->get_results( $wpdb->prepare( $results_query, $params_with_pagination ) );

    // URL base para paginación y exportación
    $base_url = admin_url( 'admin.php?page=clickbutton&button_id=' . $button_id );

    ?>
    <div class="wrap">
        <h1><?php printf( esc_html__( 'Detalles del Botón: %s', 'clickbutton' ), esc_html( $button->name ) ); ?></h1>

        <!-- Barra de Herramientas: Exportación y Filtro por Fecha -->
        <div class="clickbutton-toolbar" style="display: flex; justify-content: space-between; margin-bottom: 20px; flex-wrap: wrap;">
            <!-- Exportación a la Izquierda -->
            <div class="export-buttons" style="margin-bottom: 10px;">
                <a href="<?php echo esc_url( add_query_arg( array( 'clickbutton_export' => 'csv', 'button_id' => $button_id, 'filter_date' => $filter_date ), $base_url ) ); ?>" class="button"><?php _e( '<i class="fas fa-file-csv"></i> Exportar a CSV', 'clickbutton' ); ?></a>
                <a href="<?php echo esc_url( add_query_arg( array( 'clickbutton_export' => 'pdf', 'button_id' => $button_id, 'filter_date' => $filter_date ), $base_url ) ); ?>" class="button"><?php _e( '<i class="fas fa-file-pdf"></i> Exportar a PDF', 'clickbutton' ); ?></a>
                <a href="<?php echo esc_url( add_query_arg( array( 'clickbutton_export' => 'excel', 'button_id' => $button_id, 'filter_date' => $filter_date ), $base_url ) ); ?>" class="button"><?php _e( '<i class="fas fa-file-excel"></i> Exportar a Excel', 'clickbutton' ); ?></a>
            </div>

            <!-- Filtro por Fecha a la Derecha -->
            <div class="search-box">
                <form method="get" action="<?php echo esc_url( $base_url ); ?>">
                    <input type="hidden" name="page" value="clickbutton">
                    <input type="hidden" name="button_id" value="<?php echo esc_attr( $button_id ); ?>">

                    <label for="filter_date" style="margin-right: 10px;"><?php _e( 'Filtrar por Fecha:', 'clickbutton' ); ?></label>
                    <input type="date" id="filter_date" name="filter_date" value="<?php echo esc_attr( $filter_date ); ?>" style="margin-right: 20px;">

                    <input type="submit" value="<?php esc_attr_e( 'Filtrar', 'clickbutton' ); ?>" class="button button-primary">
                    <a href="<?php echo esc_url( remove_query_arg( array( 'filter_date', 'paged' ), $base_url ) ); ?>" class="button"><i class="fa-solid fa-power-off"></i> <b><?php esc_html_e( 'Restablecer', 'clickbutton' ); ?></b></a>
                </form>
            </div>
        </div>
        
        <!-- Mostrar Total de Clics -->
        <h2><?php esc_html_e( 'Total de Clics:', 'clickbutton' ); ?> <span style="color:green"><strong><?php echo esc_html( $total_items ); ?></strong></span></h2>

        <!-- Tabla de Detalles de Clics -->
        <table class="wp-list-table widefat fixed striped">
            <thead>
                <tr>
                    <th><center><?php esc_html_e( 'Fecha', 'clickbutton' ); ?></center></th>
                    <th><center><?php esc_html_e( 'Hora', 'clickbutton' ); ?></center></th>
                    <th><center><?php esc_html_e( 'IP del Usuario', 'clickbutton' ); ?></center></th>
                    <th><center><?php esc_html_e( 'Agente de Usuario', 'clickbutton' ); ?></center></th>
                </tr>
            </thead>
            <tbody>
                <?php if ( ! empty( $clicks ) ) : ?>
                    <?php foreach ( $clicks as $click ) : ?>
                        <tr>
                            <td><center><?php echo esc_html( get_date_from_gmt( $click->click_time, get_option( 'date_format' ) ) ); ?></center></td>
                            <td><center><?php echo esc_html( get_date_from_gmt( $click->click_time, get_option( 'time_format' ) ) ); ?></center></td>
                            <td><center><?php echo esc_html( $click->user_ip ); ?></center></td>
                            <td><center><?php echo esc_html( $click->user_agent ); ?></center></td>
                        </tr>
                    <?php endforeach; ?>
                <?php else : ?>
                    <tr>
                        <td colspan="4"><?php esc_html_e( 'No se encontraron clics para este botón.', 'clickbutton' ); ?></td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>

        <!-- Paginación -->
        <?php
        if ( $total_pages > 1 ) {
            // Mantener los parámetros de búsqueda en la paginación
            $pagination_args = array(
                'base'      => add_query_arg( 'paged', '%#%' ),
                'format'    => '',
                'prev_text' => __( '&laquo;', 'clickbutton' ),
                'next_text' => __( '&raquo;', 'clickbutton' ),
                'total'     => $total_pages,
                'current'   => $current_page,
                'add_args'  => array(
                    'button_id'   => $button_id,
                    'filter_date' => $filter_date,
                ),
            );

            // En algunos casos, WordPress puede remover ciertos argumentos
            if ( strpos( $base_url, '?' ) === false ) {
                $pagination_args['base'] = $base_url . '?paged=%#%';
            }

            $page_links = paginate_links( $pagination_args );

            if ( $page_links ) {
                echo '<div class="tablenav top">';
                echo '<div class="tablenav-pages">';
                echo $page_links;
                echo '</div>';
                echo '</div>';
            }
        }
        ?>
    </div>
    <?php
}

/**
 * Página de Gestión de Botones con Búsqueda y Paginación.
 */
function clickbutton_buttons_page() {
    if ( ! current_user_can( 'manage_options' ) ) {
        return;
    }

    global $wpdb;
    $table_buttons = $wpdb->prefix . 'clickbutton_buttons';

    // Manejar acciones de agregar, editar, eliminar
    if ( isset( $_POST['action'] ) ) {
        // Agregar Botón
        if ( $_POST['action'] === 'add' ) {
            check_admin_referer( 'clickbutton_add_button', 'clickbutton_nonce' );

            $css_id = isset( $_POST['css_id'] ) ? sanitize_text_field( $_POST['css_id'] ) : '';
            $name   = isset( $_POST['name'] ) ? sanitize_text_field( $_POST['name'] ) : '';

            if ( empty( $css_id ) || empty( $name ) ) {
                echo '<div class="error"><p>' . esc_html__( 'Todos los campos son obligatorios.', 'clickbutton' ) . '</p></div>';
            } else {
                // Verificar unicidad del CSS ID
                $existing = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $table_buttons WHERE css_id = %s", $css_id ) );
                if ( $existing > 0 ) {
                    echo '<div class="error"><p>' . esc_html__( 'El ID ya está registrado.', 'clickbutton' ) . '</p></div>';
                } else {
                    $inserted = $wpdb->insert(
                        $table_buttons,
                        array(
                            'css_id' => $css_id,
                            'name'   => $name,
                        ),
                        array(
                            '%s',
                            '%s',
                        )
                    );

                    if ( $inserted ) {
                        echo '<div class="updated"><p>' . esc_html__( 'Botón agregado exitosamente.', 'clickbutton' ) . '</p></div>';
                    } else {
                        echo '<div class="error"><p>' . esc_html__( 'Error al agregar el botón.', 'clickbutton' ) . '</p></div>';
                    }
                }
            }
        }

        // Editar Botón
        if ( $_POST['action'] === 'edit' ) {
            check_admin_referer( 'clickbutton_edit_button', 'clickbutton_nonce' );

            $id     = isset( $_POST['id'] ) ? intval( $_POST['id'] ) : 0;
            $css_id = isset( $_POST['css_id'] ) ? sanitize_text_field( $_POST['css_id'] ) : '';
            $name   = isset( $_POST['name'] ) ? sanitize_text_field( $_POST['name'] ) : '';

            if ( empty( $css_id ) || empty( $name ) ) {
                echo '<div class="error"><p>' . esc_html__( 'Todos los campos son obligatorios.', 'clickbutton' ) . '</p></div>';
            } else {
                // Verificar si el nuevo CSS ID ya está en uso por otro botón
                $existing = $wpdb->get_var(
                    $wpdb->prepare(
                        "SELECT COUNT(*) FROM $table_buttons WHERE css_id = %s AND id != %d",
                        $css_id,
                        $id
                    )
                );

                if ( $existing > 0 ) {
                    echo '<div class="error"><p>' . esc_html__( 'El ID ya está registrado por otro botón.', 'clickbutton' ) . '</p></div>';
                } else {
                    $updated = $wpdb->update(
                        $table_buttons,
                        array(
                            'css_id' => $css_id,
                            'name'   => $name,
                        ),
                        array( 'id' => $id ),
                        array(
                            '%s',
                            '%s',
                        ),
                        array( '%d' )
                    );

                    if ( $updated ) {
                        echo '<div class="updated"><p>' . esc_html__( 'Botón actualizado exitosamente.', 'clickbutton' ) . '</p></div>';
                    } else {
                        echo '<div class="error"><p>' . esc_html__( 'Error al actualizar el botón.', 'clickbutton' ) . '</p></div>';
                    }
                }
            }
        }

        // Eliminar Botón
        if ( $_POST['action'] === 'delete' ) {
            check_admin_referer( 'clickbutton_delete_button', 'clickbutton_nonce' );

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

            if ( $id > 0 ) {
                $deleted = $wpdb->delete( $table_buttons, array( 'id' => $id ), array( '%d' ) );

                if ( $deleted ) {
                    echo '<div class="updated"><p>' . esc_html__( 'Botón eliminado exitosamente.', 'clickbutton' ) . '</p></div>';
                } else {
                    echo '<div class="error"><p>' . esc_html__( 'Error al eliminar el botón.', 'clickbutton' ) . '</p></div>';
                }
            } else {
                echo '<div class="error"><p>' . esc_html__( 'ID de botón inválido.', 'clickbutton' ) . '</p></div>';
            }
        }
    }

    // Parámetros de búsqueda y paginación
    $search_date = isset( $_GET['search_date'] ) ? sanitize_text_field( $_GET['search_date'] ) : '';
    $search_name = isset( $_GET['search_name'] ) ? sanitize_text_field( $_GET['search_name'] ) : '';
    $current_page  = isset( $_GET['paged'] ) && is_numeric( $_GET['paged'] ) ? intval( $_GET['paged'] ) : 1;
    $per_page      = 20; // Número de botones por página
    $offset        = ( $current_page - 1 ) * $per_page;

    // Construir la consulta con filtros de búsqueda
    $where  = "WHERE 1=1";
    $params = array();

    if ( ! empty( $search_date ) ) {
        $where  .= " AND DATE(c.click_time) = %s";
        $params[] = $search_date;
    }

    if ( ! empty( $search_name ) ) {
        $where  .= " AND b.name LIKE %s";
        $params[] = '%' . $wpdb->esc_like( $search_name ) . '%';
    }

    // Obtener el total de botones filtrados
    if ( ! empty( $search_date ) ) {
        $total_items_query = "SELECT COUNT(*) 
                              FROM (
                                  SELECT b.id
                                  FROM $table_buttons b
                                  LEFT JOIN $table_clicks c ON b.id = c.button_id
                                  $where
                                  GROUP BY b.id, b.css_id, b.name
                                  HAVING DATE(c.click_time) = %s
                              ) as filtered_buttons";
        $total_items = $wpdb->get_var( $wpdb->prepare( $total_items_query, $search_date ) );
    } else {
        if ( ! empty( $search_name ) ) {
            $total_items_query = "SELECT COUNT(*) 
                                  FROM (
                                      SELECT b.id
                                      FROM $table_buttons b
                                      LEFT JOIN $table_clicks c ON b.id = c.button_id
                                      $where
                                      GROUP BY b.id, b.css_id, b.name
                                  ) as filtered_buttons";
            $total_items = $wpdb->get_var( $wpdb->prepare( $total_items_query, $params ) );
        } else {
            // Sin filtros, contar todos los botones
            $total_items_query = "SELECT COUNT(*) FROM $table_buttons";
            $total_items = $wpdb->get_var( $total_items_query );
        }
    }

    // Calcular el total de páginas
    $total_pages = ceil( $total_items / $per_page );

    // Consulta para obtener los botones con filtros y paginación
    if ( ! empty( $search_date ) ) {
        $buttons_query = "SELECT * FROM (
                            SELECT b.id, b.css_id, b.name, COUNT(c.id) as clics, MAX(c.click_time) as ultimo_clic
                            FROM $table_buttons b
                            LEFT JOIN $table_clicks c ON b.id = c.button_id
                            $where
                            GROUP BY b.id, b.css_id, b.name
                            HAVING DATE(c.click_time) = %s
                          ) as filtered_buttons
                          ORDER BY filtered_buttons.clics DESC
                          LIMIT %d OFFSET %d";
        $buttons = $wpdb->get_results( $wpdb->prepare( $buttons_query, array_merge( $params, array( $per_page, $offset ) ) ) );
    } else {
        $buttons_query = "SELECT * FROM $table_buttons b
                          LEFT JOIN $table_clicks c ON b.id = c.button_id
                          $where
                          GROUP BY b.id, b.css_id, b.name
                          ORDER BY b.id DESC
                          LIMIT %d OFFSET %d";
        $buttons = $wpdb->get_results( $wpdb->prepare( $buttons_query, array( $per_page, $offset ) ) );
    }

    // URL base para paginación y acciones
    $base_url = admin_url( 'admin.php?page=clickbutton_buttons' );

    ?>
    <div class="wrap">
        <h1><?php esc_html_e( 'Gestión de Botones', 'clickbutton' ); ?></h1>

        <!-- Formulario para Agregar Nuevo Botón -->
        <h2><?php esc_html_e( 'Agregar Nuevo Botón', 'clickbutton' ); ?></h2>
        <form method="post" style="margin-bottom: 20px;">
            <?php wp_nonce_field( 'clickbutton_add_button', 'clickbutton_nonce' ); ?>
            <input type="hidden" name="action" value="add">
            <label for="css_id"><?php esc_html_e( 'ID', 'clickbutton' ); ?></label>
            <input type="text" id="css_id" name="css_id" required class="regular-text" placeholder="id_button" style="margin-right: 20px;">
            <label for="name"><?php esc_html_e( 'Nombre', 'clickbutton' ); ?></label>
            <input type="text" id="name" name="name" required class="regular-text" placeholder="Botón WhatsApp" style="margin-right: 20px;">
            <?php submit_button( __( 'Agregar Botón', 'clickbutton' ) ); ?>
        </form>

        <!-- Formulario de Búsqueda -->
        <h2><?php esc_html_e( 'Botones Existentes', 'clickbutton' ); ?></h2>
        <form method="get" action="<?php echo esc_url( $base_url ); ?>" style="margin-bottom: 20px;">
            <input type="hidden" name="page" value="clickbutton_buttons">
            <label for="search_date" style="margin-right: 10px;"><?php _e( 'Fecha:', 'clickbutton' ); ?></label>
            <input type="date" id="search_date" name="search_date" value="<?php echo esc_attr( $search_date ); ?>" placeholder="<?php esc_attr_e( 'Buscar por Fecha', 'clickbutton' ); ?>" style="margin-right: 20px;">

            <label for="search_name" style="margin-right: 10px;"><?php _e( 'Nombre:', 'clickbutton' ); ?></label>
            <input type="text" id="search_name" name="search_name" value="<?php echo esc_attr( $search_name ); ?>" placeholder="<?php esc_attr_e( 'Buscar por Nombre', 'clickbutton' ); ?>" style="margin-right: 20px;">

            <input type="submit" value="<?php esc_attr_e( 'Buscar', 'clickbutton' ); ?>" class="button button-primary">
            <a href="<?php echo esc_url( $base_url ); ?>" class="button"><i class="fa-solid fa-power-off"></i> <b><?php esc_html_e( 'Restablecer', 'clickbutton' ); ?></b></a>
        </form>

        <!-- Tabla de Botones Existentes -->
        <table class="wp-list-table widefat fixed striped">
            <thead>
                <tr>
                    <th><center><?php esc_html_e( 'ID', 'clickbutton' ); ?></center></th>
                    <th><center><?php esc_html_e( 'ID BUTTON', 'clickbutton' ); ?></center></th>
                    <th><center><?php esc_html_e( 'NOMBRE', 'clickbutton' ); ?></center></th>
                    <th><center><?php esc_html_e( 'ACCIONES', 'clickbutton' ); ?></center></th>
                </tr>
            </thead>
            <tbody>
                <?php if ( ! empty( $buttons ) ) : ?>
                    <?php foreach ( $buttons as $button ) : ?>
                        <tr>
                            <td><center><?php echo esc_html( $button->id ); ?></center></td>
                            <td><center><?php echo esc_html( $button->css_id ); ?></center></td>
                            <td><center><?php echo esc_html( $button->name ); ?></center></td>
                            <td><center>
                                <!-- Editar -->
                                <button class="button edit-button" data-id="<?php echo esc_attr( $button->id ); ?>" data-css_id="<?php echo esc_attr( $button->css_id ); ?>" data-name="<?php echo esc_attr( $button->name ); ?>"><i class="fas fa-edit"></i> <b><?php esc_html_e( 'Editar', 'clickbutton' ); ?></b></button>

                                <!-- Eliminar -->
                                <form method="post" style="display:inline;">
                                    <?php wp_nonce_field( 'clickbutton_delete_button', 'clickbutton_nonce' ); ?>
                                    <input type="hidden" name="action" value="delete">
                                    <input type="hidden" name="id" value="<?php echo esc_attr( $button->id ); ?>">
                                    <button type="submit" class="button delete-button" onclick="return confirm('<?php echo esc_js( __( '¿Estás seguro de eliminar este botón?', 'clickbutton' ) ); ?>');"><i class="fas fa-trash"></i> <b><?php esc_html_e( 'Eliminar', 'clickbutton' ); ?></b></button>
                                </form>
                                </center>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php else : ?>
                    <tr>
                        <td colspan="4"><?php esc_html_e( 'No se encontraron botones.', 'clickbutton' ); ?></td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>

        <!-- Paginación -->
        <?php
        if ( $total_pages > 1 ) {
            // Mantener los parámetros de búsqueda en la paginación
            $pagination_args = array(
                'base'      => add_query_arg( 'paged', '%#%' ),
                'format'    => '',
                'prev_text' => __( '&laquo;', 'clickbutton' ),
                'next_text' => __( '&raquo;', 'clickbutton' ),
                'total'     => $total_pages,
                'current'   => $current_page,
                'add_args'  => array(
                    'search_date' => $search_date,
                    'search_name' => $search_name,
                ),
            );

            // En algunos casos, WordPress puede remover ciertos argumentos
            if ( strpos( $base_url, '?' ) === false ) {
                $pagination_args['base'] = $base_url . '?paged=%#%';
            }

            $page_links = paginate_links( $pagination_args );

            if ( $page_links ) {
                echo '<div class="tablenav top">';
                echo '<div class="tablenav-pages">';
                echo $page_links;
                echo '</div>';
                echo '</div>';
            }
        }
        ?>

        <!-- Modal para Editar Botón -->
        <div id="edit-button-modal" style="display:none; position:fixed; top:50%; left:50%; transform:translate(-50%, -50%); background:#fff; padding:30px; border:1px solid #ccc; z-index:1000; width:580px;">
            <h2><?php esc_html_e( 'Editar Botón', 'clickbutton' ); ?></h2>
            <button class="close-modal" style="float:right; background:none; border:none; font-size:24px; cursor:pointer;">&times;</button>
            <form method="post">
                <?php wp_nonce_field( 'clickbutton_edit_button', 'clickbutton_nonce' ); ?>
                <input type="hidden" name="action" value="edit">
                <input type="hidden" name="id" id="edit-button-id">
                <table class="form-table">
                    <tr valign="top">
                        <th scope="row"><label for="edit-css_id"><?php esc_html_e( 'ID BUTTON', 'clickbutton' ); ?></label></th>
                        <td><input type="text" id="edit-css_id" name="css_id" required class="regular-text" style="width: 100%;"></td>
                    </tr>
                    <tr valign="top">
                        <th scope="row"><label for="edit-name"><?php esc_html_e( 'Nombre', 'clickbutton' ); ?></label></th>
                        <td><input type="text" id="edit-name" name="name" required class="regular-text" style="width: 100%;"></td>
                    </tr>
                </table>
                <?php submit_button( __( 'Actualizar Botón', 'clickbutton' ) ); ?>
            </form>
        </div>

        <!-- JavaScript para manejar el modal -->
        <script>
        document.addEventListener('DOMContentLoaded', function() {
            const editButtons = document.querySelectorAll('.edit-button');
            const modal = document.getElementById('edit-button-modal');
            const closeModalBtn = modal.querySelector('.close-modal');

            editButtons.forEach(button => {
                button.addEventListener('click', function() {
                    const id = this.getAttribute('data-id');
                    const css_id = this.getAttribute('data-css_id');
                    const name = this.getAttribute('data-name');

                    document.getElementById('edit-button-id').value = id;
                    document.getElementById('edit-css_id').value = css_id;
                    document.getElementById('edit-name').value = name;

                    modal.style.display = 'block';
                });
            });

            closeModalBtn.addEventListener('click', function() {
                modal.style.display = 'none';
            });

            // Cerrar el modal al hacer clic fuera de él
            window.addEventListener('click', function(event) {
                if (event.target == modal) {
                    modal.style.display = 'none';
                }
            });
        });
        </script>
    </div>
    <?php
}
?>
