<?php
$rutaBD = '/var/www/datos/pedidos.db';
$db = new SQLite3($rutaBD);

$inicio = $_GET['desde'] ?? '';
$fin = $_GET['hasta'] ?? '';
$pedidos = [];
$totalGeneral = 0;

if ($inicio && $fin) {
    $finCompleta = date('Y-m-d', strtotime($fin)) . ' 23:59:59';
    
    $stmt = $db->prepare("SELECT * FROM pedidos WHERE fecha BETWEEN :inicio AND :fin ORDER BY fecha DESC");
    $stmt->bindValue(':inicio', $inicio);
    $stmt->bindValue(':fin', $finCompleta);
    $result = $stmt->execute();
    
    while ($fila = $result->fetchArray()) {
        $items = json_decode($fila['items'], true);
        $totalPedido = 0;
        foreach ($items as $p) {
            $totalPedido += $p['precio'] * $p['cantidad'];
        }
        $fila['totalPedido'] = $totalPedido;
        $fila['itemsDecodificados'] = $items;
        $pedidos[] = $fila;
        $totalGeneral += $totalPedido;
    }
}

if (isset($_GET['bajar']) && !empty($pedidos)) {
    header('Content-Type: text/csv; charset=utf-8');
    header("Content-Disposition: attachment; filename=pedidos_{$inicio}_al_{$fin}.csv");
    $salida = fopen('php://output', 'w');
    fputcsv($salida, ['Hora', 'Mesa', 'Cliente', 'Detalle', 'Total']);
    foreach ($pedidos as $p) {
        $det = [];
        foreach ($p['itemsDecodificados'] as $it) {
            $txt = "{$it['cantidad']}x {$it['nombre']} - $" . number_format($it['precio'] * $it['cantidad'], 2);
            if (!empty($it['comentario'])) $txt .= " ({$it['comentario']})";
            $det[] = $txt;
        }
        fputcsv($salida, [
            date('H:i', strtotime($p['fecha'])),
            $p['mesa'],
            $p['cliente'],
            implode(" | ", $det),
            '$' . number_format($p['totalPedido'], 2)
        ]);
    }
    fputcsv($salida, ['', '', '', 'TOTAL', '$' . number_format($totalGeneral, 2)]);
    fclose($salida);
    exit;
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Consultar Pedidos</title>
    <style>
        * { margin: 0; padding: 0; font-family: sans-serif; box-sizing: border-box; }
        body { background: #0f2b48; color: white; padding: 20px; min-height: 100vh; }
        h1 { text-align: center; margin-bottom: 30px; color: #94c5f0; }
        .caja { background: rgba(255,255,255,0.1); padding: 25px; border-radius: 12px; max-width: 900px; margin: 0 auto; }
        .fila { display: flex; gap: 15px; flex-wrap: wrap; margin-bottom: 20px; }
        .campo { flex: 1; min-width: 200px; }
        label { display: block; margin-bottom: 8px; color: #b8d8f5; }
        input { width: 100%; padding: 12px; border: none; border-radius: 8px; background: rgba(255,255,255,0.15); color: white; font-size: 16px; }
        .boton { padding: 12px 25px; border: none; border-radius: 8px; font-size: 16px; font-weight: bold; cursor: pointer; text-decoration: none; display: inline-block; }
        .btn-verde { background: #2ecc71; color: white; }
        .btn-amarillo { background: #facc15; color: #000; margin-left: 10px; }
        .botones { text-align: center; margin: 20px 0; }
        table { width: 100%; border-collapse: collapse; margin-top: 20px; }
        th, td { padding: 12px; text-align: left; border-bottom: 1px solid rgba(255,255,255,0.1); }
        th { background: #5ea8e5; }
        .total { text-align: right; margin-top: 20px; font-size: 22px; font-weight: bold; color: #facc15; padding: 15px; background: rgba(0,0,0,0.2); border-radius: 8px; }
        .vacio { text-align: center; padding: 40px; color: #888; }
        .volver { display: inline-block; margin-top: 25px; color: #94c5f0; text-decoration: none; }
    </style>
</head>
<body>

<h1>📅 Consulta de Pedidos</h1>
<div class="caja">
    <form method="GET">
        <div class="fila">
            <div class="campo">
                <label>Fecha de Inicio</label>
                <input type="date" name="desde" required value="<?= htmlspecialchars($inicio) ?>">
            </div>
            <div class="campo">
                <label>Fecha de Fin</label>
                <input type="date" name="hasta" required value="<?= htmlspecialchars($fin) ?>">
            </div>
        </div>
        <div class="botones">
            <button type="submit" class="boton btn-verde">🔍 Buscar</button>
            <?php if ($inicio && $fin && count($pedidos) > 0): ?>
                <a href="?desde=<?= urlencode($inicio) ?>&hasta=<?= urlencode($fin) ?>&bajar=1" class="boton btn-amarillo">⬇️ Descargar</a>
            <?php endif; ?>
        </div>
    </form>

    <?php if ($inicio && $fin): ?>
        <h3 style="margin-top: 25px;">Pedidos del <?= date('d/m/Y', strtotime($inicio)) ?> al <?= date('d/m/Y', strtotime($fin)) ?></h3>
        
        <?php if (count($pedidos) > 0): ?>
            <table>
                <tr>
                    <th>Hora</th>
                    <th>Mesa</th>
                    <th>Cliente</th>
                    <th>Detalle</th>
                    <th>Total</th>
                </tr>
                <?php foreach ($pedidos as $p): ?>
                    <tr>
                        <td><?= date('H:i', strtotime($p['fecha'])) ?></td>
                        <td><?= $p['mesa'] ?></td>
                        <td><?= htmlspecialchars($p['cliente']) ?></td>
                        <td>
                            <?php foreach ($p['itemsDecodificados'] as $it): ?>
                                <div>
                                    <?= $it['cantidad'] ?>x <?= htmlspecialchars($it['nombre']) ?> — $<?= number_format($it['precio'] * $it['cantidad'], 2) ?>
                                    <?php if (!empty($it['comentario'])): ?>
                                        <br><small style="color:#facc15">📝 <?= htmlspecialchars($it['comentario']) ?></small>
                                    <?php endif; ?>
                                </div>
                            <?php endforeach; ?>
                        </td>
                        <td><strong>$<?= number_format($p['totalPedido'], 2) ?></strong></td>
                    </tr>
                <?php endforeach; ?>
            </table>
            <div class="total">💰 TOTAL: $<?= number_format($totalGeneral, 2) ?></div>
        <?php else: ?>
            <div class="vacio">No hay pedidos en esas fechas</div>
        <?php endif; ?>
    <?php endif; ?>

    <a href="index.html" class="volver">← Volver</a>
</div>
</body>
</html>
