<?php
session_start();
include "db.php";
include "header.php";

/* ---------------------------------------------------------
    AJAX: UPDATE QTY  (debounced -> final update only)
--------------------------------------------------------- */
if (isset($_POST['ajax_update'])) {

    $key = $_POST['key'];
    $qty = max(1, intval($_POST['qty']));

    if (isset($_SESSION['cart'][$key])) {
        $_SESSION['cart'][$key]['qty'] = $qty;
    }

    // Recalculate based on the saved session price (server-side source of truth)
    $subtotal = $_SESSION['cart'][$key]['qty'] * $_SESSION['cart'][$key]['price'];

    $total = 0;
    foreach ($_SESSION['cart'] as $c) {
        $total += $c['qty'] * $c['price'];
    }

    echo json_encode([
        "subtotal" => number_format($subtotal, 2, '.', ''),
        "total" => number_format($total, 2, '.', '')
    ]);
    exit();
}

/* ---------------------------------------------------------
    REMOVE ITEM
--------------------------------------------------------- */
if (isset($_POST['remove_item'])) {
    unset($_SESSION['cart'][$_POST['key']]);
    header("Location: cart.php");
    exit();
}

/* ---------------------------------------------------------
    LOAD CART
--------------------------------------------------------- */
$items = [];
$total = 0;

if (!empty($_SESSION['cart'])) {
    foreach ($_SESSION['cart'] as $key => $c) {
        $stmt = $pdo->prepare("SELECT product_name, images FROM products WHERE id=? LIMIT 1");
        $stmt->execute([$c['product_id']]);
        $p = $stmt->fetch(PDO::FETCH_ASSOC);

        $imgs = json_decode($p['images'], true);
        $img = (is_array($imgs) && count($imgs) > 0) ? ltrim($imgs[0], '/') : "";

        $subtotal = $c['qty'] * $c['price'];
        $total += $subtotal;

        $items[] = [
            "key" => $key,
            "name" => $p['product_name'],
            "image" => $img,
            "size" => $c['size'],
            "garlic" => $c['garlic'],
            "spice" => $c['spice'],
            "qty" => $c['qty'],
            // Store the raw price in a data attribute or similar if needed for complex JS logic, 
            // but for simple multiplication, the JS will read the text content.
            "raw_price" => $c['price'], 
            "price" => number_format($c['price'], 2, '.', ''),
            "subtotal" => number_format($subtotal, 2, '.', '')
        ];
    }
}

$display_total = number_format($total, 2, '.', '');
?>

<style>
    :root {
        --primary-color: #002344;
        --secondary-color: #f7f7f7;
        --text-color: #333;
        --light-border: #ddd;
    }

    /* General Reset/Base Styles */
    body {
        font-family: Arial, sans-serif;
        color: var(--text-color);
        margin: 0;
        padding: 0;
    }

    /* Cart Container */
    .cart-container {
        max-width: 1000px;
        margin: 40px auto;
        padding: 0 20px;
    }

    .cart-header {
        color: var(--primary-color);
        border-bottom: 3px solid var(--primary-color);
        padding-bottom: 10px;
        margin-bottom: 30px;
        font-size: 2em;
    }

    /* Empty Cart Message */
    .empty-cart {
        padding: 40px;
        background: var(--secondary-color);
        border: 1px dashed var(--light-border);
        text-align: center;
        font-size: 1.2em;
    }

    /* Cart Table Styling (Desktop) */
    .cart-table {
        width: 100%;
        border-collapse: collapse;
        margin-bottom: 30px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        display: table; /* Reset display for desktop */
    }

    .cart-table th, .cart-table td {
        padding: 15px;
        text-align: left;
        border-bottom: 1px solid var(--light-border);
    }

    .cart-table th {
        background-color: var(--primary-color);
        color: white;
        text-transform: uppercase;
        font-size: 0.9em;
        letter-spacing: 0.5px;
    }

    .cart-table tr:last-child td {
        border-bottom: none;
    }
    
    .product-info-cell {
        display: flex;
        align-items: center;
        gap: 15px;
    }

    .product-info-cell img {
        width: 80px;
        height: 80px;
        object-fit: cover;
        border-radius: 4px;
        border: 1px solid var(--light-border);
    }

    .product-details strong {
        display: block;
        margin-bottom: 5px;
        font-size: 1.1em;
        color: var(--primary-color);
    }
    
    .options-list {
        font-size: 0.9em;
        line-height: 1.5;
        color: #666;
    }

    /* Quantity Box Styling */
    .qty-box {
        display: flex;
        align-items: center;
        border: 1px solid var(--light-border);
        border-radius: 4px;
        overflow: hidden;
    }
    .qty-btn {
        padding: 8px 12px;
        cursor: pointer;
        border: none;
        background: var(--secondary-color);
        font-size: 16px;
        transition: background-color 0.2s;
        flex-shrink: 0;
    }
    .qty-btn:hover {
        background-color: #e0e0e0;
    }
    .qty-input {
        width: 40px;
        text-align: center;
        font-size: 16px;
        border: none;
        outline: none;
        padding: 8px 0;
    }

    /* Remove Button */
    .remove-form {
        margin: 0;
    }
    .remove-btn {
        background: none;
        border: none;
        color: #e74c3c;
        font-weight: bold;
        cursor: pointer;
        font-size: 1.2em;
        transition: color 0.2s;
        padding: 0; 
    }
    .remove-btn:hover {
        color: #c0392b;
    }

    /* Totals Section */
    .cart-totals {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        padding: 20px 0;
        border-top: 1px solid var(--light-border);
        flex-wrap: wrap; /* Allows wrapping on mobile */
    }

    .total-display {
        font-size: 1.5em;
        font-weight: bold;
        color: var(--primary-color);
    }

    .checkout-link {
        margin-left: 30px;
    }

    .checkout-btn {
        padding: 12px 25px;
        font-size: 1.1em;
        background-color: var(--primary-color);
        color: white;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        transition: background-color 0.3s;
        text-decoration: none; 
        display: inline-block;
    }
    .checkout-btn:hover {
        background-color: #003768; /* Darker shade of primary */
    }

    /* -----------------------------------------
        MOBILE STYLES 
    ----------------------------------------- */
   /* -----------------------------------------
    MOBILE STYLES 
----------------------------------------- */
@media (max-width: 768px) {
    .cart-container {
        margin: 20px 0;
        padding: 0 10px;
    }

    /* Hide table headers on mobile */
    .cart-table thead {
        display: none;
    }

    /* Treat rows and cells as block elements */
    .cart-table, 
    .cart-table tbody, 
    .cart-table tr, 
    .cart-table td {
        /* *** FIX: Ensure display: block takes precedence *** */
        display: block !important; 
        width: 100%;
        box-sizing: border-box; /* Ensures padding/border are included in the 100% width */
    }

    .cart-table tr {
        margin-bottom: 20px;
        border: 1px solid var(--light-border);
        border-radius: 5px;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
    }

    .cart-table td {
        text-align: right;
        padding: 10px;
        position: relative;
        border-bottom: 1px solid var(--secondary-color);
    }

    /* Use pseudo-element to show the "header" label on mobile */
    .cart-table td::before {
        content: attr(data-label);
        position: absolute;
        left: 10px;
        width: 45%; 
        padding-right: 10px;
        white-space: nowrap;
        font-weight: bold;
        text-align: left;
        color: var(--primary-color);
    }

    /* ... (rest of your existing mobile styles are fine) ... */

    .product-info-cell {
        flex-direction: column;
        align-items: flex-start;
    }
    
    .cart-totals {
        justify-content: space-between;
        flex-direction: column;
        align-items: stretch;
    }
    
    .checkout-link {
        margin-left: 0;
        margin-top: 15px;
        width: 100%;
    }
    .checkout-btn {
        width: 100%;
        text-align: center;
    }
}
</style>

<div class="cart-container">
    <h2 class="cart-header">Your Cart 🛒</h2>

    <?php if (empty($items)) { ?>
        <div class="empty-cart">
            <p>Your cart is empty. Time to start shopping! 🛍️</p>
        </div>
    <?php } else { ?>

        <table class="cart-table">
            <thead>
                <tr>
                    <th>Product</th>
                    <th>Options</th>
                    <th>Qty</th>
                    <th>Price</th>
                    <th>Subtotal</th>
                    <th></th>
                </tr>
            </thead>

            <tbody>
                <?php foreach ($items as $it) { ?>
                <tr>

                    <td data-label="Product">
                        <div class="product-info-cell">
                            <?php 
                            $image_src = !empty($it['image']) 
                                ? "https://lalitavarahifoods.com/" . $it['image'] 
                                : "https://lalitavarahifoods.com/uploads/products/default.jpg";
                            ?>
                            <img src="<?php echo $image_src; ?>">
                            <div class="product-details">
                                <strong><?php echo $it['name']; ?></strong>
                            </div>
                        </div>
                    </td>

                    <td data-label="Options">
                        Size: <?php echo $it['size']; ?><br>
                        Garlic: <?php echo $it['garlic']; ?><br>
                        Spice: <?php echo $it['spice']; ?>
                    </td>

                    <td data-label="Quantity">
                        <div class="qty-box">
                            <button class="qty-btn minus" data-key="<?php echo $it['key']; ?>" type="button">−</button>

                            <input type="number" class="qty-input"
                                   data-key="<?php echo $it['key']; ?>"
                                   value="<?php echo $it['qty']; ?>" min="1">

                            <button class="qty-btn plus" data-key="<?php echo $it['key']; ?>" type="button">+</button>
                        </div>
                    </td>

                    <td data-label="Price" data-price="<?php echo $it['raw_price']; ?>">
                        ₹<span class="price-val"><?php echo $it['price']; ?></span>
                    </td>

                    <td id="subtotal-<?php echo $it['key']; ?>" data-label="Subtotal">
                        ₹<?php echo $it['subtotal']; ?>
                    </td>

                    <td data-label="Remove">
                        <form method="POST">
                            <input type="hidden" name="key" value="<?php echo $it['key']; ?>">
                            <button name="remove_item" class="remove-btn" type="submit">X</button>
                        </form>
                    </td>

                </tr>
                <?php } ?>
            </tbody>
        </table>

        <div class="cart-totals">
            <div class="total-display">
                Total: ₹<span id="cart-total"><?php echo $display_total; ?></span>
            </div>

            <a href="checkout.php" class="checkout-link">
                <button class="checkout-btn">Proceed to Checkout →</button>
            </a>
        </div>

    <?php } ?>
</div>

<script>
/* --------------------------------------------------
    SUPER FAST LIVE CALC + DEBOUNCED AJAX UPDATE
-------------------------------------------------- */

let updateTimer = {};
let cartTotalEl = document.getElementById("cart-total");

/* Recalculate grand total locally (instant) */
function recalcTotal() {
    // Select all subtotal elements by their data-label
    let subs = document.querySelectorAll("td[data-label='Subtotal']");
    let total = 0;
    subs.forEach(s => {
        // Safely extract and convert the number from the inner text (e.g., "₹125.00" -> 125.00)
        total += parseFloat(s.innerText.replace("₹", "")) || 0;
    });
    // Update the grand total display instantly, formatted to 2 decimals
    cartTotalEl.innerText = total.toFixed(2);
}

/* Send update to server (debounced) */
function sendUpdate(key, qty) {

    if (updateTimer[key]) clearTimeout(updateTimer[key]);

    // Use a small delay (debounce) before hitting the server
    updateTimer[key] = setTimeout(() => {
        console.log(`Sending AJAX update for key ${key} with qty ${qty}`);
        fetch("cart.php", {
            method: "POST",
            headers: {"Content-Type": "application/x-www-form-urlencoded"},
            body: `ajax_update=1&key=${key}&qty=${qty}`
        })
        .then(res => res.json())
        .then(data => {
            // Final confirmed update from server (optional check, but good for accuracy)
            // This re-confirms the total/subtotal based on server data
            document.getElementById(`subtotal-${key}`).innerText = "₹" + data.subtotal;
            cartTotalEl.innerText = data.total;
        })
        .catch(error => console.error("AJAX Error:", error));

    }, 150); // 150ms debounce
}

/* Main function to handle quantity change */
function updateQty(key, qty) {
    // 1. Sanitize input
    qty = Math.max(1, parseInt(qty)); // Ensure quantity is at least 1 and an integer

    let input = document.querySelector(`.qty-input[data-key='${key}']`);
    if (!input) return;

    let priceCell = input.closest("tr").querySelector("td[data-label='Price']");
    
    // Read the price directly from the cell's data attribute or inner text (better to read data-price if set)
    let price = parseFloat(priceCell.getAttribute('data-price')) || parseFloat(priceCell.querySelector('.price-val').innerText);
    
    if (isNaN(price)) return; // Stop if price isn't a number

    // 2. Client-side LIVE subtotal update
    let newSubtotal = (price * qty).toFixed(2);
    document.getElementById(`subtotal-${key}`).innerText = "₹" + newSubtotal;

    // 3. Client-side LIVE total recalculation
    // Must happen after the specific subtotal is updated
    recalcTotal();

    // 4. Update the input field value
    input.value = qty;

    // 5. Send update to backend (debounced)
    sendUpdate(key, qty);
}

/* PLUS Button Event Listener */
document.querySelectorAll(".plus").forEach(btn => {
    btn.addEventListener("click", () => {
        let key = btn.dataset.key;
        let input = document.querySelector(`.qty-input[data-key='${key}']`);
        updateQty(key, parseInt(input.value) + 1);
    });
});

/* MINUS Button Event Listener */
document.querySelectorAll(".minus").forEach(btn => {
    btn.addEventListener("click", () => {
        let key = btn.dataset.key;
        let input = document.querySelector(`.qty-input[data-key='${key}']`);
        let newQty = parseInt(input.value) - 1;
        if (newQty >= 1) {
            updateQty(key, newQty);
        }
    });
});

/* Manual typing (keyup and blur for immediate feedback) */
document.querySelectorAll(".qty-input").forEach(input => {
    // Use keyup for instant visual feedback while typing
    input.addEventListener("keyup", () => {
        updateQty(input.dataset.key, input.value);
    });
    // Use blur to catch changes when user tabs out or clicks away
    input.addEventListener("blur", () => {
        // Ensure update is run one last time to sanitize the value if needed
        updateQty(input.dataset.key, input.value);
    });
});
</script>

<?php include "footer.php"; ?>