<?php
require_once __DIR__ . '/functions.php';
$page_title = 'Shopping Cart';
$db = db();

$cartId = getCartId();
$items = getCartItems();
$subtotal = getCartTotal();
$coupon = getAppliedCoupon();
$shippingState = null;
if (isLoggedIn()) {
    $shippingState = $_SESSION['user_state'] ?? null;
    if (!$shippingState) {
        $u = $db->prepare("SELECT state FROM users WHERE id = ?");
        $u->execute([$_SESSION['user_id']]);
        $shippingState = $u->fetchColumn() ?: null;
    }
}
$totals = calculateTotals($subtotal, $coupon, $items, $shippingState);

require_once __DIR__ . '/includes/header.php';
?>

<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
    <h1 class="text-2xl font-bold text-gray-800 mb-6">Shopping Cart</h1>

    <?php if (count($items) === 0): ?>
    <div class="text-center py-16">
        <i class="fas fa-shopping-cart text-gray-300 text-6xl mb-4"></i>
        <h2 class="text-xl font-semibold text-gray-800 mb-2">Your cart is empty</h2>
        <p class="text-gray-500 mb-6">Start shopping to add items to your cart.</p>
        <a href="catalog.php" class="bg-primary-600 text-white px-6 py-2.5 rounded-lg font-semibold hover:bg-primary-700">Browse Products</a>
    </div>
    <?php else: ?>

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
        <div class="lg:col-span-2 space-y-4">
            <?php foreach ($items as $item): ?>
            <div class="bg-white rounded-xl border border-gray-200 p-4" id="cart-item-<?= $item['id'] ?>">
                <div class="flex items-start gap-3 sm:gap-4">
                    <div class="w-16 h-16 sm:w-20 sm:h-20 bg-gray-50 rounded-lg flex items-center justify-center overflow-hidden shrink-0">
                        <?php $cartImg = $item['variant_image'] ? BASE_PATH . '/' . h($item['variant_image']) : ($item['image'] ? h($item['image']) : ''); ?>
                        <?php if ($cartImg): ?>
                        <img src="<?= $cartImg ?>" alt="" class="w-full h-full object-cover">
                        <?php else: ?>
                        <i class="fas fa-box text-gray-300 text-2xl"></i>
                        <?php endif; ?>
                    </div>
                    <div class="flex-1 min-w-0">
                        <a href="product.php?slug=<?= h($item['slug']) ?>" class="font-medium text-gray-800 hover:text-primary-600 text-sm sm:text-base truncate block"><?= h($item['name']) ?></a>
                        <?php if ($item['variant_value']):
                            $isColor = strtolower($item['variant_type']) === 'color';
                            $hex = $item['variant_value'];
                        ?>
                        <p class="text-xs text-gray-500 flex items-center gap-1 mt-0.5">
                            <?php if ($isColor && preg_match('/^#[0-9a-f]{6}$/i', $hex)): ?>
                            <span class="inline-block w-3 h-3 rounded-full border border-gray-300" style="background:<?= h($hex) ?>"></span>
                            <?php endif; ?>
                            <?= h($item['variant_type']) ?>: <?= h($item['variant_value']) ?>
                        </p>
                        <?php endif; ?>
                        <p class="text-primary-600 font-bold mt-1"><?= formatPrice($item['unit_price']) ?></p>
                    </div>
                    <div class="text-right shrink-0">
                        <p class="font-bold text-gray-800 text-sm sm:text-base"><?= formatPrice($item['unit_price'] * $item['quantity']) ?></p>
                        <button onclick="updateCart(<?= $item['id'] ?>, 0)" class="text-xs text-red-500 hover:underline mt-1 block sm:inline">Remove</button>
                    </div>
                </div>
                <!-- Qty controls on their own row on mobile -->
                <div class="flex items-center justify-between sm:justify-end mt-3 sm:mt-2 pt-3 sm:pt-0 border-t sm:border-0 border-gray-100 gap-4">
                    <div class="flex items-center gap-2">
                        <button onclick="updateCart(<?= $item['id'] ?>, <?= $item['quantity'] - 1 ?>)" class="w-10 h-10 border border-gray-300 rounded-lg flex items-center justify-center text-gray-600 hover:border-primary-500 text-lg">&minus;</button>
                        <span class="w-8 text-center font-medium text-base" id="qty-<?= $item['id'] ?>"><?= $item['quantity'] ?></span>
                        <button onclick="updateCart(<?= $item['id'] ?>, <?= $item['quantity'] + 1 ?>)" class="w-10 h-10 border border-gray-300 rounded-lg flex items-center justify-center text-gray-600 hover:border-primary-500 text-lg">+</button>
                    </div>
                    <button onclick="updateCart(<?= $item['id'] ?>, 0)" class="text-sm text-red-500 hover:underline sm:hidden">Remove</button>
                </div>
            </div>
            <?php endforeach; ?>
        </div>

        <!-- Order Summary -->
        <div class="bg-white rounded-xl border border-gray-200 p-6 h-fit sticky top-24">
            <h2 class="font-semibold text-gray-800 mb-4">Order Summary</h2>
            
            <!-- Coupon -->
            <form action="api/cart.php" method="POST" class="mb-4 flex gap-2">
                <input type="hidden" name="action" value="apply_coupon">
                <input type="text" name="code" placeholder="Coupon code" value="<?= h($_POST['code'] ?? '') ?>" class="flex-1 border border-gray-300 rounded-lg px-3 py-1.5 text-sm focus:outline-none focus:ring-1 focus:ring-primary-500">
                <button type="submit" class="bg-gray-800 text-white px-4 py-1.5 rounded-lg text-sm font-medium hover:bg-gray-700">Apply</button>
            </form>
            <?php if ($coupon): ?>
            <div class="flex items-center justify-between text-sm text-green-600 mb-4">
                <span>Coupon: <?= h($coupon['code']) ?></span>
                <a href="api/cart.php?action=remove_coupon" class="text-red-500 hover:underline">Remove</a>
            </div>
            <?php endif; ?>

            <div class="space-y-2 text-sm">
                <div class="flex justify-between text-gray-600">
                    <span>Subtotal</span>
                    <span><?= formatPrice($totals['subtotal']) ?></span>
                </div>
                <?php if ($totals['discount'] > 0): ?>
                <div class="flex justify-between text-green-600">
                    <span>Discount</span>
                    <span>-<?= formatPrice($totals['discount']) ?></span>
                </div>
                <?php endif; ?>
                <div class="flex justify-between text-gray-600">
                    <span><?= $totals['tax_label'] ?></span>
                    <span><?= formatPrice($totals['tax']) ?></span>
                </div>
                <div class="flex justify-between text-gray-600">
                    <span><?= $totals['shipping_label'] ?? 'Shipping' ?></span>
                    <span><?= $totals['shipping'] > 0 ? formatPrice($totals['shipping']) : 'Free' ?></span>
                </div>
                <hr class="my-2">
                <div class="flex justify-between font-bold text-gray-800 text-base">
                    <span>Total</span>
                    <span><?= formatPrice($totals['total']) ?></span>
                </div>
            </div>
            <a href="checkout.php" class="block text-center bg-primary-600 text-white py-2.5 rounded-lg font-semibold hover:bg-primary-700 transition mt-6">Proceed to Checkout</a>
            <a href="catalog.php" class="block text-center text-primary-600 text-sm mt-2 hover:underline">Continue Shopping</a>
        </div>
    </div>
    <?php endif; ?>
</div>

<script>
async function updateCart(itemId, quantity) {
    const r = await fetch('api/cart.php', {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: 'action=update&item_id=' + itemId + '&quantity=' + quantity
    });
    const d = await r.json();
    if (d.success) {
        location.reload();
    }
}
</script>
<?php require_once __DIR__ . '/includes/footer.php'; ?>
