<?php
// cart.php - Session Shopping Cart Manager (Cyberpunk Theme)
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();
}

// Initialize session cart if not exists
if (!isset($_SESSION['cart'])) {
    $_SESSION['cart'] = [];
}

// 1. Process Actions (Adding to Cart)
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action']) && $_POST['action'] == 'add') {
    $product_id = isset($_POST['product_id']) ? intval($_POST['product_id']) : 0;
    $size = isset($_POST['size']) ? trim($_POST['size']) : '';
    $color = isset($_POST['color']) ? trim($_POST['color']) : '';
    $quantity = isset($_POST['quantity']) ? intval($_POST['quantity']) : 1;
    $redirect_checkout = isset($_POST['redirect_checkout']) ? intval($_POST['redirect_checkout']) : 0;

    if ($product_id > 0 && $size !== '' && $color !== '' && $quantity >= 1) {
        // Fetch product info securely
        $stmt = $pdo->prepare("SELECT * FROM products WHERE id = :id");
        $stmt->execute([':id' => $product_id]);
        $product = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($product) {
            $stock = intval($product['stock']);
            $price = floatval($product['price']);
            
            // Check duplicate items
            $found = false;
            foreach ($_SESSION['cart'] as $index => $item) {
                if ($item['product_id'] === $product_id && $item['size'] === $size && $item['color'] === $color) {
                    $new_qty = $item['quantity'] + $quantity;
                    if ($new_qty > $stock) {
                        $new_qty = $stock;
                    }
                    $_SESSION['cart'][$index]['quantity'] = $new_qty;
                    $found = true;
                    break;
                }
            }

            // Add new item
            if (!$found) {
                if ($quantity > $stock) {
                    $quantity = $stock;
                }
                $_SESSION['cart'][] = [
                    'product_id' => $product_id,
                    'name' => $product['name'],
                    'image' => $product['image'],
                    'size' => $size,
                    'color' => $color,
                    'quantity' => $quantity,
                    'price' => $price
                ];
            }
        }
    }

    if ($redirect_checkout === 1) {
        header("Location: checkout.php");
    } else {
        header("Location: cart.php");
    }
    exit();
}

// 2. Handle GET actions (remove, quantity update)
if ($_SERVER['REQUEST_METHOD'] == 'GET' && isset($_GET['action'])) {
    $action = $_GET['action'];
    $key = isset($_GET['key']) ? intval($_GET['key']) : -1;

    if ($key >= 0 && isset($_SESSION['cart'][$key])) {
        if ($action == 'remove') {
            unset($_SESSION['cart'][$key]);
            $_SESSION['cart'] = array_values($_SESSION['cart']); // Re-index array
        } elseif ($action == 'update') {
            $qty = isset($_GET['qty']) ? intval($_GET['qty']) : 1;
            if ($qty < 1) {
                $qty = 1;
            }

            // Verify stock limit
            $product_id = $_SESSION['cart'][$key]['product_id'];
            $stmt = $pdo->prepare("SELECT stock FROM products WHERE id = :id");
            $stmt->execute([':id' => $product_id]);
            $stock = intval($stmt->fetchColumn());

            if ($qty > $stock) {
                $qty = $stock;
            }

            $_SESSION['cart'][$key]['quantity'] = $qty;
        }
    }
    header("Location: cart.php");
    exit();
}

// 3. Handle Coupon Apply / Remove
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] == 'apply_coupon') {
        $coupon_id = isset($_POST['coupon_id']) ? intval($_POST['coupon_id']) : 0;
        if ($coupon_id > 0) {
            // Check if user has this coupon and it is unused
            $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
            ");
            $stmt->execute([
                ':user_id' => $_SESSION['user_id'],
                ':coupon_id' => $coupon_id
            ]);
            $coupon = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($coupon) {
                // Calculate current grand total
                $temp_total = 0;
                foreach ($_SESSION['cart'] as $item) {
                    $temp_total += ($item['price'] * $item['quantity']);
                }

                if ($temp_total >= $coupon['min_order_value']) {
                    $_SESSION['applied_coupon_id'] = $coupon_id;
                    $_SESSION['coupon_success'] = "เปิดใช้งานคูปอง " . htmlspecialchars($coupon['code']) . " สำเร็จ!";
                } else {
                    $_SESSION['coupon_error'] = "ยอดเงินรวมยังไม่ถึงขั้นต่ำ ฿" . number_format($coupon['min_order_value']) . " ของคูปองนี้";
                }
            } else {
                $_SESSION['coupon_error'] = "ไม่พบคูปองนี้ หรือคูปองถูกใช้งานไปแล้ว";
            }
        }
        header("Location: cart.php");
        exit();
    } elseif ($_POST['action'] == 'remove_coupon') {
        unset($_SESSION['applied_coupon_id']);
        header("Location: cart.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; // Discount can't exceed grand total
        }
    } else {
        // If conditions are no longer met, remove coupon
        unset($_SESSION['applied_coupon_id']);
        $applied_coupon = null;
    }
}
$total_due = $grand_total - $discount;

// Fetch all collected unused coupons for user
$my_coupons_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.is_used = 0
");
$my_coupons_stmt->execute([':user_id' => $_SESSION['user_id']]);
$my_coupons = $my_coupons_stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!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);
        }
        <!-- Multi-language Support -->
        <script src="lang.js"></script>
        .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 data-lang-key="vip_guest">VIP GUEST: </span><?php echo htmlspecialchars($_SESSION['username']); ?>
                <span>|</span>
                <span data-lang-key="status_label">STATUS: </span><span class="text-cyber-accent font-bold uppercase" data-lang-key="<?php echo $_SESSION['role'] === 'admin' ? 'admin_member' : 'vip_member'; ?>"><?php echo htmlspecialchars($_SESSION['role']); ?> MEMBER</span>
            </div>
            <div class="flex gap-4">
                <a href="index.php" class="text-cyber-accent hover:text-white transition font-bold tracking-widest" data-lang-key="return_to_salon">← BACK TO SALON</a>
            </div>
        </div>

        <!-- Main Header -->
        <div class="w-full px-6 md:px-12 py-4 flex items-center justify-between">
            <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 class="flex items-center gap-4">
                <!-- Language Selector -->
                <div class="flex items-center gap-1.5 bg-cyber-card border border-cyber-border px-3 py-1.5 rounded-lg shadow-sm">
                    <span class="text-xs text-stone-500">🌐</span>
                    <select id="lang-selector" class="bg-transparent text-xs text-stone-300 outline-none cursor-pointer focus:text-cyber-accent">
                        <option value="th">TH / ไทย</option>
                        <option value="en">EN / English</option>
                        <option value="zh">ZH / 中文</option>
                        <option value="ja">JA / 日本語</option>
                        <option value="ko">KO / 한국어</option>
                    </select>
                </div>
                <span class="text-[11px] font-cyber tracking-[0.25em] text-stone-400" data-lang-key="shopping_bag">// SHOPPING BAG</span>
            </div>
        </div>
    </header>

    <!-- Main Container -->
    <main class="flex-grow w-full px-6 md:px-12 py-8">
        
        <?php if (!empty($_SESSION['cart'])): ?>
            
            <div class="flex flex-col lg:flex-row gap-8 mt-4">
                
                <!-- Left: Cart Items List -->
                <div class="flex-grow space-y-4">
                    <!-- Heading Header (Desktop only) -->
                    <div class="bg-cyber-card rounded-xl p-4 border border-cyber-border hidden md:grid md:grid-cols-12 text-[10px] font-sans text-stone-400 font-semibold uppercase tracking-wider gap-4">
                        <div class="col-span-6" data-lang-key="cart_table_product">ACQUISITION // สินค้า</div>
                        <div class="col-span-2 text-center" data-lang-key="cart_table_price">PRICE // ราคา</div>
                        <div class="col-span-2 text-center" data-lang-key="cart_table_qty">QTY // จำนวน</div>
                        <div class="col-span-2 text-center" data-lang-key="cart_table_total">TOTAL // รวม</div>
                    </div>

                    <!-- Items Rows -->
                    <?php foreach ($_SESSION['cart'] as $key => $item): ?>
                        <div class="bg-cyber-card rounded-xl p-4 border border-cyber-border grid grid-cols-1 md:grid-cols-12 items-center gap-4 hover:border-cyber-accent/50 transition duration-300">
                            
                            <!-- Product Details Column -->
                            <div class="col-span-1 md:col-span-6 flex gap-4">
                                <div class="w-16 h-16 shrink-0 border border-cyber-border rounded overflow-hidden bg-black">
                                    <img src="<?php echo htmlspecialchars($item['image']); ?>" 
                                         alt="<?php echo htmlspecialchars($item['name']); ?>" 
                                         class="w-full h-full object-cover"
                                         onerror="this.src='https://images.unsplash.com/photo-1521572267360-ee0c2909d518?w=800&auto=format&fit=crop';">
                                </div>
                                <div class="flex flex-col justify-between py-0.5 min-w-0">
                                    <a href="product-detail.php?id=<?php echo $item['product_id']; ?>" 
                                       class="font-serif font-medium text-sm text-white hover:text-cyber-accent transition truncate">
                                        <?php echo htmlspecialchars($item['name']); ?>
                                    </a>
                                    <!-- Attributes -->
                                    <div class="flex flex-wrap gap-2 mt-1 text-[9px] font-sans">
                                        <span class="bg-[#0A0A0B] text-stone-400 px-2 py-0.5 rounded border border-cyber-border">
                                            SIZE: <strong class="text-white"><?php echo htmlspecialchars($item['size']); ?></strong>
                                        </span>
                                        <span class="bg-[#0A0A0B] text-stone-400 px-2 py-0.5 rounded border border-cyber-border">
                                            COLOR: <strong class="text-white"><?php echo htmlspecialchars($item['color']); ?></strong>
                                        </span>
                                    </div>
                                    
                                    <!-- Mobile view controls -->
                                    <div class="flex items-center justify-between mt-2.5 md:hidden">
                                        <span class="text-sm font-cyber font-medium text-cyber-accent">฿<?php echo number_format($item['price'], 2); ?></span>
                                        <div class="flex items-center border border-cyber-border bg-[#0A0A0B] rounded overflow-hidden">
                                            <a href="cart.php?action=update&key=<?php echo $key; ?>&qty=<?php echo $item['quantity'] - 1; ?>" class="px-2.5 py-1 text-stone-400 font-bold hover:bg-stone-900 transition text-xs select-none">-</a>
                                            <span class="px-3 font-cyber text-xs text-white font-medium"><?php echo $item['quantity']; ?></span>
                                            <a href="cart.php?action=update&key=<?php echo $key; ?>&qty=<?php echo $item['quantity'] + 1; ?>" class="px-2.5 py-1 text-stone-400 font-bold hover:bg-stone-900 transition text-xs select-none">+</a>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Unit Price (Desktop only) -->
                            <div class="col-span-2 text-center hidden md:block">
                                <span class="text-sm font-cyber font-medium text-stone-300">฿<?php echo number_format($item['price'], 2); ?></span>
                            </div>

                            <!-- Quantity Controller (Desktop only) -->
                            <div class="col-span-2 text-center hidden md:flex justify-center items-center">
                                <div class="flex border border-cyber-border bg-[#0A0A0B] rounded overflow-hidden">
                                    <a href="cart.php?action=update&key=<?php echo $key; ?>&qty=<?php echo $item['quantity'] - 1; ?>" 
                                       class="px-3 py-1 hover:bg-stone-900 text-stone-400 font-bold transition select-none text-xs">-</a>
                                    <span class="w-10 text-center py-1 text-xs font-cyber font-medium text-white"><?php echo $item['quantity']; ?></span>
                                    <a href="cart.php?action=update&key=<?php echo $key; ?>&qty=<?php echo $item['quantity'] + 1; ?>" 
                                       class="px-3 py-1 hover:bg-stone-900 text-stone-400 font-bold transition select-none text-xs">+</a>
                                </div>
                            </div>

                            <!-- Total Price & Remove Button -->
                            <div class="col-span-2 flex items-center justify-between md:justify-center gap-4">
                                <span class="text-sm font-cyber font-medium text-cyber-accent md:text-center block w-full neon-text-purple">
                                    ฿<?php echo number_format($item['price'] * $item['quantity'], 2); ?>
                                </span>
                                <a href="cart.php?action=remove&key=<?php echo $key; ?>" 
                                   class="text-cyber-danger hover:text-white transition p-2 bg-[#2D1B1B]/40 border border-cyber-danger/30 rounded"
                                   title="ลบรายการสินค้า"
                                   onclick="return confirmDelete(event)">
                                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
                                    </svg>
                                </a>
                            </div>

                        </div>
                    <?php endforeach; ?>
                </div>

                <!-- Right: Summary checkout card -->
                <aside class="w-full lg:w-1/3 shrink-0">
                    <div class="bg-cyber-card rounded-xl p-6 border border-cyber-border space-y-6 sticky top-28 shadow-lg">
                        <h3 class="font-cyber font-medium text-xs text-white border-b border-cyber-border pb-3 tracking-[0.15em] uppercase" data-lang-key="checkout_summary">ACQUISITION SUMMARY // สรุปรายการสั่งซื้อ</h3>
                        
                        <!-- Coupon success/error alerts -->
                        <?php if (isset($_SESSION['coupon_success'])): ?>
                            <div class="p-3 bg-[#1E221F] border border-cyber-success text-cyber-success rounded text-[11px] font-sans flex items-center justify-between">
                                <span><?php echo $_SESSION['coupon_success']; ?></span>
                                <button type="button" onclick="this.parentElement.remove()" class="text-cyber-success hover:text-white font-bold ml-2">✕</button>
                            </div>
                            <?php unset($_SESSION['coupon_success']); ?>
                        <?php endif; ?>
                        <?php if (isset($_SESSION['coupon_error'])): ?>
                            <div class="p-3 bg-[#2D1B1B] border border-cyber-danger text-cyber-danger rounded text-[11px] font-sans flex items-center justify-between">
                                <span><?php echo $_SESSION['coupon_error']; ?></span>
                                <button type="button" onclick="this.parentElement.remove()" class="text-cyber-danger hover:text-white font-bold ml-2">✕</button>
                            </div>
                            <?php unset($_SESSION['coupon_error']); ?>
                        <?php endif; ?>

                        <div class="space-y-3.5 text-xs font-sans text-stone-400">
                            <div class="flex justify-between">
                                <span data-lang-key="cart_table_qty">จำนวนรายการรวม:</span>
                                <span class="font-semibold text-white"><?php echo $cart_count; ?> <span data-lang-key="piece_unit">ชิ้น</span></span>
                            </div>
                            <div class="flex justify-between">
                                <span data-lang-key="subtotal_label">ยอดมูลค่าสินค้ารวม:</span>
                                <span class="font-semibold text-white">฿<?php echo number_format($grand_total, 2); ?></span>
                            </div>
                            <?php if ($discount > 0): ?>
                                <div class="flex justify-between text-cyber-success">
                                    <span data-lang-key="discount_label">ส่วนลดคูปอง 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 data-lang-key="form_payment_method">บริการจัดส่งพัสดุ:</span>
                                <span class="text-cyber-success font-semibold tracking-wider" data-lang-key="banner_exclusivite">COMPLIMENTARY</span>
                            </div>
                        </div>

                        <!-- Apply Coupon Section -->
                        <div class="pt-4 border-t border-cyber-border/40">
                            <label class="text-[9px] font-sans tracking-widest uppercase text-cyber-accent font-semibold block mb-2" data-lang-key="apply_coupon_title">🎟 สิทธิพิเศษคูปองส่วนลด VIP ของท่าน</label>
                            <?php if ($discount > 0): ?>
                                <div class="bg-[#0A0A0B] border border-cyber-success/30 rounded p-3 flex items-center justify-between">
                                    <div class="text-[11px] font-sans">
                                        <p class="font-semibold text-white"><?php echo htmlspecialchars($applied_coupon['code']); ?></p>
                                        <p class="text-[9px] text-stone-400">ลดทันที ฿<?php echo number_format($discount, 2); ?></p>
                                    </div>
                                    <form action="cart.php" method="POST">
                                        <input type="hidden" name="action" value="remove_coupon">
                                        <button type="submit" class="text-cyber-danger hover:text-white text-[10px] font-semibold border border-cyber-danger/30 hover:border-cyber-danger bg-[#2D1B1B]/40 px-2.5 py-1 rounded transition">ยกเลิก</button>
                                    </form>
                                </div>
                            <?php else: ?>
                                <?php if (!empty($my_coupons)): ?>
                                    <form action="cart.php" method="POST" class="flex gap-2">
                                        <input type="hidden" name="action" value="apply_coupon">
                                        <select name="coupon_id" required class="flex-grow bg-[#0A0A0B] border border-cyber-border rounded px-2 py-1.5 text-[11px] text-white outline-none focus:border-cyber-accent">
                                            <option value="" data-lang-key="no_coupon_option">-- เลือกคูปอง VIP ของคุณ --</option>
                                            <?php foreach ($my_coupons as $cp): ?>
                                                <?php 
                                                    $eligible = $grand_total >= $cp['min_order_value'];
                                                    $opt_text = $cp['code'] . " (" . ($cp['discount_type'] === 'percent' ? $cp['discount_value']."%" : "฿".$cp['discount_value']) . " Off - ขั้นต่ำ ฿" . number_format($cp['min_order_value']) . ")";
                                                ?>
                                                <option value="<?php echo $cp['id']; ?>" <?php echo !$eligible ? 'disabled class="text-stone-600"' : 'class="text-white bg-[#121215]"'; ?>>
                                                    <?php echo htmlspecialchars($opt_text); ?> <?php echo !$eligible ? '❌ ยอดไม่ถึง' : '⚜️ ใช้ได้'; ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                        <button type="submit" class="bg-cyber-accent hover:bg-cyber-accentGlow text-black px-3 py-1.5 rounded text-[11px] font-cyber font-semibold tracking-wider transition">APPLY</button>
                                    </form>
                                <?php else: ?>
                                    <p class="text-[10px] text-stone-500 font-sans">// ยังไม่มีคูปองที่สะสมไว้ <a href="index.php" class="text-cyber-accent hover:underline">ไปเก็บคูปอง VIP ที่นี่</a></p>
                                <?php endif; ?>
                            <?php endif; ?>
                        </div>

                        <!-- Grand Total display -->
                        <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-2xl font-cyber font-medium text-cyber-accent neon-text-purple">
                                ฿<?php echo number_format($total_due, 2); ?>
                            </span>
                        </div>

                        <!-- CTA buttons -->
                        <div class="space-y-3 pt-2 text-xs">
                            <a href="checkout.php" 
                               data-lang-key="btn_proceed_checkout"
                               class="block w-full bg-cyber-accent hover:bg-cyber-accentGlow text-black text-center font-cyber font-semibold tracking-[0.15em] py-3.5 rounded transition uppercase">
                                PROCEED TO ACQUISITION
                            </a>
                            <a href="index.php" 
                               data-lang-key="return_to_salon"
                               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">
                                RETURN TO SALON
                            </a>
                        </div>
                    </div>
                </aside>

            </div>

        <?php else: ?>
            
            <!-- Empty Cart UI -->
            <div class="bg-cyber-card rounded-2xl border border-cyber-border p-16 text-center max-w-2xl mx-auto mt-12 shadow-2xl relative overflow-hidden">
                <div class="absolute -top-10 -right-10 w-24 h-24 bg-cyber-accent/10 rounded-full blur-2xl"></div>
                
                <div class="bg-amber-950/40 w-20 h-20 rounded-full border border-cyber-accent/30 flex items-center justify-center mx-auto mb-6 text-cyber-accent 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="M16 11V7a4 4 0 00-8 0v4M5 9h14l1 12H4L5 9z"></path>
                    </svg>
                </div>
                <h2 class="font-cyber font-medium text-lg text-white tracking-[0.2em] uppercase" data-lang-key="cart_empty">NO SELECTIONS IN BAG</h2>
                <p class="text-xs text-stone-400 mt-3.5 max-w-sm mx-auto leading-relaxed font-sans" data-lang-key="cart_empty">
                    คุณยังไม่ได้เลือกสรรสินค้าลงในถุงช้อปปิ้งของท่านในเซสชันนี้ ร่วมเปิดประสบการณ์และเลือกชมผลงานชิ้นเอกของเรา
                </p>
                <a href="index.php" class="inline-block mt-6 bg-cyber-accent hover:bg-cyber-accentGlow text-black font-cyber font-semibold tracking-[0.15em] px-8 py-3.5 rounded transition text-xs uppercase" data-lang-key="return_to_salon">
                    EXPLORE COLLECTIONS
                </a>
            </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 data-lang-key="footer_rights">⚜️ <span class="font-cyber tracking-[0.25em] text-white">NON LUXURY</span> // CONCIERGE SERVICES. สงวนลิขสิทธิ์</p>
                <p class="text-[10px] text-stone-600 mt-1" data-lang-key="footer_port">ระบบฐานข้อมูล PDO MySQL // รหัสพอร์ต 014</p>
            </div>
            <div class="text-right">
                <p data-lang-key="footer_developer">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. All rights reserved.</p>
            </div>
        </div>
    </footer>
    <script>
        function confirmDelete(e) {
            e.preventDefault();
            const currentLang = localStorage.getItem("selected_lang") || "th";
            const msgs = {
                th: "ต้องการนำสินค้าออกจากถุงช้อปปิ้งใช่หรือไม่?",
                en: "Are you sure you want to remove this item from your shopping bag?",
                zh: "您确定要将此商品从购物袋中移除吗？",
                ja: "この商品をショッピングバッグから削除してもよろしいですか？",
                ko: "이 상품을 장바구니 쇼핑백에서 삭제하시겠습니까?"
            };
            const msg = msgs[currentLang] || msgs['th'];
            if (confirm(msg)) {
                window.location.href = e.currentTarget.href;
            }
        }
    </script>

</body>
</html>
