<?php
// cart.php - EXACT SAME AS YOUR ORIGINAL + AUTO QUANTITY UPDATE (NO BUTTON)
session_start();
include_once 'config.php';
include_once 'auth.php';

// ======================== AJAX: AUTO UPDATE QUANTITY ========================
if (isset($_POST['ajax_qty_update'])) {
    header('Content-Type: application/json');
    
    $product_id = (int)$_POST['product_id'];
    $quantity   = max(0, (int)$_POST['quantity']);

    if ($quantity <= 0) {
        unset($_SESSION['cart'][$product_id]);
    } else {
        $_SESSION['cart'][$product_id] = $quantity;
    }

    // Recalculate total
    $total = 0;
    if (!empty($_SESSION['cart'])) {
        $ids = array_map('intval', array_keys($_SESSION['cart']));
        $placeholders = str_repeat('?,', count($ids)-1).'?';
        $stmt = $conn->prepare("SELECT price FROM products WHERE id IN ($placeholders)");
        $stmt->bind_param(str_repeat('i', count($ids)), ...$ids);
        $stmt->execute();
        $result = $stmt->get_result();
        while ($row = $result->fetch_assoc()) {
            $id = array_search($row['price'], array_column(array_map(function($id) use ($conn) {
                static $prices = [];
                if (!isset($prices[$id])) {
                    $stmt = $conn->prepare("SELECT price FROM products WHERE id = ?");
                    $stmt->bind_param("i", $id);
                    $stmt->execute();
                    $prices[$id] = $stmt->get_result()->fetch_assoc()['price'];
                }
                return ['id' => $id, 'price' => $prices[$id]];
            }, $ids), 'price'));
            $total += $row['price'] * ($_SESSION['cart'][$ids[$id]] ?? 0);
        }
    }

    echo json_encode(['success' => true, 'total' => $total]);
    exit;
}

// ======================== ORIGINAL ADD / REMOVE ACTIONS (UNCHANGED) ========================
if (isset($_GET['action']) && isset($_GET['product_id'])) {
    $product_id = (int)$_GET['product_id'];
    $return_url = $_GET['return_url'] ?? ($_SERVER['HTTP_REFERER'] ?? 'products.php');
    $return_url = $return_url ?: 'products.php';

    if ($_GET['action'] == 'add') {
        $stmt = $conn->prepare("SELECT id, stock FROM products WHERE id = ?");
        $stmt->bind_param("i", $product_id);
        $stmt->execute();
        $product = $stmt->get_result()->fetch_assoc();

        if ($product && $product['stock'] > 0) {
            $_SESSION['cart'][$product_id] = ($_SESSION['cart'][$product_id] ?? 0) + 1;
            set_flash_message('success', 'Item added to cart.');
        } else {
            set_flash_message('error', 'Item is out of stock or invalid.');
        }
        header("Location: " . urldecode($return_url));
        exit();
    }

    if ($_GET['action'] == 'remove') {
        unset($_SESSION['cart'][$product_id]);
        set_flash_message('success', 'Item removed from cart.');
        header("Location: cart.php");
        exit();
    }
}

// ======================== CHECKOUT (EXACTLY YOUR ORIGINAL) ========================
if (isset($_POST['checkout']) && is_logged_in()) {
    $user_id = $_SESSION['user_id'];
    $total = 0;
    $items = [];

    if (!empty($_SESSION['cart'])) {
        $ids = implode(',', array_map('intval', array_keys($_SESSION['cart'])));
        $result = $conn->query("SELECT id, price FROM products WHERE id IN ($ids)");
        while ($row = $result->fetch_assoc()) {
            $total += $row['price'] * $_SESSION['cart'][$row['id']];
            $items[$row['id']] = $_SESSION['cart'][$row['id']];
        }

        $stmt = $conn->prepare("INSERT INTO orders (user_id, total, status, items) VALUES (?, ?, 'pending', ?)");
        $items_json = json_encode($items);
        $stmt->bind_param("ids", $user_id, $total, $items_json);
        if ($stmt->execute()) {
            unset($_SESSION['cart']);
            set_flash_message('success', 'Order placed successfully! <a href="orders.php" class="alert-link">View Orders</a>');
        } else {
            set_flash_message('error', 'Error placing order.');
        }
    } else {
        set_flash_message('error', 'Your cart is empty.');
    }
    header("Location: cart.php");
    exit();
}

include_once 'header.php';
?>

<!-- YOUR ORIGINAL STYLES — 100% UNCHANGED -->
<style>
    .cart-container {
        max-width: 900px;
        margin: 120px auto;
        padding: 30px;
        background-color: white;
        box-shadow: 0 6px 15px rgba(0,0,0,0.1);
        border-radius: 12px;
        transition: box-shadow 0.3s ease;
    }
    .cart-container:hover { box-shadow: 0 8px 20px rgba(0,0,0,0.15); }
    .btn-primary { background-color: #0D6EFD; border-color: #0D6EFD; transition: all .2s; }
    .btn-primary:hover { background-color: #0c5fdb; transform: translateY(-2px); }
    .btn-danger:hover, .btn-success:hover { transform: translateY(-2px); }
    .table th, .table td { vertical-align: middle; }
    .form-control-sm { width: 80px; }
    h2 { font-family: 'Inter', sans-serif; color: #212529; }
    .alert-link { color: #0D6EFD; }
</style>

<div class="container cart-container">
    <h2 class="text-center mb-4">Shopping Cart</h2>

    <?php if (empty($_SESSION['cart'])): ?>
        <div class="alert alert-info text-center">
            Your cart is empty. <a href="products.php" class="link-primary">Shop now</a>.
        </div>
    <?php else: ?>
        <table class="table table-striped table-hover">
            <thead>
                <tr>
                    <th>Product</th>
                    <th>Price</th>
                    <th>Quantity</th>
                    <th>Total</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
                <?php
                $total = 0;
                $ids = implode(',', array_map('intval', array_keys($_SESSION['cart'])));
                $result = $conn->query("SELECT id, name, price, image FROM products WHERE id IN ($ids)");
                while ($row = $result->fetch_assoc()):
                    $qty = $_SESSION['cart'][$row['id']];
                    $subtotal = $row['price'] * $qty;
                    $total += $subtotal;
                ?>
                    <tr data-id="<?= $row['id'] ?>">
                        <td>
                            <img src="<?= htmlspecialchars($row['image'] ?? 'placeholder.jpg') ?>" width="50" class="me-2">
                            <?= htmlspecialchars($row['name']) ?>
                        </td>
                        <td data-price="<?= $row['price'] ?>">
                            KES<?= number_format($row['price'], 2) ?>
                        </td>
                        <td>
                            <input type="number" min="0" class="form-control form-control-sm qty"
                                   value="<?= $qty ?>" data-id="<?= $row['id'] ?>">
                        </td>
                        <td class="subtotal">KES<?= number_format($subtotal, 2) ?></td>
                        <td>
                            <a href="cart.php?action=remove&product_id=<?= $row['id'] ?>" 
                               class="btn btn-danger btn-sm">Remove</a>
                        </td>
                    </tr>
                <?php endwhile; ?>
            </tbody>
            <tfoot>
                <tr>
                    <td colspan="3" class="text-end fw-bold">Total:</td>
                    <td colspan="2" class="fw-bold grandtotal">
                        KES<?= number_format($total, 2) ?>
                    </td>
                </tr>
            </tfoot>
        </table>

        <!-- UPDATE BUTTON REMOVED — AUTO UPDATE NOW -->
        <div class="d-flex justify-content-between">
            <?php if (is_logged_in()): ?>
                <a href="checkout.php" class="btn btn-success">Proceed to Checkout</a>
            <?php else: ?>
                <a href="login.php?redirect=cart" class="btn btn-success">Login to Checkout</a>
            <?php endif; ?>
        </div>
    <?php endif; ?>

    <div class="text-center mt-4">
        <a href="products.php" class="btn btn-outline-primary">Continue Shopping</a>
    </div>
</div>

<!-- AUTO UPDATE SCRIPT — CLEAN & SAFE -->
<script>
document.querySelectorAll('.qty').forEach(input => {
    let timeout;
    const update = () => {
        clearTimeout(timeout);
        timeout = setTimeout(() => {
            const id = input.dataset.id;
            const qty = parseInt(input.value) || 0;
            const row = input.closest('tr');
            const price = parseFloat(row.querySelector('[data-price]').dataset.price);

            fetch('cart.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: 'ajax_qty_update=1&product_id=' + id + '&quantity=' + qty
            })
            .then(r => r.json())
            .then(data => {
                if (data.success) {
                    row.querySelector('.subtotal').textContent = 
                        'KES' + (price * qty).toLocaleString('en-US', {minimumFractionDigits: 2});
                    document.querySelector('.grandtotal').textContent = 
                        'KES' + parseFloat(data.total).toLocaleString('en-US', {minimumFractionDigits: 2});
                    
                    if (qty == 0) row.remove();
                    if (!document.querySelector('tbody tr')) location.reload();
                }
            });
        }, 500);
    };

    input.addEventListener('input', update);
    input.addEventListener('blur', () => {
        if (input.value < 1) input.value = 1;
        update();
    });
});
</script>

<?php include_once 'footer.php'; ?>