<?php
// checkout.php - Final Cart Review and Order Confirmation

require_once 'includes/helper.php';
require_once 'classes/Cart.php';

start_secure_session();

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$userId = $_SESSION['user_id'];
$cartObj = new Cart();
$cartDetails = $cartObj->getDetails($userId);
$totals = $cartObj->getTotals($userId);

if ($totals['total_items'] <= 0) {
    header("Location: index.php");
    exit();
}

$csrfToken = generate_csrf_token();
require_once 'includes/header.php';
?>

<div class="max-w-2xl mx-auto my-4 sm:my-6">
    <div class="glass p-6 sm:p-8 rounded-2xl sm:rounded-3xl shadow-2xl relative overflow-hidden">
        <div class="absolute -top-12 -left-12 w-32 h-32 bg-violet-600/10 rounded-full blur-2xl pointer-events-none"></div>

        <h2 class="text-2xl sm:text-3xl font-extrabold text-white mb-2 tracking-tight text-center">ยืนยันรายการสั่งซื้อ</h2>
        <p class="text-slate-400 text-sm text-center mb-6 sm:mb-8">กรุณาตรวจสอบสินค้าในตะกร้าของท่านก่อนทำการสั่งซื้อ</p>

        <!-- Product list in checkout -->
        <div class="space-y-4 mb-8">
            <?php foreach ($cartDetails as $item): ?>
                <div class="flex items-center justify-between border-b border-slate-900 pb-3">
                    <div>
                        <h4 class="font-bold text-slate-200"><?= escape($item['product_name']) ?></h4>
                        <p class="text-xs text-slate-500">จำนวน: <?= $item['quantity'] ?> ชิ้น | ขนาด: <span class="text-indigo-400 font-semibold"><?= escape($item['size'] ?? 'Free Size') ?></span></p>
                    </div>
                    <span class="font-bold text-violet-400"><?= format_price($item['subtotal']) ?></span>
                </div>
            <?php endforeach; ?>
        </div>

        <div class="flex justify-between items-baseline mb-8">
            <span class="text-slate-400 font-bold">ยอดชำระสุทธิ</span>
            <span class="text-3xl font-black text-violet-400"><?= format_price($totals['total_amount']) ?></span>
        </div>

        <!-- Checkout Action Form -->
        <form action="cart.php" method="POST">
            <input type="hidden" name="csrf_token" value="<?= escape($csrfToken) ?>">
            <input type="hidden" name="action" value="checkout">
            
                    <button type="submit" class="w-full py-3.5 sm:py-4 bg-gradient-to-r from-violet-600 to-indigo-600 hover:from-violet-500 hover:to-indigo-500 text-white font-bold rounded-xl sm:rounded-2xl shadow-lg shadow-violet-600/35 transition-all duration-200 active:scale-95 text-sm sm:text-base">
                        สั่งซื้อและชำระเงินทันที (มีเวลา 20 นาที) &rarr;
                    </button>
        </form>

        <div class="text-center mt-4">
            <a href="cart.php" class="text-xs text-slate-500 hover:text-slate-300">ย้อนกลับไปแก้ไขตะกร้า</a>
        </div>
    </div>
</div>

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