<?php
// /cart.php
require_once 'includes/header.php';
$page_title = "Shopping Cart";

$cart_items = $_SESSION['cart'] ?? [];
$products = [];
$subtotal = 0;

if (!empty($cart_items)) {
    $product_ids = array_keys($cart_items);
    $placeholders = implode(',', array_fill(0, count($product_ids), '?'));
    $types = str_repeat('i', count($product_ids));
    
    // MODIFIED: Fetched the thumbnail_url from the product_images table
    $stmt = $conn->prepare("
        SELECT id, name, price, stock,
               (SELECT pi.image_url FROM product_images pi WHERE pi.product_id = products.id ORDER BY pi.is_thumbnail DESC, pi.id ASC LIMIT 1) as thumbnail_url
        FROM products 
        WHERE id IN ($placeholders)
    ");
    $stmt->bind_param($types, ...$product_ids);
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $products[$row['id']] = $row;
    }
    $stmt->close();
}
?>

<div class="container mx-auto px-4 lg:px-6 py-8">
    <h1 class="text-3xl font-bold mb-6">Your Shopping Cart</h1>
    
    <?php if (empty($cart_items) || empty($products)): ?>
        <div class="bg-white p-8 rounded-lg shadow-md text-center">
            <p class="text-gray-600 text-lg">Your cart is empty.</p>
            <a href="/listing.php" class="mt-4 inline-block bg-blue-600 text-white font-semibold px-6 py-3 rounded-lg hover:bg-blue-700">Continue Shopping</a>
        </div>
    <?php else: ?>
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
            <div class="lg:col-span-2 bg-white p-4 sm:p-6 rounded-lg shadow-md">
                <div class="space-y-4">
                    
                    <?php foreach ($cart_items as $product_id => $quantity): 
                        if (!isset($products[$product_id])) continue; // Skip if product was deleted
                        $product = $products[$product_id];
                        $item_total = $product['price'] * $quantity;
                        $subtotal += $item_total;
                    ?>
                    <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center border-b last:border-b-0 py-4">
                        
                        <div class="flex items-center mb-4 sm:mb-0">
                            <img src="/<?php echo escape($product['thumbnail_url'] ?? 'assets/images/placeholder.png'); ?>" class="w-20 h-20 object-cover rounded-md mr-4" alt="<?php echo escape($product['name']); ?>">
                            <div class="flex-grow">
                                <h3 class="font-semibold text-md sm:text-lg"><?php echo escape($product['name']); ?></h3>
                                <p class="text-gray-500 text-sm">₦<?php echo number_format($product['price']); ?></p>
                            </div>
                        </div>

                        <div class="w-full sm:w-auto flex items-center justify-between sm:space-x-4">
                            <form action="/cart_actions.php" method="POST">
                                <input type="hidden" name="action" value="update">
                                <input type="hidden" name="product_id" value="<?php echo $product_id; ?>">
                                <label for="quantity-<?php echo $product_id; ?>" class="sr-only">Quantity</label>
                                <input id="quantity-<?php echo $product_id; ?>" type="number" name="quantity" value="<?php echo $quantity; ?>" min="1" max="<?php echo $product['stock']; ?>" class="w-16 p-2 border rounded-md" onchange="this.form.submit()">
                            </form>
                            
                            <p class="font-semibold w-24 text-right">₦<?php echo number_format($item_total); ?></p>
                            
                            <form action="/cart_actions.php" method="POST">
                                <input type="hidden" name="action" value="remove">
                                <input type="hidden" name="product_id" value="<?php echo $product_id; ?>">
                                <button type="submit" class="text-red-500 hover:text-red-700 p-2" aria-label="Remove item">
                                    <i data-lucide="trash-2" class="w-5 h-5"></i>
                                </button>
                            </form>
                        </div>
                    </div>
                    <?php endforeach; ?>
                    </div>
            </div>

            <div class="lg:col-span-1">
                <div class="bg-white p-6 rounded-lg shadow-md sticky top-24">
                    <h2 class="text-xl font-bold border-b pb-3 mb-4">Order Summary</h2>
                    <div class="flex justify-between mb-2">
                        <span>Subtotal</span>
                        <span class="font-semibold">₦<?php echo number_format($subtotal, 2); ?></span>
                    </div>
                    <div class="flex justify-between font-bold text-lg border-t pt-3 mt-3">
                        <span>Total</span>
                        <span>₦<?php echo number_format($subtotal, 2); ?></span>
                    </div>
                    <a href="/checkout.php" class="w-full mt-6 block text-center bg-green-600 text-white font-bold py-3 rounded-lg hover:bg-green-700">
                        Proceed to Checkout
                    </a>
                </div>
            </div>
        </div>
    <?php endif; ?>
</div>

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