<?php
// Incluir la conexión a la base de datos
include 'db.php';

// Obtener el ID de la bomba desde la URL
$pump_id = intval($_GET['pump_id']);

// Consulta para obtener las últimas 10 ventas relacionadas con la bomba seleccionada
$stmt = $conn->prepare("
    SELECT 
        si.sale_id,
        p.name AS product_name,
        si.qty,
        si.unit_price,
        ROUND(si.qty * si.unit_price, 2) AS total
    FROM sale_items si
    JOIN products p ON p.id = si.product_id
    JOIN hoses h ON h.id = si.hose_id
    JOIN pumps pm ON pm.id = h.pump_id
    WHERE pm.id = ?
    ORDER BY si.sale_id DESC
    LIMIT 10
");
$stmt->execute([$pump_id]);
$ventas = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ventas recientes</title>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            background-color: #f8f9fa;
        }
        .table-container {
            margin-top: 20px;
        }
        .sale-row {
            cursor: pointer;
            transition: background-color 0.3s, color 0.3s;
        }
        .sale-row:hover {
            background-color: #e9ecef;
        }
        .sale-row.selected {
            background-color: #007bff;
            color: white;
        }
        .btn-group {
            display: flex;
            justify-content: space-between;
            margin-top: 20px;
        }
        .btn-action {
            display: block;
            width: 48%; /* Divide los botones en dos partes iguales */
            padding: 15px;
            color: white;
            border: none;
            border-radius: 10px;
            font-size: 1.2rem;
            font-weight: bold;
            cursor: pointer;
            transition: background-color 0.3s;
            text-align: center;
        }
        .btn-primary {
            background-color: #007bff;
        }
        .btn-primary:hover {
            background-color: #0056b3;
        }
        .btn-ticket {
            background-color: #28a745;
        }
        .btn-ticket:hover {
            background-color: #218838;
        }
    </style>
</head>
<body>
    <div class="container mt-4">
        <h1 class="text-center mb-4">Ventas recientes: Bomba <?= htmlspecialchars($pump_id) ?></h1>
        
        <!-- Formulario dinámico -->
        <form method="POST" id="sales-form">
            <input type="hidden" name="selected_sale_id" id="selected_sale_id" value="">
            <input type="hidden" name="selected_qty" id="selected_qty" value="">
            <input type="hidden" name="selected_product_name" id="selected_product_name" value="">
            <input type="hidden" name="selected_unit_price" id="selected_unit_price" value="">
            <input type="hidden" name="selected_total" id="selected_total" value="">

            <div class="table-container">
                <table class="table table-bordered">
                    <thead>
                        <tr>
                            <th>Producto</th>
                            <th>Cantidad</th>
                            <th>Precio Unitario</th>
                            <th>Total</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ($ventas): ?>
                            <?php foreach ($ventas as $venta): ?>
                                <tr class="sale-row" data-sale-id="<?= htmlspecialchars($venta['sale_id']) ?>" data-qty="<?= $venta['qty'] ?>" data-product-name="<?= htmlspecialchars($venta['product_name']) ?>" data-unit-price="<?= $venta['unit_price'] ?>" data-total="<?= $venta['total'] ?>">
                                    <td><?= htmlspecialchars($venta['product_name']) ?></td>
                                    <td><?= number_format($venta['qty'], 3) ?></td>
                                    <td>$<?= number_format($venta['unit_price'], 2) ?></td>
                                    <td>$<?= number_format($venta['total'], 2) ?></td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="4" class="text-center">No hay ventas para esta bomba</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <!-- Botones de acción -->
            <div class="btn-group">
                <button type="submit" formaction="rnc.php" class="btn-action btn-primary">Comprobante</button>
                <button type="submit" formaction="imprimir_ticket.php" class="btn-action btn-ticket">Ticket</button>
            </div>
        </form>
    </div>

    <script>
        // Selección de filas de ventas y asignar valores a los inputs ocultos
        const rows = document.querySelectorAll('.sale-row');
        const selectedSaleIdInput = document.getElementById('selected_sale_id');
        const selectedQtyInput = document.getElementById('selected_qty');
        const selectedProductNameInput = document.getElementById('selected_product_name');
        const selectedUnitPriceInput = document.getElementById('selected_unit_price');
        const selectedTotalInput = document.getElementById('selected_total');

        rows.forEach(row => {
            row.addEventListener('click', () => {
                // Remover clase "selected" de todas las filas
                rows.forEach(r => r.classList.remove('selected'));

                // Asignar clase "selected" a la fila actual
                row.classList.add('selected');

                // Asignar valores a los inputs ocultos
                selectedSaleIdInput.value = row.dataset.saleId;
                selectedQtyInput.value = row.dataset.qty;
                selectedProductNameInput.value = row.dataset.productName;
                selectedUnitPriceInput.value = row.dataset.unitPrice;
                selectedTotalInput.value = row.dataset.total;
            });
        });

        // Validar selección antes de enviar el formulario
        document.querySelector('form').addEventListener('submit', (event) => {
            if (!selectedSaleIdInput.value) {
                event.preventDefault();
                alert('Por favor, selecciona una venta antes de continuar.');
            }
        });
    </script>
</body>
</html>