<?php
// cart.php - Shopping Cart Details & Checkout trigger

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

start_secure_session();

// Redirect to login if user session is not active
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$userId = $_SESSION['user_id'];
$cartObj = new Cart();
$orderObj = new Order();

$error = '';
$success = '';
$csrfToken = generate_csrf_token();

// Handle Actions (Remove / Update quantity)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $token = $_POST['csrf_token'] ?? '';
    
    if (!validate_csrf_token($token)) {
        $error = "ระบบความปลอดภัย: CSRF Token ไม่ถูกต้อง";
    } else {
        if ($_POST['action'] === 'remove') {
            $productId = (int)($_POST['product_id'] ?? 0);
            $size = trim($_POST['size'] ?? 'Free Size');
            $cartObj->remove($userId, $productId, $size);
            header("Location: cart.php");
            exit();
        } 
        
        if ($_POST['action'] === 'update') {
            $productId = (int)($_POST['product_id'] ?? 0);
            $qty = (int)($_POST['quantity'] ?? 0);
            $size = trim($_POST['size'] ?? 'Free Size');
            $cartObj->updateQuantity($userId, $productId, $qty, $size);
            header("Location: cart.php");
            exit();
        }

        if ($_POST['action'] === 'checkout') {
            try {
                // Returns order_id upon transactional completion
                $orderId = $orderObj->checkout($userId);
                header("Location: payment.php?order_id=" . $orderId);
                exit();
            } catch (Exception $e) {
                $error = "การสั่งซื้อล้มเหลว: " . $e->getMessage();
            }
        }
    }
}

$cartDetails = $cartObj->getDetails($userId);
$totals = $cartObj->getTotals($userId);

require_once 'includes/header.php';
?>

<h2 class="text-2xl sm:text-3xl font-extrabold text-white mb-4 sm:mb-6 tracking-tight flex items-center gap-3">
    <span>🛒</span> ตะกร้าสินค้า
</h2>

<?php if ($error): ?>
    <div class="bg-red-950/60 border border-red-800 text-red-300 p-4 rounded-2xl text-sm mb-6 animate-pulse">
        ⚠️ <?= escape($error) ?>
    </div>
<?php endif; ?>

<div class="grid grid-cols-1 lg:grid-cols-3 gap-6 lg:gap-8">
    <!-- Cart Items Detail -->
    <div class="lg:col-span-2 space-y-4">
        <?php if (empty($cartDetails)): ?>
            <div class="glass p-8 sm:p-12 rounded-2xl sm:rounded-3xl text-center">
                <span class="text-4xl sm:text-5xl block mb-4">🛒</span>
                <p class="text-slate-400 text-sm sm:text-base">ยังไม่มีสินค้าในตะกร้าของคุณ</p>
                <a href="index.php" class="inline-block mt-4 text-sm text-violet-400 font-semibold hover:text-violet-300 transition-colors">ไปเลือกซื้อสินค้ากันเลย &rarr;</a>
            </div>
        <?php else: ?>
            <?php foreach ($cartDetails as $item): ?>
                <div class="glass rounded-2xl sm:rounded-3xl p-4 sm:p-5 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
                    <div class="flex items-center gap-3 sm:gap-4">
                        <div class="h-12 w-12 sm:h-16 sm:w-16 bg-slate-900 border border-slate-800 rounded-xl sm:rounded-2xl flex items-center justify-center overflow-hidden flex-shrink-0">
                            <?php $itemImg = get_product_image_url($item['image_url'] ?? '', $item['product_name'] ?? ''); ?>
                            <?php if (!empty($itemImg)): ?>
                                <img src="<?= escape($itemImg) ?>" alt="<?= escape($item['product_name']) ?>" class="w-full h-full object-cover" onerror="if(!this.dataset.tried){ this.dataset.tried='1'; this.src=(this.src.indexOf('assets/')!==-1 ? this.src.replace('assets/','รูป/') : this.src.replace('รูป/','assets/')); } else { this.style.display='none'; if(this.nextElementSibling) this.nextElementSibling.style.display='inline'; }">
                                <span class="text-xl sm:text-2xl hidden">📦</span>
                            <?php else: ?>
                                <span class="text-xl sm:text-2xl">📦</span>
                            <?php endif; ?>
                        </div>
                        <div>
                            <h3 class="font-bold text-sm sm:text-base text-slate-100 line-clamp-1"><?= escape($item['product_name']) ?></h3>
                            <p class="text-[10px] sm:text-xs text-slate-400 mt-0.5">ราคาต่อหน่วย: <?= format_price($item['unit_price']) ?> | ขนาด: <span class="text-indigo-400 font-semibold"><?= escape($item['size'] ?? 'Free Size') ?></span></p>
                        </div>
                    </div>

                    <!-- Quantity Control / Delete -->
                    <div class="flex items-center gap-3 sm:gap-4 w-full sm:w-auto justify-between sm:justify-end border-t border-slate-800/40 sm:border-t-0 pt-3 sm:pt-0">
                        <form action="cart.php" method="POST" class="flex items-center gap-1.5">
                            <input type="hidden" name="csrf_token" value="<?= escape($csrfToken) ?>">
                            <input type="hidden" name="action" value="update">
                            <input type="hidden" name="product_id" value="<?= $item['product_id'] ?>">
                            <input type="hidden" name="size" value="<?= escape($item['size'] ?? 'Free Size') ?>">
                            
                            <button type="submit" name="quantity" value="<?= $item['quantity'] - 1 ?>" 
                                    class="w-7 h-7 sm:w-8 sm:h-8 rounded-lg bg-slate-900 border border-slate-800 flex items-center justify-center text-slate-400 hover:text-violet-400 transition-all font-bold text-sm">
                                -
                            </button>
                            <span class="w-8 sm:w-10 text-center font-bold text-slate-200 text-xs sm:text-sm"><?= $item['quantity'] ?></span>
                            <button type="submit" name="quantity" value="<?= $item['quantity'] + 1 ?>" 
                                    class="w-7 h-7 sm:w-8 sm:h-8 rounded-lg bg-slate-900 border border-slate-800 flex items-center justify-center text-slate-400 hover:text-violet-400 transition-all font-bold text-sm">
                                +
                            </button>
                        </form>

                        <div class="flex items-center gap-3 sm:gap-4">
                            <span class="font-black text-slate-100 text-sm sm:text-base"><?= format_price($item['subtotal']) ?></span>
                            
                            <!-- Remove Item -->
                            <form action="cart.php" method="POST">
                                <input type="hidden" name="csrf_token" value="<?= escape($csrfToken) ?>">
                                <input type="hidden" name="action" value="remove">
                                <input type="hidden" name="product_id" value="<?= $item['product_id'] ?>">
                                <input type="hidden" name="size" value="<?= escape($item['size'] ?? 'Free Size') ?>">
                                <button type="submit" class="text-red-400 hover:text-red-300 text-xs sm:text-sm font-semibold transition-colors">
                                    ลบ
                                </button>
                            </form>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>

    <!-- Order Summary card -->
    <?php if (!empty($cartDetails)): ?>
        <div class="glass rounded-2xl sm:rounded-3xl p-5 sm:p-6 h-fit shadow-xl relative overflow-hidden lg:sticky lg:top-24">
            <div class="absolute -top-12 -right-12 w-28 h-28 bg-violet-600/10 rounded-full blur-2xl"></div>

            <h3 class="text-lg sm:text-xl font-bold text-white mb-5 sm:mb-6">สรุปคำสั่งซื้อ</h3>
            <div class="space-y-3 sm:space-y-4 border-b border-slate-900 pb-5 sm:pb-6 mb-5 sm:mb-6 text-xs sm:text-sm">
                <div class="flex justify-between text-slate-400">
                    <span>สินค้าทั้งหมด</span>
                    <span class="font-semibold text-slate-200"><?= $totals['total_items'] ?> ชิ้น</span>
                </div>
                <div class="flex justify-between text-slate-400">
                    <span>ค่าจัดส่ง</span>
                    <span class="text-emerald-400 font-semibold">ฟรี</span>
                </div>
            </div>

            <!-- Price Calculated automatically by SQL View -->
            <div class="flex justify-between items-baseline mb-6 sm:mb-8">
                <span class="text-xs sm:text-sm font-bold text-slate-400">ยอดรวมสุทธิ</span>
                <span class="text-xl sm:text-2xl font-black text-violet-400"><?= format_price($totals['total_amount']) ?></span>
            </div>

            <!-- Checkout 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 sm:py-4 bg-gradient-to-r from-violet-600 to-indigo-600 hover:from-violet-500 hover:to-indigo-500 text-white text-sm sm:text-base font-bold rounded-xl sm:rounded-2xl shadow-lg shadow-violet-600/35 transition-all duration-200">
                    สั่งซื้อและดำเนินการชำระเงิน &rarr;
                </button>
            </form>

            <p class="text-[10px] sm:text-[11px] text-slate-500 text-center mt-4 leading-relaxed">
                * เมื่อกดสั่งซื้อแล้ว ท่านจะมีเวลานับถอยหลัง 20 นาทีในการทำรายการชำระเงิน หากเกินเวลาออเดอร์นี้จะถูกยกเลิก (Expired) ทันที
            </p>
        </div>
    <?php endif; ?>
</div>

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