<?php
// File: checkout.php (PhonePe Fix)
session_start();

// Security check: User must be logged in to access this page
if (!isset($_SESSION['user_id'])) {
    $_SESSION['redirect_to_checkout'] = true;
    header('Location: login.php?error=login_required');
    exit();
}

include 'header.php';

// Recalculate cart totals to ensure accuracy
$cart_items = $_SESSION['cart'] ?? [];
$cart_details = [];
$subtotal = 0;

if (empty($cart_items)) {
    // If cart is empty, redirect them away
    header('Location: cart.php');
    exit();
}

// Fetch details for all paintings in the cart
$painting_ids = array_keys($cart_items);
if (!empty($painting_ids)) {
    $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'];
        $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-4xl mx-auto px-4 sm:px-6 lg:px-8">
        <h1 class="text-4xl font-extrabold text-ucf-charcoal text-center mb-12">Checkout</h1>
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-x-12">
            <!-- Shipping Information Form -->
            <div class="bg-white p-8 rounded-lg shadow-md">
                <h2 class="text-2xl font-bold text-ucf-charcoal mb-6">Shipping Information</h2>
                
                <!-- ⭐️⭐️⭐️ THE FIX IS HERE ⭐️⭐️⭐️ -->
                <!-- This form now correctly submits to the checkout_handler.php script -->
                <form action="checkout_handler.php" method="POST" class="space-y-4">
                    <div>
                        <label for="shipping_name" class="block text-sm font-medium text-gray-700">Full Name</label>
                        <input type="text" name="shipping_name" id="shipping_name" required class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-ucf-green focus:ring-ucf-green">
                    </div>
                    <div>
                        <label for="shipping_address" class="block text-sm font-medium text-gray-700">Shipping Address</label>
                        <textarea name="shipping_address" id="shipping_address" rows="3" required class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-ucf-green focus:ring-ucf-green"></textarea>
                    </div>
                     <div>
                        <label for="shipping_phone" class="block text-sm font-medium text-gray-700">Phone Number</label>
                        <input type="tel" name="shipping_phone" id="shipping_phone" required class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-ucf-green focus:ring-ucf-green">
                    </div>
                    <div class="pt-4">
                        <button type="submit" 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">
                            Place Order & Proceed to Payment
                        </button>
                    </div>
                </form>
            </div>

            <!-- Order Summary -->
            <div class="mt-10 lg:mt-0">
                 <h2 class="text-2xl font-bold text-ucf-charcoal mb-6">Your Order</h2>
                 <div class="bg-white p-6 rounded-lg shadow-md">
                    <ul role="list" class="divide-y divide-gray-200">
                        <?php foreach ($cart_details as $item): ?>
                            <li class="py-4 flex items-center">
                                <img src="<?php echo htmlspecialchars($item['image_path']); ?>" alt="<?php echo htmlspecialchars($item['title']); ?>" class="h-16 w-16 rounded-md object-cover">
                                <div class="ml-4 flex-1">
                                    <p class="font-medium text-ucf-charcoal"><?php echo htmlspecialchars($item['title']); ?></p>
                                    <p class="text-sm text-gray-500">Qty: <?php echo $item['quantity']; ?></p>
                                </div>
                                <p class="font-medium text-gray-800">₹<?php echo number_format($item['total'], 2); ?></p>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                    <dl class="mt-6 pt-6 border-t border-gray-200 space-y-4">
                        <div class="flex items-center justify-between font-bold text-lg">
                            <dt class="text-ucf-charcoal">Total</dt>
                            <dd class="text-ucf-charcoal">₹<?php echo number_format($subtotal, 2); ?></dd>
                        </div>
                    </dl>
                 </div>
            </div>
        </div>
    </div>
</div>

<?php include 'footer.php'; ?>