<?php
/**
 * Tom's Java Jive - Shopping Cart
 */

$pageTitle = "Shopping Cart - Tom's Java Jive";
$metaTitle = "Your Cart | Tom's Java Jive";
$metaDescription = 'Review your coffee selections and checkout securely.';
$canonicalUrl = 'https://tomsjavajive.com/cart.php';
$metaRobots = "noindex, nofollow";
$suppressSchema = true;
$extraHead = '<link rel="stylesheet" href="/assets/css/cart.css?v=' . filemtime(__DIR__ . '/assets/css/cart.css') . '">';
require_once __DIR__ . '/includes/header.php';

$cart = getCart();
$cartItems = [];
$subtotal = 0;

// Get product details for cart items
foreach ($cart as $productId => $quantity) {
    $product = db()->fetch(
        "SELECT product_id, name, price, sale_price, stock, images FROM products WHERE product_id = :id AND is_active = 1",
        ['id' => $productId]
    );
    
    if ($product) {
        $images = json_decode($product['images'] ?? '[]', true);
        $product['image'] = !empty($images) ? $images[0] : '/assets/images/placeholder-product.svg';
        $product['quantity'] = min($quantity, $product['stock']);
        $product['unit_price'] = $product['sale_price'] ?? $product['price'];
        $product['total'] = $product['unit_price'] * $product['quantity'];
        $subtotal += $product['total'];
        $cartItems[] = $product;
    }
}

// Get shipping settings
$shippingSettings = getSetting('shipping', [
    'flat_rate_enabled' => true,
    'flat_rate_amount' => 5.99,
    'free_shipping_threshold' => 50
]);

$shippingCost = 0;
if ($shippingSettings['flat_rate_enabled'] ?? true) {
    if ($subtotal >= ($shippingSettings['free_shipping_threshold'] ?? 50)) {
        $shippingCost = 0;
    } else {
        $shippingCost = $shippingSettings['flat_rate_amount'] ?? 5.99;
    }
}

$total = $subtotal + $shippingCost;
?>

<section class="section" style="padding-top: 2rem;">
    <div class="container">
        <h1 style="margin-bottom: 2rem;">Shopping Cart</h1>
        
        <?php if (empty($cartItems)): ?>
            <div class="card">
                <div class="card-body text-center" style="padding: 3rem;">
                    <i class="fas fa-shopping-bag" style="font-size: 4rem; color: var(--color-text-muted); margin-bottom: 1rem;"></i>
                    <h3>Your cart is empty</h3>
                    <p class="text-muted mb-2">Looks like you haven't added any items yet.</p>
                    <a href="/shop.php" class="btn btn-primary">Start Shopping</a>
                </div>
            </div>
        <?php else: ?>
            <div class="cart-layout">

                <!-- Cart Items -->
                <div class="card">
                    <div class="card-body">
                        <div class="cart-items-list">
                            <?php foreach ($cartItems as $item): ?>
                                <div class="cart-item" data-product-id="<?= $item['product_id'] ?>">

                                    <img src="<?= htmlspecialchars($item['image']) ?>" alt="<?= htmlspecialchars($item['name']) ?>"
                                         class="cart-item-img">

                                    <div>
                                        <a href="/product.php?id=<?= $item['product_id'] ?>">
                                            <h4 class="cart-item-name"><?= htmlspecialchars($item['name']) ?></h4>
                                        </a>
                                        <p class="cart-item-price"><?= formatCurrency($item['unit_price']) ?> each</p>
                                    </div>

                                    <div class="quantity-selector">
                                        <button type="button" class="qty-btn"
                                                onclick="updateCartItem('<?= $item['product_id'] ?>', <?= $item['quantity'] - 1 ?>)">-</button>
                                        <input type="number" class="qty-input" value="<?= $item['quantity'] ?>" min="1" max="<?= $item['stock'] ?>"
                                               onchange="updateCartItem('<?= $item['product_id'] ?>', this.value)">
                                        <button type="button" class="qty-btn"
                                                onclick="updateCartItem('<?= $item['product_id'] ?>', <?= $item['quantity'] + 1 ?>)">+</button>
                                    </div>

                                    <div class="cart-item-total">
                                        <p class="amount"><?= formatCurrency($item['total']) ?></p>
                                        <button type="button" class="btn-remove"
                                                onclick="removeFromCart('<?= $item['product_id'] ?>')">
                                            <i class="fas fa-trash"></i> Remove
                                        </button>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>

                <!-- Order Summary -->
                <div class="card cart-summary">
                    <div class="card-header">
                        <h3 style="margin: 0;">Order Summary</h3>
                    </div>
                    <div class="card-body">
                        <div class="cart-summary-row">
                            <span>Subtotal</span>
                            <span id="cart-subtotal"><?= formatCurrency($subtotal) ?></span>
                        </div>
                        <div class="cart-summary-row">
                            <span>Shipping</span>
                            <span id="cart-shipping">
                                <?php if ($shippingCost == 0): ?>
                                    <span class="text-success">FREE</span>
                                <?php else: ?>
                                    <?= formatCurrency($shippingCost) ?>
                                <?php endif; ?>
                            </span>
                        </div>

                        <?php if ($shippingCost > 0 && isset($shippingSettings['free_shipping_threshold'])):
                            $remaining = $shippingSettings['free_shipping_threshold'] - $subtotal;
                        ?>
                            <p class="free-shipping-msg">
                                <i class="fas fa-truck"></i>
                                Add <?= formatCurrency($remaining) ?> more for FREE shipping!
                            </p>
                        <?php endif; ?>

                        <hr style="margin: 1rem 0;">

                        <div class="cart-summary-total">
                            <span>Total</span>
                            <span id="cart-total"><?= formatCurrency($total) ?></span>
                        </div>
                        
                        <a href="/checkout.php" class="btn btn-primary btn-lg btn-block mt-2">
                            Proceed to Checkout
                        </a>
                        
                        <a href="/shop.php" class="btn btn-outline btn-block mt-1">
                            Continue Shopping
                        </a>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </div>
</section>

<script>
function updateCartDisplay(data) {
    location.reload();
}
</script>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
