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

require_once __DIR__ . '/../../controllers/ProductController.php';
$productController = new ProductController();
$categories = $productController->getCategories();
$products = $productController->getProducts();
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Punto de Venta - Glado</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" rel="stylesheet">
    <style>
        body { background-color: #FFFACD; }
        #product-list { max-height: 70vh; overflow-y: auto; }
        .product-card {
            cursor: pointer;
            transition: transform 0.1s ease-in-out;
        }
        .product-card:hover { transform: scale(1.05); }
        #cart {
            background-color: #FFFFFF;
            height: 100vh;
            display: flex;
            flex-direction: column;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- Columna de Productos -->
            <div class="col-md-8 p-4">
                <h2 class="mb-4">Punto de Venta</h2>
                <!-- Categorías -->
                <div class="mb-4">
                    <?php foreach ($categories as $category): ?>
                        <button class="btn btn-lg me-2" style="background-color: #98FF98;"><?php echo htmlspecialchars($category['name']); ?></button>
                    <?php endforeach; ?>
                </div>
                <!-- Productos -->
                <div id="product-list" class="row">
                    <?php foreach ($products as $product): ?>
                        <div class="col-md-4 mb-4">
                            <div class="card product-card h-100" data-name="<?php echo htmlspecialchars($product['name']); ?>" data-price="<?php echo $product['price']; ?>">
                                <div class="card-body text-center">
                                    <h5 class="card-title"><?php echo htmlspecialchars($product['name']); ?></h5>
                                    <p class="card-text fs-4">Q<?php echo number_format($product['price'], 2); ?></p>
                                    <span class="badge bg-secondary">Stock: <?php echo $product['stock']; ?></span>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
            <!-- Columna de Carrito -->
            <div id="cart" class="col-md-4 p-4 border-start">
                <div class="d-flex justify-content-between align-items-center">
                    <h2 class="mb-4">Carrito</h2>
                    <a href="../../controllers/AuthController.php?action=logout" class="btn btn-outline-danger"><i class="fas fa-sign-out-alt"></i></a>
                </div>
                <div class="flex-grow-1">
                    <ul id="cart-items" class="list-group mb-3"></ul>
                </div>
                <div class="mt-auto">
                    <div class="mb-3"><input type="text" class="form-control" id="customer_phone" placeholder="Teléfono del Cliente (Opcional)"></div>
                    <div class="input-group mb-3"><input type="text" class="form-control" id="promo_code" placeholder="Código de Promoción"><button class="btn btn-outline-secondary" type="button" id="apply-promo-btn">Aplicar</button></div>
                    <hr>
                    <h5>Subtotal: <span class="float-end">Q<span id="cart-subtotal">0.00</span></span></h5>
                    <h5 class="text-danger">Descuento: <span class="float-end">-Q<span id="cart-discount">0.00</span></span></h5>
                    <h3>Total: <span class="float-end">Q<span id="cart-total">0.00</span></span></h3>
                    <div class="d-grid gap-2 mt-3">
                        <button id="pay-button" class="btn btn-success btn-lg">Pagar</button>
                        <a href="close_cash.php" class="btn btn-info">Cierre de Caja</a>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <script>
        let cart = [];
        let discount = 0;

        $(document).ready(function() {
            // Añadir producto al carrito
            $('.product-card').on('click', function() {
                const name = $(this).data('name');
                const price = parseFloat($(this).data('price'));
                addToCart({ name, price });
            });

            // Aplicar promoción
            $('#apply-promo-btn').on('click', function() {
                // (Lógica de promoción que ya teníamos)
            });

            // Pagar
            $('#pay-button').on('click', function() {
                if (cart.length === 0) {
                    alert('El carrito está vacío.');
                    return;
                }
                const customer_phone = $('#customer_phone').val();
                const referral_code = '' // (Añadir campo de referido si es necesario)
                const payment_method = 'efectivo' // (Añadir selector de método de pago si es necesario)

                $.ajax({
                    url: '../../controllers/SaleController.php',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify({ 
                        action: 'create_sale', 
                        cart: cart, 
                        customer_phone: customer_phone,
                        referral_code: referral_code,
                        payment_method: payment_method
                    }),
                    success: function(response) {
                        const res = JSON.parse(response);
                        if (res.success) {
                            alert(res.message);
                            cart = [];
                            discount = 0;
                            renderCart();
                        } else {
                            alert(res.message);
                        }
                    },
                    error: function() {
                        alert('Error al procesar la venta.');
                    }
                });
            });
        });

        function addToCart(product) {
            cart.push(product);
            renderCart();
        }

        function renderCart() {
            $('#cart-items').empty();
            let subtotal = 0;
            cart.forEach((item, index) => {
                subtotal += item.price;
                $('#cart-items').append(`<li class="list-group-item d-flex justify-content-between align-items-center">${item.name}<span>Q${item.price.toFixed(2)}</span><button class="btn btn-danger btn-sm" onclick="removeFromCart(${index})"><i class="fas fa-times"></i></button></li>`);
            });
            let total = subtotal - discount;
            $('#cart-subtotal').text(subtotal.toFixed(2));
            $('#cart-discount').text(discount.toFixed(2));
            $('#cart-total').text(total.toFixed(2));
        }

        function removeFromCart(index) {
            cart.splice(index, 1);
            renderCart();
        }
    </script>
</body>
</html>