<?php
session_start();
require_once '../../config.php';

if (!isset($_SESSION['userid'])) {
    header("Location: ../../login/");
    exit();
}

$userid = $_SESSION['userid'];
$page = 'carrito';

// ======================
// ACTUALIZAR CANTIDAD
// ======================
if (isset($_POST['update_qty'])) {
    $cart_id = intval($_POST['cart_id']);
    $quantity = max(1, intval($_POST['quantity'])); // mínimo 1

    $stmt = $conn->prepare("UPDATE temp_cart SET quantity = ? WHERE id = ? AND user_id = ?");
    $stmt->bind_param("iii", $quantity, $cart_id, $userid);
    $stmt->execute();
    $stmt->close();

    header("Location: cart.php");
    exit();
}

// ======================
// ELIMINAR PRODUCTO
// ======================
if (isset($_POST['delete_item'])) {
    $cart_id = intval($_POST['cart_id']);

    $stmt = $conn->prepare("DELETE FROM temp_cart WHERE id = ? AND user_id = ?");
    $stmt->bind_param("ii", $cart_id, $userid);
    $stmt->execute();
    $stmt->close();

    header("Location: cart.php");
    exit();
}

// ======================
// FINALIZAR COMPRA
// ======================
if (isset($_POST['checkout'])) {
    // 1. Obtener productos del carrito
    $sql = "SELECT tc.id AS cart_id, p.id AS product_id, p.name, p.price, tc.quantity 
            FROM temp_cart tc
            JOIN products p ON tc.product_id = p.id
            WHERE tc.user_id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $userid);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        // Calcular total
        $total = 0;
        $names = [];
        while ($row = $result->fetch_assoc()) {
            $subtotal = $row['price'] * $row['quantity'];
            $total += $subtotal;
            $names[] = $row['name'] . " (x" . $row['quantity'] . ")";
        }
        $stmt->close();

        // 2. Crear una factura agrupada
        $invoice_name = "Compra de productos: " . implode(", ", $names);
        //$status = "unpaid";
        //$route = NULL;

        //$stmt = $conn->prepare("INSERT INTO invoices (userid, name, price, status, route, created_at) VALUES (?, ?, ?, ?, ?, NOW())");
        //$stmt->bind_param("isdss", $userid, $invoice_name, $total, $status, $route);
        $status = "unpaid";
        $route = "cart_checkout"; // valor por defecto para productos agrupados

        $stmt = $conn->prepare("INSERT INTO invoices (userid, name, price, status, route, created_at) 
                        VALUES (?, ?, ?, ?, ?, NOW())");
        $stmt->bind_param("isdss", $userid, $invoice_name, $total, $status, $route);
        $stmt->execute();
        $stmt->close();

        // 3. Vaciar carrito lo comente domingo 24/25
        //$stmt = $conn->prepare("DELETE FROM temp_cart WHERE user_id = ?");
        //$stmt->bind_param("i", $userid);
        //$stmt->execute();
        //$stmt->close();

        // 4. Redirigir al listado de facturas
        $_SESSION['alert_message'] = [
            'type' => 'success',
            'message' => 'Compra finalizada. Se generó una factura para el pago.'
        ];
        header("Location: ../invoices/index.php");
        exit();
    }
}

// ======================
// CONSULTAR CARRITO
// ======================
$sql = "SELECT tc.id AS cart_id, p.name, p.price, tc.quantity 
        FROM temp_cart tc
        JOIN products p ON tc.product_id = p.id
        WHERE tc.user_id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $userid);
$stmt->execute();
$result = $stmt->get_result();

require_once '../../assets/templates/header-dashboard.php';
?>

<div class="container mt-4">
    <h3><i class="bi bi-cart"></i> Tu Carrito</h3>

    <?php if ($result->num_rows > 0): ?>
        <form method="POST">
        <table class="table table-striped">
            <thead>
                <tr>
                    <th>Producto</th>
                    <th>Cantidad</th>
                    <th>Precio Unitario</th>
                    <th>Subtotal</th>
                    <th>Acciones</th>
                </tr>
            </thead>
            <tbody>
            <?php 
            $total = 0;
            while ($row = $result->fetch_assoc()):
                $subtotal = $row['price'] * $row['quantity'];
                $total += $subtotal;
            ?>
                <tr>
                    <td><?= htmlspecialchars($row['name']) ?></td>
                    <td>
                        <form method="POST" class="d-flex">
                            <input type="hidden" name="cart_id" value="<?= $row['cart_id'] ?>">
                            <input type="number" name="quantity" value="<?= $row['quantity'] ?>" min="1" class="form-control me-2" style="width:80px;">
                            <button type="submit" name="update_qty" class="btn btn-sm btn-primary">Actualizar</button>
                        </form>
                    </td>
                    <td><?= number_format($row['price'], 2) ?></td>
                    <td><?= number_format($subtotal, 2) ?></td>
                    <td>
                        <form method="POST">
                            <input type="hidden" name="cart_id" value="<?= $row['cart_id'] ?>">
                            <button type="submit" name="delete_item" class="btn btn-sm btn-danger">Eliminar</button>
                        </form>
                    </td>
                </tr>
            <?php endwhile; ?>
                <tr>
                    <td colspan="3" class="text-end"><strong>Total</strong></td>
                    <td colspan="2"><strong><?= number_format($total, 2) ?></strong></td>
                </tr>
            </tbody>
        </table>
        <div class="text-end">
            <form method="POST">
                <button type="submit" name="checkout" class="btn btn-success">Finalizar Compra</button>
            </form>
        </div>
        </form>
    <?php else: ?>
        <div class="alert alert-info">22 Tu carrito está vacío.</div>
        <a href="index.php" class="btn btn-primary">Ir a la tienda</a>
    <?php endif; ?>
</div>

<?php
require_once '../../assets/templates/footer-dashboard.php';
?>


