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

// Agregar acciones para exportar
function clickbutton_handle_export() {
    if ( isset( $_GET['clickbutton_export'] ) && current_user_can( 'manage_options' ) ) {
        $format = sanitize_text_field( $_GET['clickbutton_export'] );

        // Verificar si se está exportando datos detallados
        $button_id    = isset( $_GET['button_id'] ) ? intval( $_GET['button_id'] ) : 0;
        $filter_date  = isset( $_GET['filter_date'] ) ? sanitize_text_field( $_GET['filter_date'] ) : '';

        export_clickbutton_data( $format, $button_id, $filter_date );
        exit;
    }
}

add_action( 'admin_init', 'clickbutton_handle_export' );

// Función para exportar datos
function export_clickbutton_data( $format, $button_id = 0, $filter_date = '' ) {
    global $wpdb;
    $table_buttons = $wpdb->prefix . 'clickbutton_buttons';
    $table_clicks  = $wpdb->prefix . 'clickbutton_clicks';

    if ( $button_id > 0 ) {
        // Exportar datos detallados de un botón específico
        $button = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $table_buttons WHERE id = %d", $button_id ) );

        if ( ! $button ) {
            wp_die( __( 'Botón no encontrado.', 'clickbutton' ) );
        }

        // 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;
        }

        $results_query = "SELECT c.click_time, c.user_ip, c.user_agent
                          FROM $table_clicks c
                          $where
                          ORDER BY c.click_time DESC";

        $results = $wpdb->get_results( $wpdb->prepare( $results_query, $params ) );

        // Nombre del archivo basado en el botón y fecha
        $file_name = 'clickbutton_' . $button->css_id;
        if ( ! empty( $filter_date ) ) {
            $file_name .= '_' . $filter_date;
        }

    } else {
        // Exportar datos generales
        $results_query = "SELECT b.css_id, c.page_url, COUNT(c.id) as clics, MAX(c.click_time) as ultimo_clic, c.user_ip, c.user_agent
                          FROM $table_buttons b
                          LEFT JOIN $table_clicks c ON b.id = c.button_id
                          GROUP BY b.css_id, c.page_url, c.user_ip, c.user_agent";

        $results = $wpdb->get_results( $results_query );

        $file_name = 'clickbutton_data';
    }

    if ( $format == 'csv' ) {
        header( 'Content-Type: text/csv; charset=utf-8' );
        header( 'Content-Disposition: attachment; filename=' . $file_name . '.csv' );
        $output = fopen( 'php://output', 'w' );

        if ( $button_id > 0 ) {
            fputcsv( $output, array( 'Fecha', 'Hora', 'IP del Usuario', 'Agente de Usuario' ) );
            foreach ( $results as $row ) {
                $date = date_i18n( get_option( 'date_format' ), strtotime( $row->click_time ) );
                $time = date_i18n( get_option( 'time_format' ), strtotime( $row->click_time ) );
                fputcsv( $output, array( $date, $time, $row->user_ip, $row->user_agent ) );
            }
        } else {
            fputcsv( $output, array( 'ID CSS', 'URL de la Página', 'Clics', 'Último Clic', 'IP del Usuario', 'Agente de Usuario' ) );
            foreach ( $results as $row ) {
                fputcsv( $output, array( $row->css_id, $row->page_url, $row->clics, $row->ultimo_clic, $row->user_ip, $row->user_agent ) );
            }
        }

        fclose( $output );
        exit;
    }

    if ( $format == 'pdf' ) {
        // Verificar si TCPDF está disponible
        if ( class_exists( 'TCPDF' ) ) {
            $pdf = new TCPDF();
            $pdf->SetCreator(PDF_CREATOR);
            $pdf->SetAuthor('Click Button Plugin');
            $pdf->SetTitle('Estadísticas de ClickButton');
            $pdf->SetHeaderData('', 0, 'Click Button Report', '');
            $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
            $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
            $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
            $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
            $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
            $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
            $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
            $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
            $pdf->AddPage();

            if ( $button_id > 0 ) {
                $html = '<h1>Detalles del Botón: ' . esc_html( $button->name ) . '</h1><table border="1" cellpadding="4">
                    <tr>
                        <th>Fecha</th>
                        <th>Hora</th>
                        <th>IP del Usuario</th>
                        <th>Agente de Usuario</th>
                    </tr>';

                foreach ( $results as $row ) {
                    $date = date_i18n( get_option( 'date_format' ), strtotime( $row->click_time ) );
                    $time = date_i18n( get_option( 'time_format' ), strtotime( $row->click_time ) );
                    $html .= '<tr>
                        <td>' . esc_html( $date ) . '</td>
                        <td>' . esc_html( $time ) . '</td>
                        <td>' . esc_html( $row->user_ip ) . '</td>
                        <td>' . esc_html( $row->user_agent ) . '</td>
                    </tr>';
                }
            } else {
                $html = '<h1>Estadísticas de ClickButton</h1><table border="1" cellpadding="4">
                    <tr>
                        <th>ID CSS</th>
                        <th>URL de la Página</th>
                        <th>Clics</th>
                        <th>Último Clic</th>
                        <th>IP del Usuario</th>
                        <th>Agente de Usuario</th>
                    </tr>';

                foreach ( $results as $row ) {
                    $html .= '<tr>
                        <td>' . esc_html( $row->css_id ) . '</td>
                        <td>' . esc_html( $row->page_url ) . '</td>
                        <td>' . esc_html( $row->clics ) . '</td>
                        <td>' . esc_html( $row->ultimo_clic ) . '</td>
                        <td>' . esc_html( $row->user_ip ) . '</td>
                        <td>' . esc_html( $row->user_agent ) . '</td>
                    </tr>';
                }
            }

            $html .= '</table>';
            $pdf->writeHTML( $html, true, false, true, false, '' );
            $pdf->Output( $file_name . '.pdf', 'D' );
            exit;
        } else {
            wp_die( __( 'La librería TCPDF no está disponible. Por favor, verifica la instalación.', 'clickbutton' ) );
        }
    }

    if ( $format == 'excel' ) {
        // Verificar si PhpSpreadsheet está disponible
        if ( class_exists( 'PhpOffice\PhpSpreadsheet\Spreadsheet' ) ) {
            // Crear una nueva hoja de cálculo
            $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
            $sheet = $spreadsheet->getActiveSheet();

            if ( $button_id > 0 ) {
                // Establecer los encabezados
                $sheet->setCellValue('A1', 'Fecha');
                $sheet->setCellValue('B1', 'Hora');
                $sheet->setCellValue('C1', 'IP del Usuario');
                $sheet->setCellValue('D1', 'Agente de Usuario');

                // Llenar los datos
                $rowNum = 2;
                foreach ( $results as $row ) {
                    $date = date_i18n( get_option( 'date_format' ), strtotime( $row->click_time ) );
                    $time = date_i18n( get_option( 'time_format' ), strtotime( $row->click_time ) );
                    $sheet->setCellValue('A' . $rowNum, $date);
                    $sheet->setCellValue('B' . $rowNum, $time);
                    $sheet->setCellValue('C' . $rowNum, $row->user_ip);
                    $sheet->setCellValue('D' . $rowNum, $row->user_agent);
                    $rowNum++;
                }
            } else {
                // Establecer los encabezados
                $sheet->setCellValue('A1', 'ID CSS');
                $sheet->setCellValue('B1', 'URL de la Página');
                $sheet->setCellValue('C1', 'Clics');
                $sheet->setCellValue('D1', 'Último Clic');
                $sheet->setCellValue('E1', 'IP del Usuario');
                $sheet->setCellValue('F1', 'Agente de Usuario');

                // Llenar los datos
                $rowNum = 2;
                foreach ( $results as $row ) {
                    $sheet->setCellValue('A' . $rowNum, $row->css_id);
                    $sheet->setCellValue('B' . $rowNum, $row->page_url);
                    $sheet->setCellValue('C' . $rowNum, $row->clics);
                    $sheet->setCellValue('D' . $rowNum, $row->ultimo_clic);
                    $sheet->setCellValue('E' . $rowNum, $row->user_ip);
                    $sheet->setCellValue('F' . $rowNum, $row->user_agent);
                    $rowNum++;
                }
            }

            // Autoajustar el tamaño de las columnas
            $columns = $button_id > 0 ? range('A','D') : range('A','F');
            foreach ( $columns as $columnID ) {
                $sheet->getColumnDimension($columnID)->setAutoSize(true);
            }

            // Crear el Writer
            $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);

            // Configurar las cabeceras para descargar el archivo
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header( 'Content-Disposition: attachment; filename="' . $file_name . '.xlsx"' );
            header('Cache-Control: max-age=0');

            // Descargar el archivo
            $writer->save('php://output');
            exit;
        } else {
            wp_die( __( 'La librería PhpSpreadsheet no está disponible. Por favor, verifica la instalación.', 'clickbutton' ) );
        }
    }
}
?>
