<?php
require_once __DIR__ . '/config/db.php';
require_once __DIR__ . '/helpers/jwt_helper.php';
require_once __DIR__ . '/helpers/auth.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (!isset($_SESSION['cart'])) {
    $_SESSION['cart'] = [];
}

$currentUser = get_current_user_data();
$error = '';
$success = '';

// จัดการการลบสินค้าออกจากตะกร้า (ตามคีย์ผสม id_size)
if (isset($_GET['action']) && $_GET['action'] === 'remove') {
    $remove_key = trim($_GET['key'] ?? '');
    if (!empty($remove_key)) {
        unset($_SESSION['cart'][$remove_key]);
        header("Location: cart.php");
        exit();
    }
}

// จัดการการใช้งานโค้ดส่วนลด (Coupon Code)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['apply_coupon'])) {
    $coupon_code = strtoupper(trim($_POST['coupon_code'] ?? ''));
    if ($coupon_code === 'CYBER10') {
        $_SESSION['coupon'] = [
            'code' => 'CYBER10',
            'discount_percent' => 10
        ];
        $success = 'ใช้งานโค้ดส่วนลด CYBER10 สำเร็จ! รับส่วนลด 10%';
    } else if (!empty($coupon_code)) {
        $error = 'โค้ดส่วนลด "' . htmlspecialchars($coupon_code) . '" ไม่ถูกต้อง หรือหมดอายุแล้ว';
    } else {
        $error = 'กรุณากรอกโค้ดส่วนลด';
    }
}

// จัดการการยกเลิกโค้ดส่วนลด
if (isset($_GET['action']) && $_GET['action'] === 'remove_coupon') {
    unset($_SESSION['coupon']);
    header("Location: cart.php");
    exit();
}

// จัดการการอัปเดตจำนวนสินค้าค้างตะกร้า
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_cart'])) {
    $cart_key = trim($_POST['cart_key'] ?? '');
    $qty = (int)$_POST['quantity'];

    if (!empty($cart_key) && $qty > 0) {
        // แยกค่า ID และ Size ออกจากคีย์
        list($product_id, $size) = explode('_', $cart_key);
        
        // ตรวจสอบสต็อกในระบบ
        $stmt = $pdo->prepare("SELECT stock FROM products WHERE id = ?");
        $stmt->execute([$product_id]);
        $prod = $stmt->fetch();

        if ($prod) {
            if ($qty <= $prod['stock']) {
                $_SESSION['cart'][$cart_key] = $qty;
                $success = 'อัปเดตจำนวนสินค้าในตะกร้าสำเร็จ';
            } else {
                $_SESSION['cart'][$cart_key] = $prod['stock'];
                $error = 'ไม่สามารถสั่งเกินสต็อกที่มีอยู่ได้ (ปรับเป็นจำนวนสูงสุดแล้ว)';
            }
        }
    }
}

// ดึงรายละเอียดของสินค้าทั้งหมดที่อยู่ในตะกร้า
$cart_products_details = [];
$total_credits = 0;

if (!empty($_SESSION['cart'])) {
    // หา IDs ของสินค้าทั้งหมดในตะกร้า
    $product_ids = array_unique(array_map(function($key) {
        return (int)explode('_', $key)[0];
    }, array_keys($_SESSION['cart'])));

    if (!empty($product_ids)) {
        $placeholders = implode(',', array_fill(0, count($product_ids), '?'));
        $stmt = $pdo->prepare("SELECT * FROM products WHERE id IN ($placeholders)");
        $stmt->execute($product_ids);
        $db_products = $stmt->fetchAll();

        // แมปข้อมูลสินค้ากลับเพื่อให้ดึงง่ายขึ้น
        $products_map = [];
        foreach ($db_products as $p) {
            $products_map[$p['id']] = $p;
        }

        // จัดเตรียมรายการสินค้าที่จะนำมาเรนเดอร์ในตะกร้า
        foreach ($_SESSION['cart'] as $key => $qty) {
            list($product_id, $size) = explode('_', $key);
            if (isset($products_map[$product_id])) {
                $prod = $products_map[$product_id];
                $subtotal = $prod['price'] * $qty;
                $total_credits += $subtotal;
                
                $cart_products_details[] = [
                    'key' => $key,
                    'product_id' => $product_id,
                    'name' => $prod['name'],
                    'size' => $size,
                    'price' => $prod['price'],
                    'image_url' => $prod['image_url'],
                    'stock' => $prod['stock'],
                    'quantity' => $qty,
                    'subtotal' => $subtotal
                ];
            }
        }
    }
}

$discount_amount = 0;
$mega_deal_discount = 0;
$mega_deal_applied = false;

// อัตโนมัติ: ซื้อครบ 2000 บาท ลด 67% ทันที
$MEGA_DEAL_THRESHOLD = 2000;
$MEGA_DEAL_PERCENT  = 67;

if ($total_credits >= $MEGA_DEAL_THRESHOLD) {
    $mega_deal_discount = $total_credits * ($MEGA_DEAL_PERCENT / 100);
    $mega_deal_applied = true;
}

// หัก MEGA DEAL ก่อน
$after_mega = max(0, $total_credits - $mega_deal_discount);

// คำนวณส่วนลดสมาชิกอัตโนมัติ 10% หรือโค้ดส่วนลดที่กรอก
$member_disc_pct = get_member_discount_percent();
$coupon_disc_pct = !empty($_SESSION['coupon']['discount_percent']) ? $_SESSION['coupon']['discount_percent'] : 0;
$total_disc_pct = max($member_disc_pct, $coupon_disc_pct);

$discount_label = '';
if ($total_disc_pct > 0) {
    if ($member_disc_pct >= $coupon_disc_pct && $member_disc_pct > 0) {
        $discount_label = '🛡️ ส่วนลดสมาชิก CYBERMEMBER (-' . $member_disc_pct . '%)';
    } else {
        $discount_label = '🏷️ โค้ด ' . htmlspecialchars($_SESSION['coupon']['code'] ?? '') . ' (-' . $coupon_disc_pct . '%)';
    }
    $discount_amount = $after_mega * ($total_disc_pct / 100);
}
$grand_total = max(0, $after_mega - $discount_amount);

$cart_count = array_sum($_SESSION['cart']);
$remaining_for_mega = max(0, $MEGA_DEAL_THRESHOLD - $total_credits);
$progress_pct = min(100, ($total_credits / $MEGA_DEAL_THRESHOLD) * 100);
?>
<!DOCTYPE html>
<html lang="th">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CyberGear // ตะกร้าสินค้าของคุณ</title>
    <link rel="stylesheet" href="assets/css/style.css">
</head>
<body>

    <nav class="navbar">
        <a href="index.php" class="navbar-brand">
            CYBER<span class="brand-red">SHOP</span>
        </a>
        <div class="navbar-menu">
            <a href="index.php" class="nav-link">หน้าร้านค้า</a>
            <a href="cart.php" class="nav-link active" style="color: var(--text-white);">
                ตะกร้าสินค้า 
                <span style="background: var(--neon-red); color: #fff; padding: 2px 7px; border-radius: 50%; font-size: 0.75rem; font-family: 'Orbitron', sans-serif; margin-left: 4px;">
                    <?php echo $cart_count; ?>
                </span>
            </a>

            <!-- ช่องใส่โค้ดส่วนลดใน Navbar -->
            <div style="margin-left: 0.5rem; display: flex; align-items: center;">
                <?php if (!empty($_SESSION['coupon']['code'])): ?>
                    <div style="background: rgba(0, 240, 255, 0.1); border: 1px solid var(--neon-cyan); padding: 0.3rem 0.6rem; border-radius: 6px; display: flex; align-items: center; gap: 6px; font-size: 0.8rem; box-shadow: 0 0 10px rgba(0, 240, 255, 0.2);">
                        <span style="color: var(--neon-cyan); font-family: 'Orbitron', sans-serif; font-weight: bold;">🏷️ <?php echo htmlspecialchars($_SESSION['coupon']['code']); ?> (-10%)</span>
                        <a href="?action=remove_nav_coupon" style="color: var(--neon-red); text-decoration: none; font-weight: bold; margin-left: 2px;" title="ยกเลิกโค้ด">✕</a>
                    </div>
                <?php else: ?>
                    <form action="" method="POST" style="display: flex; gap: 0.3rem; align-items: center;">
                        <input class="cyber-input" type="text" name="coupon_code" placeholder="🎟️ โค้ดลด 10%" style="padding: 0.35rem 0.6rem; font-size: 0.8rem; width: 120px; text-transform: uppercase; font-family: 'Orbitron', sans-serif; border-color: rgba(0, 240, 255, 0.5); color: var(--neon-cyan);">
                        <button type="submit" name="apply_nav_coupon" class="btn-cyber" style="padding: 0.35rem 0.65rem; font-size: 0.75rem; border-color: var(--neon-cyan); color: var(--neon-cyan); background: rgba(0, 240, 255, 0.1); white-space: nowrap;">ใช้โค้ด</button>
                    </form>
                <?php endif; ?>
            </div>
            <?php if ($currentUser): ?>
                <span style="font-size: 0.95rem; margin-left: 1rem; padding-left: 1rem; border-left: 1px solid var(--border-color);">
                    ลูกค้า: <span class="brand-red" style="font-weight: bold;"><?php echo htmlspecialchars($currentUser['username']); ?></span>
                </span>
                <a href="logout.php" class="btn-cyber" style="padding: 0.4rem 0.8rem; font-size: 0.75rem; border-color: var(--text-gray); margin-left: 1rem;">ออกระบบ</a>
            <?php else: ?>
                <a href="login.php" class="btn-cyber" style="padding: 0.4rem 1rem; font-size: 0.8rem; margin-left: 1rem;">เข้าสู่ระบบ</a>
            <?php endif; ?>
        </div>
    </nav>

    <div class="container" style="margin-top: 3rem;">
        
        <h1 style="font-size: 2.2rem; text-shadow: 0 0 10px var(--glow-red); margin-bottom: 2rem;">ตะกร้าสินค้าของคุณ</h1>

        <?php if ($error): ?>
            <div class="cyber-alert cyber-alert-error">
                <strong>[เกิดข้อผิดพลาด]</strong> <?php echo htmlspecialchars($error); ?>
            </div>
        <?php endif; ?>

        <?php if ($success): ?>
            <div class="cyber-alert cyber-alert-success">
                <strong>[สำเร็จ]</strong> <?php echo htmlspecialchars($success); ?>
            </div>
        <?php endif; ?>

        <div style="display: grid; grid-template-columns: 2fr 1fr; gap: 2rem;">
            
            <!-- ตารางรายการสินค้าในตะกร้า -->
            <div class="cyber-card">
                <h3 style="margin-bottom: 1.5rem; text-transform: uppercase;">&gt;_ รายการเสื้อผ้าสั่งซื้อ</h3>
                
                <?php if (empty($cart_products_details)): ?>
                    <div style="text-align: center; padding: 3rem 0; color: var(--text-muted);">
                        <p>ไม่มีสินค้าอยู่ในตะกร้าของคุณขณะนี้</p>
                        <a href="index.php" class="btn-cyber" style="margin-top: 1.5rem;">กลับไปเลือกซื้อสินค้า</a>
                    </div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="cyber-table">
                            <thead>
                                <tr>
                                    <th>สินค้า / ไซส์</th>
                                    <th>ราคา</th>
                                    <th style="width: 130px;">จำนวน</th>
                                    <th>รวม</th>
                                    <th style="text-align: right;">การจัดการ</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($cart_products_details as $item): ?>
                                    <tr>
                                        <td>
                                            <div style="display: flex; gap: 1rem; align-items: center;">
                                                <?php if ($item['image_url']): ?>
                                                    <img src="<?php echo htmlspecialchars($item['image_url']); ?>" alt="img" style="width: 45px; height: 55px; object-fit: cover; border-radius: 6px; border: 1px solid var(--border-color);">
                                                <?php endif; ?>
                                                <div>
                                                    <strong style="color:var(--text-white);"><?php echo htmlspecialchars($item['name']); ?></strong>
                                                    <div style="font-size:0.85rem; color: var(--neon-red); font-weight: bold; margin-top: 2px;">
                                                        ไซส์เสื้อผ้า: [ <?php echo htmlspecialchars($item['size']); ?> ]
                                                    </div>
                                                </div>
                                            </div>
                                        </td>
                                        <td>฿<?php echo number_format($item['price'], 2); ?></td>
                                        <td>
                                            <form action="cart.php" method="POST" style="display: flex; gap: 0.3rem;">
                                                <input type="hidden" name="cart_key" value="<?php echo htmlspecialchars($item['key']); ?>">
                                                <input class="cyber-input" type="number" name="quantity" value="<?php echo $item['quantity']; ?>" min="1" max="<?php echo $item['stock']; ?>" style="padding: 0.3rem 0.5rem; width: 55px; text-align: center; font-size: 0.95rem;">
                                                <button type="submit" name="update_cart" class="btn-cyber" style="padding: 0.3rem 0.5rem; border-color: var(--text-gray); box-shadow: none;" title="บันทึกจำนวน">✔</button>
                                            </form>
                                        </td>
                                        <td>฿<?php echo number_format($item['subtotal'], 2); ?></td>
                                        <td style="text-align: right;">
                                            <a href="cart.php?action=remove&key=<?php echo urlencode($item['key']); ?>" style="color: var(--neon-red); text-decoration: none; font-size: 0.9rem;" onclick="return confirm('นำสินค้าชิ้นนี้ออก?');">นำออก</a>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>

            <!-- กล่องรวมยอดชำระและชำระเงิน -->
            <?php if (!empty($cart_products_details)): ?>
                <div class="cyber-card" style="height: fit-content; display: flex; flex-direction: column; justify-content: space-between;">
                    <div>
                        <h3 style="margin-bottom: 1.5rem; text-transform: uppercase;">สรุปยอดรายการสั่งซื้อ</h3>
                        
                        <!-- ฟอร์มใส่โค้ดส่วนลด -->
                        <form action="cart.php" method="POST" style="margin-bottom: 1.2rem; background: rgba(0, 0, 0, 0.3); padding: 1rem; border-radius: 8px; border: 1px dashed var(--border-color);">
                            <label style="font-size: 0.8rem; color: var(--neon-cyan); display: block; margin-bottom: 0.5rem; font-weight: bold; letter-spacing: 1px;">
                                🏷️ โค้ดส่วนลด (PROMO CODE)
                            </label>
                            <div style="display: flex; gap: 0.5rem;">
                                <input type="text" name="coupon_code" class="cyber-input" placeholder="ใส่โค้ด เช่น CYBER10" value="<?php echo htmlspecialchars($_SESSION['coupon']['code'] ?? ''); ?>" style="padding: 0.4rem 0.8rem; text-transform: uppercase; font-family: 'Orbitron', sans-serif; font-size: 0.85rem; flex-grow: 1;">
                                <button type="submit" name="apply_coupon" class="btn-cyber" style="padding: 0.4rem 0.8rem; font-size: 0.8rem; white-space: nowrap; border-color: var(--neon-cyan); color: var(--neon-cyan);">ใช้โค้ด</button>
                            </div>
                        </form>

                        <!-- Progress bar MEGA DEAL -->
                        <?php if (!$mega_deal_applied): ?>
                        <div style="background: rgba(255,140,0,0.07); border: 1px solid rgba(255,140,0,0.3); border-radius: 8px; padding: 0.8rem; margin-bottom: 1.2rem;">
                            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px;">
                                <span style="font-size: 0.78rem; color: #ffa500; font-weight: bold;">💰 อีกเพียง ฿<?php echo number_format($remaining_for_mega, 2); ?> รับส่วนลด 67%!</span>
                                <span style="font-size: 0.75rem; color: #888;">฿<?php echo number_format($total_credits, 0); ?>/2,000</span>
                            </div>
                            <div style="background: rgba(0,0,0,0.4); border-radius: 20px; height: 8px; overflow: hidden;">
                                <div style="background: linear-gradient(90deg, #ff8c00, #ffd700); height: 100%; width: <?php echo $progress_pct; ?>%; border-radius: 20px; transition: width 0.5s ease; box-shadow: 0 0 8px rgba(255,180,0,0.5);"></div>
                            </div>
                        </div>
                        <?php else: ?>
                        <div style="background: linear-gradient(90deg, rgba(255,140,0,0.15), rgba(255,215,0,0.1)); border: 1.5px solid #ffd700; border-radius: 8px; padding: 0.75rem 1rem; margin-bottom: 1.2rem; display: flex; align-items: center; gap: 10px;">
                            <span style="font-size: 1.3rem;">🏆</span>
                            <div>
                                <div style="font-size: 0.8rem; font-weight: bold; color: #ffd700; font-family: 'Orbitron', sans-serif;">MEGA DEAL ปลดล็อกแล้ว!</div>
                                <div style="font-size: 0.75rem; color: #ffa500;">คุณได้รับส่วนลดสูงสุด 67% อัตโนมัติ!</div>
                            </div>
                        </div>
                        <?php endif; ?>

                        <div style="border-bottom: 1px dashed var(--border-color); padding-bottom: 1rem; margin-bottom: 1rem;">
                            <div style="display: flex; justify-content: space-between; margin-bottom: 0.5rem;">
                                <span>จำนวนรวมทั้งหมด:</span>
                                <span style="font-family: 'Orbitron', sans-serif;"><?php echo $cart_count; ?> ชิ้น</span>
                            </div>
                            <div style="display: flex; justify-content: space-between; margin-bottom: 0.5rem;">
                                <span>ยอดรวมก่อนส่วนลด:</span>
                                <span style="font-family: 'Orbitron', sans-serif;">฿<?php echo number_format($total_credits, 2); ?></span>
                            </div>
                            <?php if ($mega_deal_applied): ?>
                                <div style="display: flex; justify-content: space-between; margin-bottom: 0.5rem; color: #ffd700;">
                                    <span>⚡ MEGA DEAL ซื้อครบ ฿2,000 ลด 67%:</span>
                                    <span style="font-family: 'Orbitron', sans-serif; font-weight: bold;">-฿<?php echo number_format($mega_deal_discount, 2); ?></span>
                                </div>
                            <?php endif; ?>
                            <?php if ($discount_amount > 0): ?>
                                <div style="display: flex; justify-content: space-between; margin-bottom: 0.5rem; color: var(--neon-green);">
                                    <span><?php echo $discount_label; ?>: <?php if (!empty($_SESSION['coupon']['code'])): ?><a href="cart.php?action=remove_coupon" style="color: var(--neon-red); font-size: 0.75rem; text-decoration: underline; margin-left: 4px;">[ยกเลิกโค้ด]</a><?php endif; ?></span>
                                    <span style="font-family: 'Orbitron', sans-serif; font-weight: bold;">-฿<?php echo number_format($discount_amount, 2); ?></span>
                                </div>
                            <?php endif; ?>
                        </div>

                        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 2rem;">
                            <span style="font-weight: bold; color: var(--text-white);">ราคารวมสุทธิ:</span>
                            <span class="product-price" style="font-size: 1.8rem; margin: 0; color: var(--neon-green); text-shadow: 0 0 10px var(--glow-green);">฿<?php echo number_format($grand_total, 2); ?></span>
                        </div>
                        
                        <?php if ($currentUser): ?>
                            <a href="checkout.php" class="btn-cyber btn-green" style="width: 100%; text-align: center;">
                                ดำเนินการสั่งซื้อสินค้า &raquo;
                            </a>
                        <?php else: ?>
                            <div style="text-align: center;">
                                <p style="font-size: 0.85rem; color: var(--neon-red); margin-bottom: 1rem;">กรุณาเข้าสู่ระบบเพื่อดำเนินการสั่งซื้อ</p>
                                <a href="login.php" class="btn-cyber" style="width: 100%;">
                                    เข้าสู่ระบบความปลอดภัย
                                </a>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endif; ?>

        </div>

    </div>

</body>
</html>
