<?php
// checkout.php - Checkout Form & Order Database Submission (PDO Transactions & Auth Linked)
session_start();
require_once 'db.php';

// Enforce login access control: redirect to login if session not set
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

// Helper to check if cart is empty
function is_cart_empty() {
    return empty($_SESSION['cart']);
}

$action = isset($_GET['action']) ? $_GET['action'] : '';
$order_id = isset($_GET['order_id']) ? intval($_GET['order_id']) : 0;

// 1. SUCCESS STATE PAGE
if ($action === 'success' && $order_id > 0) {
    // Fetch Order details with prepared statement for safety
    $order_stmt = $pdo->prepare("SELECT * FROM orders WHERE id = :id AND user_id = :user_id");
    $order_stmt->execute([
        ':id' => $order_id,
        ':user_id' => $_SESSION['user_id']
    ]);
    $order = $order_stmt->fetch(PDO::FETCH_ASSOC);

    if (!$order) {
        header("Location: index.php");
        exit();
    }

    // Fetch Order Items
    $items_stmt = $pdo->prepare("
        SELECT oi.*, p.name as product_name, p.image 
        FROM order_items oi
        JOIN products p ON oi.product_id = p.id
        WHERE oi.order_id = :order_id
    ");
    $items_stmt->execute([':order_id' => $order_id]);
    $order_items = $items_stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Calculate total items
    $total_qty = 0;
    foreach ($order_items as $item) {
        $total_qty += $item['quantity'];
    }
}
// 2. SUBMIT FORM PROCESS STATE (POST)
elseif ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (is_cart_empty()) {
        header("Location: index.php");
        exit();
    }

    $customer_name = isset($_POST['name']) ? trim($_POST['name']) : '';
    $phone = isset($_POST['phone']) ? trim($_POST['phone']) : '';
    $address = isset($_POST['address']) ? trim($_POST['address']) : '';
    $payment_method = isset($_POST['payment_method']) ? trim($_POST['payment_method']) : 'COD';

    // Basic Validation
    if ($customer_name === '' || $phone === '' || $address === '') {
        $error_message = "กรุณากรอกข้อมูลผู้รับและที่จัดส่งให้ครบถ้วน";
    } else {
        // Calculate Total
        $total_price = 0;
        foreach ($_SESSION['cart'] as $item) {
            $total_price += ($item['price'] * $item['quantity']);
        }

        // Coupon Discount Calculation
        $discount = 0;
        $coupon_id = isset($_SESSION['applied_coupon_id']) ? intval($_SESSION['applied_coupon_id']) : 0;
        if ($coupon_id > 0) {
            $coupon_stmt = $pdo->prepare("
                SELECT c.* FROM user_coupons uc 
                JOIN coupons c ON uc.coupon_id = c.id 
                WHERE uc.user_id = :user_id AND uc.coupon_id = :coupon_id AND uc.is_used = 0
            ");
            $coupon_stmt->execute([
                ':user_id' => $_SESSION['user_id'],
                ':coupon_id' => $coupon_id
            ]);
            $coupon = $coupon_stmt->fetch(PDO::FETCH_ASSOC);

            if ($coupon && $total_price >= $coupon['min_order_value']) {
                if ($coupon['discount_type'] === 'percent') {
                    $discount = $total_price * ($coupon['discount_value'] / 100);
                } else {
                    $discount = $coupon['discount_value'];
                }
                if ($discount > $total_price) {
                    $discount = $total_price;
                }
            }
        }
        $final_price = $total_price - $discount;

        try {
            // Begin MySQL Transaction for database safety
            $pdo->beginTransaction();

            // Insert into orders (linked with logged-in user_id)
            $order_stmt = $pdo->prepare("
                INSERT INTO orders (user_id, customer_name, phone, address, total_price, status) 
                VALUES (:user_id, :name, :phone, :address, :total_price, 'Pending')
            ");
            $order_stmt->execute([
                ':user_id' => $_SESSION['user_id'],
                ':name' => $customer_name,
                ':phone' => $phone,
                ':address' => $address,
                ':total_price' => $final_price
            ]);
            
            $new_order_id = $pdo->lastInsertId();

            // Insert each item and update stock levels
            $item_stmt = $pdo->prepare("
                INSERT INTO order_items (order_id, product_id, size, color, quantity, price) 
                VALUES (:order_id, :product_id, :size, :color, :quantity, :price)
            ");
            
            $lock_stmt = $pdo->prepare("SELECT stock, name FROM products WHERE id = :id FOR UPDATE");
            $stock_update_stmt = $pdo->prepare("UPDATE products SET stock = stock - :qty WHERE id = :id");

            foreach ($_SESSION['cart'] as $item) {
                // Lock row and check stock
                $lock_stmt->execute([':id' => $item['product_id']]);
                $product = $lock_stmt->fetch(PDO::FETCH_ASSOC);
                
                if (!$product) {
                    throw new Exception("ไม่พบสินค้า ID " . $item['product_id']);
                }

                $available_stock = intval($product['stock']);
                if ($available_stock < $item['quantity']) {
                    throw new Exception("ขออภัย สินค้า '" . $product['name'] . "' มีจำนวนคงเหลือไม่เพียงพอในคลัง (คงเหลือ $available_stock ชิ้น)");
                }

                // Insert order item
                $item_stmt->execute([
                    ':order_id' => $new_order_id,
                    ':product_id' => $item['product_id'],
                    ':size' => $item['size'],
                    ':color' => $item['color'],
                    ':quantity' => $item['quantity'],
                    ':price' => $item['price']
                ]);

                // Deduct stock
                $stock_update_stmt->execute([
                    ':qty' => $item['quantity'],
                    ':id' => $item['product_id']
                ]);
            }

            // Mark Coupon as Used
            if ($coupon_id > 0) {
                $use_coupon_stmt = $pdo->prepare("
                    UPDATE user_coupons SET is_used = 1 WHERE user_id = :user_id AND coupon_id = :coupon_id
                ");
                $use_coupon_stmt->execute([
                    ':user_id' => $_SESSION['user_id'],
                    ':coupon_id' => $coupon_id
                ]);
            }

            // Commit Transaction
            $pdo->commit();

            // Clear Cart Session and Coupon
            $_SESSION['cart'] = [];
            unset($_SESSION['applied_coupon_id']);

            // Redirect to Success
            header("Location: checkout.php?action=success&order_id=" . $new_order_id);
            exit();

        } catch (Exception $e) {
            // Rollback on errors
            $pdo->rollBack();
            $error_message = "เกิดข้อผิดพลาดในการบันทึกคำสั่งซื้อ: " . $e->getMessage();
        }
    }
}
// 3. REGULAR CHECKOUT PAGE
else {
    if (is_cart_empty()) {
        header("Location: index.php");
        exit();
    }
    
    // Calculate totals
    $cart_count = 0;
    $grand_total = 0;
    foreach ($_SESSION['cart'] as $item) {
        $cart_count += $item['quantity'];
        $grand_total += ($item['price'] * $item['quantity']);
    }

    // Coupon Discount Calculation
    $discount = 0;
    $applied_coupon = null;
    if (isset($_SESSION['applied_coupon_id'])) {
        $coupon_stmt = $pdo->prepare("
            SELECT c.* FROM user_coupons uc 
            JOIN coupons c ON uc.coupon_id = c.id 
            WHERE uc.user_id = :user_id AND uc.coupon_id = :coupon_id AND uc.is_used = 0
        ");
        $coupon_stmt->execute([
            ':user_id' => $_SESSION['user_id'],
            ':coupon_id' => $_SESSION['applied_coupon_id']
        ]);
        $applied_coupon = $coupon_stmt->fetch(PDO::FETCH_ASSOC);

        if ($applied_coupon && $grand_total >= $applied_coupon['min_order_value']) {
            if ($applied_coupon['discount_type'] === 'percent') {
                $discount = $grand_total * ($applied_coupon['discount_value'] / 100);
            } else {
                $discount = $applied_coupon['discount_value'];
            }
            if ($discount > $grand_total) {
                $discount = $grand_total;
            }
        } else {
            unset($_SESSION['applied_coupon_id']);
        }
    }
    $total_due = $grand_total - $discount;
}
?>
<!DOCTYPE html>
<html lang="th" class="dark">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ชำระเงิน - NON LUXURY</title>
    <!-- Google Fonts -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Cinzel:wght@400;500;600;700;800;900&family=Cormorant+Garamond:ital,wght@0,300;0,400;0,500;0,600;0,700;1,300&family=Sarabun:wght@300;400;500;600;700&family=Montserrat:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <!-- Tailwind CSS CDN -->
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        cyber: {
                            bg: '#0A0A0B',        // Matte Deep Black
                            card: '#121215',      // Warm charcoal card
                            accent: '#D4AF37',    // Elegant Satin Gold
                            accentGlow: '#E5C158',// Brighter Champagne Gold
                            success: '#94A89A',   // Premium Muted Sage Green
                            danger: '#A94444',    // Luxury Wine Red
                            border: '#22211E'     // Subtle gold-tinted grey border
                        }
                    },
                    fontFamily: {
                        sans: ['Sarabun', 'Montserrat', 'sans-serif'],
                        cyber: ['Cinzel', 'Cormorant Garamond', 'Sarabun', 'serif']
                    }
                }
            }
        }
    </script>
    <style>
        body {
            background-color: #0A0A0B;
            color: #EAE6DF;
            font-family: 'Sarabun', sans-serif;
            background-image: radial-gradient(circle at 50% 0%, #171512 0%, #0A0A0B 70%);
        }
        .neon-text-purple {
            text-shadow: 0 0 5px #D4AF37, 0 0 10px rgba(212, 175, 55, 0.4);
        }
        .neon-text-success {
            text-shadow: 0 0 5px #94A89A, 0 0 10px rgba(148, 168, 154, 0.4);
        }
        .neon-border-purple {
            border-color: #D4AF37;
            box-shadow: 0 0 10px rgba(212, 175, 55, 0.2);
        }
        .cyber-grid {
            background-size: 40px 40px;
            background-image: 
                linear-gradient(to right, rgba(212, 175, 55, 0.02) 1px, transparent 1px),
                linear-gradient(to bottom, rgba(212, 175, 55, 0.02) 1px, transparent 1px);
        }
        .cyber-btn-glow:hover {
            box-shadow: 0 0 15px rgba(212, 175, 55, 0.4);
        }
    </style>
</head>
<body class="flex flex-col min-h-screen cyber-grid text-stone-200">

    <!-- Header Navigation -->
    <header class="sticky top-0 z-50 bg-[#0E0E10]/90 backdrop-blur-md border-b border-cyber-border">
        
        <!-- Top bar with user session metadata -->
        <div class="bg-[#050506] text-[10px] py-1.5 px-6 md:px-12 flex justify-between w-full text-stone-400 font-sans tracking-wide">
            <div class="flex gap-4">
                <span>VIP GUEST: <?php echo htmlspecialchars($_SESSION['username']); ?></span>
                <span>|</span>
                <span>STATUS: <span class="text-cyber-accent font-bold uppercase"><?php echo htmlspecialchars($_SESSION['role']); ?> MEMBER</span></span>
            </div>
            <div class="flex gap-4">
                <a href="index.php" class="text-cyber-accent hover:text-white transition font-bold tracking-widest">← BACK TO SALON</a>
            </div>
        </div>

        <div class="w-full px-6 md:px-12 py-4 flex items-center justify-between">
            <div class="flex items-center gap-3">
                <a href="index.php" class="flex items-center gap-3 text-2xl font-bold font-cyber tracking-wider hover:opacity-90 transition">
                    <div class="w-9 h-9 rounded-full bg-gradient-to-br from-cyber-accent to-cyber-border flex items-center justify-center shadow-lg border border-cyber-accent/40">
                        <span class="text-cyber-accent text-sm">N</span>
                    </div>
                    <span class="font-cyber font-medium text-lg tracking-[0.35em] text-white">NON LUXURY</span>
                </a>
            </div>
            <span class="text-[11px] font-cyber tracking-[0.25em] text-stone-400">// SECURE CHECKOUT</span>
        </div>
    </header>
<!-- Language Selector -->
<div class="flex justify-end px-6 md:px-12 mb-4">
    <select id="lang-selector" class="bg-[#0A0A0B] text-stone-200 border border-cyber-border rounded p-1">
        <option value="th">ไทย</option>
        <option value="en">English</option>
        <option value="zh">中文</option>
        <option value="ja">日本語</option>
        <option value="ko">한국어</option>
    </select>
</div>
    <!-- Main Container -->
    <main class="flex-grow w-full px-6 md:px-12 py-8">

        <?php if ($action === 'success' && isset($order)): ?>
            
            <!-- 1. Order Success Screen -->
            <div class="max-w-2xl mx-auto bg-cyber-card border border-cyber-border rounded-2xl p-8 shadow-2xl mt-4 text-center relative overflow-hidden">
                <div class="absolute -top-10 -right-10 w-24 h-24 bg-cyber-accent/15 rounded-full blur-2xl"></div>

                <!-- Check Icon -->
                <div class="w-16 h-16 bg-stone-900 text-cyber-accent border border-cyber-accent/30 rounded-full flex items-center justify-center mx-auto mb-5 shadow-lg">
                    <svg class="w-9 h-9" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M5 13l4 4L19 7"></path>
                    </svg>
                </div>
                
                <h2 class="text-2xl font-cyber font-medium text-white tracking-[0.2em] uppercase" data-lang-key="acquisition_completed"></h2>
                <p class="text-xs text-stone-400 mt-2 font-sans" data-lang-key="acquisition_completed_subtitle"></p>
                
                <!-- Order Code Box -->
                <div class="bg-black border border-cyber-border rounded py-3.5 px-4 my-6 text-xs flex flex-col sm:flex-row items-center justify-between gap-2 max-w-md mx-auto font-sans">
                    <span class="text-stone-400" data-lang-key="acquisition_id"></span>
                    <strong class="text-cyber-accent neon-text-purple font-cyber text-sm">#ORD-014-<?php echo str_pad($order['id'], 6, '0', STR_PAD_LEFT); ?></strong>
                </div>

                <!-- Receipt Detail Structure -->
                <div class="border-t border-b border-cyber-border/60 py-6 text-left text-xs space-y-4 max-w-xl mx-auto">
                    <h3 class="font-cyber font-medium text-cyber-accent tracking-wider text-[11px] uppercase" data-lang-key="acquisition_summary"></h3>
                    
                    <!-- Items Purchased list -->
                    <div class="space-y-3.5">
                        <?php foreach ($order_items as $item): ?>
                            <div class="flex items-center justify-between gap-4 bg-black/50 border border-cyber-border p-3 rounded">
                                <div class="flex items-center gap-3">
                                    <div class="w-9 h-9 rounded overflow-hidden border border-cyber-border shrink-0 bg-black">
                                        <img src="<?php echo htmlspecialchars($item['image']); ?>" class="w-full h-full object-cover">
                                    </div>
                                    <div>
                                        <h4 class="font-serif text-white text-[11px] line-clamp-1"><?php echo htmlspecialchars($item['product_name']); ?></h4>
                                        <p class="text-[9px] text-stone-500 font-sans">SIZE: <?php echo htmlspecialchars($item['size']); ?> | COLOR: <?php echo htmlspecialchars($item['color']); ?></p>
                                    </div>
                                </div>
                                <span class="text-[10px] text-stone-400 font-sans">x<?php echo $item['quantity']; ?></span>
                                <span class="text-xs font-cyber font-medium text-cyber-accent">฿<?php echo number_format($item['price'] * $item['quantity'], 2); ?></span>
                            </div>
                        <?php endforeach; ?>
                    </div>

                    <!-- Receipt Prices -->
                    <div class="pt-4 border-t border-cyber-border/50 space-y-2">
                        <div class="flex justify-between font-sans text-stone-400">
                            <span class="text-stone-400" data-lang-key="subtotal_label"></span>
                            <span class="text-stone-300">฿<?php echo number_format($order['total_price'], 2); ?></span>
                        </div>
                        <div class="flex justify-between font-sans text-stone-400">
                            <span>บริการนำส่งพัสดุ:</span>
                            <span class="text-cyber-success font-semibold">COMPLIMENTARY</span>
                        </div>
                        <div class="flex justify-between font-cyber font-medium text-sm pt-2.5 border-t border-cyber-border/50">
                            <span class="text-white tracking-wider">ยอดรวมการทำธุรกรรม:</span>
                            <span class="text-cyber-accent neon-text-purple">฿<?php echo number_format($order['total_price'], 2); ?></span>
                        </div>
                    </div>

                    <!-- Customer shipment details -->
                    <div class="pt-4 space-y-2 bg-black/30 p-3 rounded border border-cyber-border font-sans text-[10px]">
                        <p class="font-cyber font-medium text-cyber-accent text-[11px] mb-1 uppercase">// รายละเอียดผู้สั่งซื้อและการจัดส่ง (DELIVERY DETAILS):</p>
                        <p class="text-stone-400"><span class="text-stone-500">ผู้รับสิทธิ์:</span> <?php echo htmlspecialchars($order['customer_name']); ?></p>
                        <p class="text-stone-400"><span class="text-stone-500">โทรศัพท์:</span> <?php echo htmlspecialchars($order['phone']); ?></p>
                        <p class="text-stone-400"><span class="text-stone-500">สถานที่นำส่ง:</span> <?php echo htmlspecialchars($order['address']); ?></p>
                    </div>
                </div>

                <!-- Back button -->
                <div class="mt-8 flex flex-col sm:flex-row gap-4 justify-center max-w-xs mx-auto">
                    <a href="index.php" class="w-full bg-cyber-accent hover:bg-cyber-accentGlow text-black font-cyber font-semibold tracking-widest py-3 rounded transition">
                        RETURN TO SALON
                    </a>
                </div>
            </div>

        <?php else: ?>

            <!-- 2. Form Entry Checkout -->
            <div class="flex flex-col lg:flex-row gap-8 mt-4">
                
                <!-- Left Form Panel -->
                <form action="checkout.php" method="POST" class="flex-grow space-y-6">
                    
                    <!-- Error notice -->
                    <?php if (isset($error_message)): ?>
                        <div class="bg-[#2D1B1B] border border-cyber-danger text-cyber-danger rounded p-4 text-xs font-semibold flex items-center gap-2">
                            <span>⚠</span>
                            <span><?php echo $error_message; ?></span>
                        </div>
                    <?php endif; ?>

                    <!-- Shipping Address Card -->
                    <div class="bg-cyber-card rounded-xl p-6 border border-cyber-border shadow-lg space-y-4">
                        <h3 class="font-cyber font-medium text-xs text-white border-b border-cyber-border pb-3 flex items-center gap-2 tracking-wider">
                            <span class="text-cyber-accent">⚜️</span>
                            <span class="uppercase">SHIPPING ADDRESS // สถานที่นำส่งพัสดุและผู้รับสิทธิ์</span>
                        </h3>
                        
                        <div class="grid grid-cols-1 sm:grid-cols-2 gap-4 text-xs">
                            <div class="space-y-1.5">
                                <label class="text-[9px] font-sans tracking-widest uppercase text-cyber-accent font-semibold block">ชื่อ-นามสกุล ผู้รับ *</label>
                                <input type="text" name="name" required placeholder="เช่น คุณณภัทร เลิศวรพงศ์" class="w-full bg-[#0A0A0B] border border-cyber-border px-4 py-2.5 rounded text-white outline-none focus:border-cyber-accent transition font-sans">
                            </div>
                            <div class="space-y-1.5">
                                <label class="text-[9px] font-sans tracking-widest uppercase text-cyber-accent font-semibold block">เบอร์โทรศัพท์ติดต่อ *</label>
                                <input type="tel" name="phone" required placeholder="เช่น 0891234567" class="w-full bg-[#0A0A0B] border border-cyber-border px-4 py-2.5 rounded text-white outline-none focus:border-cyber-accent transition font-sans">
                            </div>
                        </div>
                        
                        <div class="space-y-1.5 text-xs">
                            <label class="text-[9px] font-sans tracking-widest uppercase text-cyber-accent font-semibold block">ที่อยู่นำจัดส่งโดยละเอียด *</label>
                            <textarea name="address" rows="3" required placeholder="ระบุเลขที่พำนัก, ถนน, ตำบล, อำเภอ, จังหวัด และรหัสไปรษณีย์..." class="w-full bg-[#0A0A0B] border border-cyber-border px-4 py-2.5 rounded text-white outline-none focus:border-cyber-accent transition resize-none font-sans"></textarea>
                        </div>
                    </div>

                    <!-- Payment Option Card -->
                    <div class="bg-cyber-card rounded-xl p-6 border border-cyber-border shadow-lg space-y-4">
                        <h3 class="font-cyber font-medium text-xs text-white border-b border-cyber-border pb-3 flex items-center gap-2 tracking-wider">
                            <span class="text-cyber-accent">💳</span>
                            <span class="uppercase">PAYMENT GATEWAY // ช่องทางการชำระเงิน</span>
                        </h3>

                        <div class="space-y-3">
                            <!-- COD -->
                            <label class="flex items-center gap-3 p-4 border border-cyber-border bg-[#0A0A0B]/50 rounded cursor-pointer hover:bg-stone-900/40 hover:border-cyber-accent transition" onclick="togglePaymentMock(false)">
                                <input type="radio" name="payment_method" value="COD" checked class="w-4 h-4 text-cyber-accent focus:ring-cyber-accent bg-[#0A0A0B] border-cyber-border">
                                <div class="text-xs font-sans">
                                    <p class="font-semibold text-white">ชำระเงินปลายทาง (Cash on Delivery)</p>
                                    <p class="text-[9px] text-stone-500 mt-0.5">// จัดส่งแบบพรีเมียม ชำระเงินสดหรือบัตรเครดิตเมื่อสินค้าถึงท่าน</p>
                                </div>
                            </label>

                            <!-- Bank Transfer QR Code simulation -->
                            <label class="flex items-center gap-3 p-4 border border-cyber-border bg-[#0A0A0B]/50 rounded cursor-pointer hover:bg-stone-900/40 hover:border-cyber-accent transition" onclick="togglePaymentMock(true)">
                                <input type="radio" name="payment_method" value="Bank Transfer" class="w-4 h-4 text-cyber-accent focus:ring-cyber-accent bg-[#0A0A0B] border-cyber-border">
                                <div class="text-xs font-sans">
                                    <p class="font-semibold text-white">โอนเงินเข้าบัญชีธนาคาร / PromptPay QR Code</p>
                                    <p class="text-[9px] text-stone-500 mt-0.5">// ยืนยันการชำระเงินผ่านระบบอัตโนมัติ เพื่อการจัดส่งที่รวดเร็วเป็นพิเศษ</p>
                                </div>
                            </label>
                        </div>

                        <!-- Mock QR PromptPay Area -->
                        <div id="promptpay-mock" class="hidden border border-cyber-border bg-black rounded p-6 flex flex-col items-center gap-4 text-center mt-4">
                            <p class="text-[9px] font-sans font-semibold text-cyber-accent uppercase tracking-widest">// SECURE QR PROMPTPAY PORTAL</p>
                            
                            <div class="bg-white border border-stone-300 p-4 rounded shadow-sm relative">
                                <svg class="w-40 h-40 text-stone-800 mx-auto" viewBox="0 0 100 100" fill="currentColor">
                                    <rect x="10" y="10" width="20" height="20" />
                                    <rect x="15" y="15" width="10" height="10" fill="white" />
                                    <rect x="70" y="10" width="20" height="20" />
                                    <rect x="75" y="15" width="10" height="10" fill="white" />
                                    <rect x="10" y="70" width="20" height="20" />
                                    <rect x="15" y="75" width="10" height="10" fill="white" />
                                    <rect x="40" y="40" width="20" height="20" />
                                    <rect x="45" y="45" width="10" height="10" fill="white" />
                                    <rect x="40" y="15" width="5" height="15" />
                                    <rect x="50" y="10" width="15" height="5" />
                                    <rect x="15" y="40" width="15" height="5" />
                                    <rect x="10" y="55" width="5" height="10" />
                                    <rect x="70" y="45" width="10" height="15" />
                                    <rect x="80" y="70" width="10" height="5" />
                                    <rect x="70" y="80" width="5" height="10" />
                                    <rect x="45" y="70" width="15" height="15" />
                                </svg>
                                <span class="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 bg-[#002D62] text-white text-[8px] px-1 font-bold rounded">PPAY</span>
                            </div>
                            <div class="text-[11px] font-sans">
                                <p class="font-semibold text-white">ผู้รับโอน: บจก. นนทวัฒน์ แฟชั่นช็อป 014</p>
                                <p class="text-stone-400 mt-1">ยอดชำระ: <strong class="text-cyber-accent neon-text-purple font-cyber text-sm">฿<?php echo number_format($total_due, 2); ?></strong></p>
                                <p class="text-[9px] text-stone-500 mt-2">*(ระบบจำลอง: รายการโอนจะตรวจพบโดยอัตโนมัติเมื่อท่านทำการสั่งซื้อสำเร็จ)</p>
                            </div>
                        </div>
                    </div>

                    <!-- Hidden Button to trigger actual submit -->
                    <button type="submit" id="real-submit-btn" class="hidden"></button>
                </form>

                <!-- Right checkout summary panel -->
                <aside class="w-full lg:w-1/3 shrink-0">
                    <div class="bg-cyber-card rounded-xl p-6 border border-cyber-border shadow-lg space-y-6 sticky top-28">
                        <h3 class="font-cyber font-medium text-xs text-white border-b border-cyber-border pb-3 tracking-wider uppercase">SELECTIONS // ถุงช้อปปิ้งของท่าน</h3>

                        <!-- Items list -->
                        <div class="space-y-4 max-h-52 overflow-y-auto pr-1">
                            <?php foreach ($_SESSION['cart'] as $item): ?>
                                <div class="flex items-center justify-between gap-3 text-xs font-sans">
                                    <div class="flex items-center gap-2 min-w-0">
                                        <div class="w-8 h-8 rounded border border-cyber-border overflow-hidden shrink-0 bg-black">
                                            <img src="<?php echo htmlspecialchars($item['image']); ?>" class="w-full h-full object-cover">
                                        </div>
                                        <div class="min-w-0">
                                            <h4 class="font-serif text-white truncate"><?php echo htmlspecialchars($item['name']); ?></h4>
                                            <p class="text-[9px] text-stone-500 truncate">SIZE: <?php echo htmlspecialchars($item['size']); ?> | COL: <?php echo htmlspecialchars($item['color']); ?></p>
                                        </div>
                                    </div>
                                    <span class="text-stone-400">x<?php echo $item['quantity']; ?></span>
                                    <span class="font-cyber font-medium text-cyber-accent whitespace-nowrap">฿<?php echo number_format($item['price'] * $item['quantity'], 2); ?></span>
                                </div>
                            <?php endforeach; ?>
                        </div>

                        <!-- Pricing breakdown -->
                        <div class="pt-4 border-t border-cyber-border space-y-2 text-xs font-sans text-stone-400">
                            <div class="flex justify-between">
                                <span>ราคาสินค้ารวม (<?php echo $cart_count; ?> ชิ้น):</span>
                                <span class="text-stone-200">฿<?php echo number_format($grand_total, 2); ?></span>
                            </div>
                            <?php if ($discount > 0): ?>
                                <div class="flex justify-between text-cyber-success">
                                    <span>ส่วนลดคูปอง VIP (<?php echo htmlspecialchars($applied_coupon['code']); ?>):</span>
                                    <span class="font-semibold">-฿<?php echo number_format($discount, 2); ?></span>
                                </div>
                            <?php endif; ?>
                            <div class="flex justify-between">
                                <span>บริการนำส่งพัสดุ:</span>
                                <span class="text-cyber-success font-semibold">COMPLIMENTARY</span>
                            </div>
                        </div>

                        <!-- Grand Total -->
                        <div class="pt-4 border-t border-cyber-border flex justify-between items-end">
                            <span class="font-cyber font-medium text-xs text-white uppercase tracking-wider">TOTAL_DUE:</span>
                            <span class="text-xl font-cyber font-medium text-cyber-accent neon-text-purple">
                                ฿<?php echo number_format($total_due, 2); ?>
                            </span>
                        </div>

                        <!-- Action buttons -->
                        <div class="space-y-3 pt-2">
                            <button type="button" 
                                    onclick="triggerFormSubmit()"
                                    class="w-full bg-cyber-accent hover:bg-cyber-accentGlow text-black font-cyber font-semibold tracking-widest py-3 rounded transition text-center block focus:outline-none text-xs uppercase">
                                CONFIRM TRANSACTION
                            </button>
                            <a href="cart.php" 
                               class="block w-full bg-[#0A0A0B] hover:bg-stone-900 text-stone-400 hover:text-white border border-cyber-border text-center font-semibold py-2.5 rounded transition text-xs">
                                RETURN TO BAG
                            </a>
                        </div>
                    </div>
                </aside>
            </div>

        <?php endif; ?>

    </main>

    <!-- Footer -->
    <footer class="bg-[#050506] border-t border-cyber-border text-stone-500 py-8 mt-12 text-xs">
        <div class="w-full px-6 md:px-12 flex flex-col md:flex-row items-center justify-between gap-4">
            <div>
                <p>⚜️ <span class="font-cyber tracking-[0.25em] text-white">NON LUXURY</span> // SECURE CHECKOUT PORTAL</p>
                <p class="text-[10px] text-stone-600 mt-1">DB Connection via PDO MySQL // System Port: 014</p>
            </div>
            <div class="text-right">
                <p>VIP CLIENT SERVICES: <span class="text-white font-bold">Nontawat 014</span></p>
                <p class="text-[10px] text-stone-600 mt-1">© 2026 Simulation Server.</p>
            </div>
        </div>
    </footer>

    <!-- Interactive script -->
    <script>
        function togglePaymentMock(show) {
            const qrMock = document.getElementById('promptpay-mock');
            if (show) {
                qrMock.classList.remove('hidden');
            } else {
                qrMock.classList.add('hidden');
            }
        }

        function triggerFormSubmit() {
            document.getElementById('real-submit-btn').click();
        }
    </script>

</body>
</html>
