<?php
session_start();
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}

require_once 'db/config.php';

try {
    $pdo = db();

    $query = "
        SELECT 
            p.dni_cliente,
            p.nombre_completo,
            p.sede_envio,
            p.celular,
            p.producto,
            p.cantidad
        FROM pedidos p
        WHERE p.estado = 'ROTULADO 📦'
        ORDER BY p.id DESC
    ";
    $stmt = $pdo->prepare($query);
    $stmt->execute();
    $pedidos = $stmt->fetchAll(PDO::FETCH_ASSOC);

    header('Content-Type: application/vnd.ms-excel; charset=utf-8');
    header('Content-Disposition: attachment; filename="rotulados.xls"');
    header('Pragma: no-cache');
    header('Expires: 0');

    $output = '<html><head><meta charset="utf-8"></head><body>';
    $output .= '<table border="1">';
    $output .= '<thead>';
    $output .= '<tr>';
    $output .= '<th>DNI</th>';
    $output .= '<th>Cliente</th>';
    $output .= '<th>Sede de Envío</th>';
    $output .= '<th>Numero</th>';
    $output .= '<th>Producto</th>';
    $output .= '<th>Cantidad</th>';
    $output .= '<th>Numero de Orden</th>';
    $output .= '</tr>';
    $output .= '</thead>';
    $output .= '<tbody>';

    $numero_orden = 1;
    foreach ($pedidos as $pedido) {
        $output .= '<tr>';
        $output .= '<td>' . htmlspecialchars($pedido['dni_cliente'] ?? '') . '</td>';
        $output .= '<td>' . htmlspecialchars($pedido['nombre_completo'] ?? '') . '</td>';
        $output .= '<td>' . htmlspecialchars($pedido['sede_envio'] ?? '') . '</td>';
        $output .= '<td>' . htmlspecialchars($pedido['celular'] ?? '') . '</td>';
        $output .= '<td>' . htmlspecialchars($pedido['producto'] ?? '') . '</td>';
        $output .= '<td>' . htmlspecialchars($pedido['cantidad'] ?? '') . '</td>';
        $output .= '<td>' . $numero_orden . '</td>';
        $output .= '</tr>';
        $numero_orden++;
    }

    $output .= '</tbody>';
    $output .= '</table>';
    $output .= '</body></html>';

    echo $output;

} catch (Exception $e) {
    // Log error if possible, but don't output it to the user here
    // as it would corrupt the Excel file.
    // For debugging, you could write to a log file:
    // file_put_contents('error_log.txt', $e->getMessage());
    
    // Restore friendly error message
    header('HTTP/1.1 500 Internal Server Error');
    // Using a script to show the message and prevent file corruption.
    echo '<script>alert("Ocurrió un error al generar el reporte."); window.history.back();</script>';
}

?>