<?php
// File: cart.php
include 'header.php';

// Initialize cart if it's not set
$cart_items = $_SESSION['cart'] ?? [];
$cart_details = [];
$subtotal = 0;

if (!empty($cart_items)) {
    // Get all painting IDs from the cart to fetch their details in one query
    $painting_ids = array_keys($cart_items);
    $id_placeholders = implode(',', array_fill(0, count($painting_ids), '?'));
    $types = str_repeat('i', count($painting_ids));

    $stmt = $conn->prepare("SELECT id, title, image_path, price, sale_price FROM paintings WHERE id IN ($id_placeholders)");
    $stmt->bind_param($types, ...$painting_ids);
    $stmt->execute();
    $result = $stmt->get_result();

    while ($row = $result->fetch_assoc()) {
        $painting_id = $row['id'];
        $quantity = $cart_items[$painting_id]['quantity'];
        // Use sale price if available, otherwise regular price
        $price = (isset($row['sale_price']) && $row['sale_price'] > 0) ? $row['sale_price'] : $row['price'];
        
        $cart_details[$painting_id] = [
            'title' => $row['title'],
            'image_path' => $row['image_path'],
            'price' => $price,
            'quantity' => $quantity,
            'total' => $price * $quantity
        ];
        $subtotal += $cart_details[$painting_id]['total'];
    }
    $stmt->close();
}
?>

<div class="bg-gray-100 py-12 md:py-20">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">

        <h1 class="text-4xl font-extrabold text-ucf-charcoal text-center mb-12">Your Shopping Cart</h1>

        <?php if (empty($cart_details)): ?>
            <div class="text-center bg-white p-12 rounded-lg shadow-md">
                <i class="fas fa-shopping-cart fa-4x text-gray-300 mb-4"></i>
                <h2 class="text-2xl font-bold text-ucf-charcoal">Your cart is empty.</h2>
                <p class="text-gray-500 mt-2">Looks like you haven't added any paintings to your cart yet.</p>
                <a href="paintings.php" class="mt-6 inline-block bg-ucf-green text-white font-bold py-3 px-6 rounded-lg hover:bg-ucf-green-dark transition-colors">
                    Browse Paintings
                </a>
            </div>
        <?php else: ?>
            <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
                <!-- Cart Items -->
                <div class="lg:col-span-2 bg-white p-6 rounded-lg shadow-md">
                    <ul role="list" class="divide-y divide-gray-200">
                        <?php foreach ($cart_details as $id => $item): ?>
                            <li class="py-6 flex">
                                <div class="h-24 w-24 flex-shrink-0 overflow-hidden rounded-md border border-gray-200">
                                    <img src="<?php echo htmlspecialchars($item['image_path']); ?>" alt="<?php echo htmlspecialchars($item['title']); ?>" class="h-full w-full object-cover object-center">
                                </div>
                                <div class="ml-4 flex flex-1 flex-col">
                                    <div>
                                        <div class="flex justify-between text-base font-medium text-ucf-charcoal">
                                            <h3>
                                                <a href="#"><?php echo htmlspecialchars($item['title']); ?></a>
                                            </h3>
                                            <p class="ml-4">₹<?php echo number_format($item['total'], 2); ?></p>
                                        </div>
                                    </div>
                                    <div class="flex flex-1 items-end justify-between text-sm">
                                        <form action="cart_handler.php" method="POST" class="flex items-center">
                                            <input type="hidden" name="action" value="update">
                                            <input type="hidden" name="painting_id" value="<?php echo $id; ?>">
                                            <label for="quantity-<?php echo $id; ?>" class="mr-2 text-gray-500">Qty:</label>
                                            <input type="number" id="quantity-<?php echo $id; ?>" name="quantity" value="<?php echo $item['quantity']; ?>" min="1" class="w-16 rounded border-gray-300" onchange="this.form.submit()">
                                        </form>
                                        <form action="cart_handler.php" method="POST">
                                            <input type="hidden" name="action" value="remove">
                                            <input type="hidden" name="painting_id" value="<?php echo $id; ?>">
                                            <button type="submit" class="font-medium text-red-600 hover:text-red-800">Remove</button>
                                        </form>
                                    </div>
                                </div>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                </div>

                <!-- Order Summary -->
                <div class="lg:col-span-1">
                    <div class="bg-white p-6 rounded-lg shadow-md sticky top-28">
                        <h2 class="text-lg font-medium text-ucf-charcoal">Order summary</h2>
                        <dl class="mt-6 space-y-4">
                            <div class="flex items-center justify-between">
                                <dt class="text-sm text-gray-600">Subtotal</dt>
                                <dd class="text-sm font-medium text-ucf-charcoal">₹<?php echo number_format($subtotal, 2); ?></dd>
                            </div>
                            <!-- You can add shipping and taxes here later -->
                        </dl>
                        <div class="mt-6">
                            <a href="checkout.php" class="w-full flex items-center justify-center rounded-md border border-transparent bg-ucf-green px-6 py-3 text-base font-medium text-white shadow-sm hover:bg-ucf-green-dark">
                                Proceed to Checkout
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </div>
</div>

<?php include 'footer.php'; ?>

