<?php
// product_detail.php
require_once 'config.php';

// Get Product ID from URL
$productId = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);

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

// Fetch Product and Shop details from SQLite
$product = null;
try {
    $stmt = $pdo->prepare("SELECT products.*, shops.name as shop_name 
                           FROM products 
                           LEFT JOIN shops ON products.shop_id = shops.id 
                           WHERE products.id = ?");
    $stmt->execute([$productId]);
    $product = $stmt->fetch();
} catch (PDOException $e) {
    $product = null;
}

// Fallback to session products if not found in db query
if (!$product && isset($_SESSION['clothing_products'])) {
    foreach ($_SESSION['clothing_products'] as $p) {
        if ($p['id'] == $productId) {
            $product = $p;
            $product['name'] = $p['name_th'];
            $product['shop_name'] = 'NoaShop';
            break;
        }
    }
}

if (!$product) {
    die("ไม่พบสินค้าที่คุณต้องการ");
}

// Parse gallery images
$galleryImages = [];
if (!empty($product['gallery_images'])) {
    $decoded = json_decode($product['gallery_images'], true);
    if (is_array($decoded) && count($decoded) > 0) {
        $galleryImages = $decoded;
    }
}
if (empty($galleryImages)) {
    $galleryImages = [
        $product['image'],
        $product['image'],
        $product['image']
    ];
}

// Parse sizes & colors
$sizes = [];
if (!empty($product['sizes'])) {
    if (is_array($product['sizes'])) {
        $sizes = $product['sizes'];
    } else {
        $sizes = array_filter(array_map('trim', explode(',', $product['sizes'])));
    }
}
if (empty($sizes)) {
    $sizes = ['S', 'M', 'L', 'XL'];
}

$colors = [];
if ($lang === 'en' && !empty($product['colors_en'])) {
    $colors = is_array($product['colors_en']) ? $product['colors_en'] : array_filter(array_map('trim', explode(',', $product['colors_en'])));
} else if (!empty($product['colors_th'])) {
    $colors = is_array($product['colors_th']) ? $product['colors_th'] : array_filter(array_map('trim', explode(',', $product['colors_th'])));
}
if (empty($colors)) {
    $colors = ['ดำ', 'สีกรมท่า', 'เทา', 'ขาว'];
}

// SKU and Pricing
$sku = $product['product_code'] ?? ('MTSZD' . (7330 + $product['id']) . 'XL');
$currentPrice = (float)$product['price'];
$originalPrice = (float)($product['original_price'] ?? ($currentPrice * 1.8));

// Handle Add to Cart or Buy Now actions
$message = "";
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? 'buy_now';
    $qty = filter_input(INPUT_POST, 'quantity', FILTER_VALIDATE_INT) ?? 1;
    $selectedSize = trim($_POST['selected_size'] ?? $sizes[count($sizes) - 1]);
    $selectedColor = trim($_POST['selected_color'] ?? $colors[0]);

    if ($qty < 1) { $qty = 1; }

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

    $cart_key = $product['id'] . '_' . $selectedSize . '_' . $selectedColor;

    $_SESSION['cart'][$cart_key] = [
        'id' => $product['id'],
        'name' => $product['name'] ?? ($product['name_th'] ?? ''),
        'name_th' => $product['name_th'] ?? $product['name'],
        'name_en' => $product['name_en'] ?? $product['name'],
        'price' => $currentPrice,
        'image' => $product['image'],
        'shop_name' => $product['shop_name'] ?? 'NoaShop',
        'shop_id' => $product['shop_id'] ?? 1,
        'size' => $selectedSize,
        'color' => $selectedColor,
        'qty' => $qty,
        'quantity' => $qty
    ];

    if ($action === 'buy_now') {
        header("Location: checkout.php");
        exit;
    } else {
        $message = "เพิ่มสินค้าลงในตะกร้าเรียบร้อยแล้ว!";
    }
}

// Calculate cart count
$cartCount = 0;
if (isset($_SESSION['cart'])) {
    foreach ($_SESSION['cart'] as $item) {
        $cartCount += $item['qty'] ?? ($item['quantity'] ?? 1);
    }
}
?>
<!DOCTYPE html>
<html lang="th" class="<?= ($theme == 'dark') ? 'dark' : '' ?> scroll-smooth">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= htmlspecialchars($product['name']) ?> - NoaShop</title>
    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            darkMode: 'class'
        }
    </script>
    <link href="https://fonts.googleapis.com/css2?family=Sarabun:wght@400;500;600;700;800&family=Plus+Jakarta+Sans:wght@500;600;700;800&display=swap" rel="stylesheet">
    <style>
        body { font-family: 'Sarabun', 'Plus Jakarta Sans', sans-serif; }
        .thumb-active {
            border: 2px solid #eab308 !important;
            opacity: 1 !important;
        }
        .size-btn-active {
            background-color: #000000 !important;
            color: #ffffff !important;
            border-color: #000000 !important;
        }
        .dark .size-btn-active {
            background-color: #ffffff !important;
            color: #000000 !important;
            border-color: #ffffff !important;
        }
        .color-swatch-active {
            border: 2px solid #000000 !important;
        }
        /* LOGIN BUTTON ALWAYS VISIBLE */
        .btn-login {
            background-color: #f59e0b !important;
            color: #000000 !important;
            font-weight: 800 !important;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        .btn-login * {
            color: #000000 !important;
        }
        
        button.text-black {
            color: #000000 !important;
        }

        <?php if ($theme == 'light'): ?>
        /* FORCE SOLID BLACK TEXT IN LIGHT MODE */
        body {
            background-color: #ffffff !important;
            color: #000000 !important;
        }
        p, span, h1, h2, h3, h4, h5, h6, a, label, input, button:not(.size-btn-active):not(.text-red-600), td, th, div {
            color: #000000 !important;
        }
        .text-slate-400, .text-slate-500, .text-slate-600, .text-slate-700, .text-neutral-400, .text-neutral-500 {
            color: #000000 !important;
        }
        .text-red-600, .text-red-500 { color: #dc2626 !important; }
        .text-amber-500, .text-amber-600 { color: #d97706 !important; }
        .bg-black, .bg-slate-900 { background-color: #000000 !important; color: #ffffff !important; }
        .bg-black *, .bg-slate-900 * { color: #ffffff !important; }
        .bg-\[\#ffcc00\], .bg-amber-400 { background-color: #ffcc00 !important; color: #000000 !important; }
        .bg-\[\#ffcc00\] * { color: #000000 !important; }
        <?php else: ?>
        /* HIGH CONTRAST BRIGHT TEXT IN DARK MODE */
        body {
            background-color: #0a0a0a !important;
            color: #ffffff !important;
        }
        p, span, h1, h2, h3, h4, h5, h6, a, label, input, button:not(.size-btn-active):not(.text-red-600), td, th, div {
            color: #ffffff !important;
        }
        .text-slate-400, .text-neutral-400, .text-neutral-500 { color: #cbd5e1 !important; }
        .text-red-600, .text-red-500 { color: #ef4444 !important; }
        .text-amber-500, .text-amber-600 { color: #f59e0b !important; }
        <?php endif; ?>
    </style>
</head>
<body class="min-h-screen antialiased flex flex-col justify-between transition-colors">

    <!-- NAVIGATION HEADER -->
    <header class="border-b border-slate-300 dark:border-neutral-800 py-3.5 px-6 md:px-12 flex items-center justify-between">
        <a href="index.php" class="text-xl font-black tracking-tight flex items-center gap-2">
            <span>NoaShop</span>
        </a>

        <div class="flex items-center gap-6 text-xs font-bold">
            <a href="index.php" class="hover:text-amber-600 transition font-bold"><?= ($lang == 'th') ? 'หน้าแรก' : 'Home' ?></a>
            <a href="checkout.php" class="relative flex items-center gap-1.5 hover:text-amber-600 transition font-bold">
                🛒 <?= ($lang == 'th') ? 'ตะกร้าสินค้า' : 'Cart' ?>
                <?php if ($cartCount > 0): ?>
                    <span class="bg-amber-600 text-white rounded-full text-[10px] px-2 py-0.5 font-bold">
                        <?= $cartCount ?>
                    </span>
                <?php endif; ?>
            </a>
        </div>
    </header>

    <?php if ($message): ?>
        <div class="max-w-6xl mx-auto px-6 mt-4">
            <div class="bg-emerald-900 text-white border border-emerald-700 text-xs px-4 py-3 rounded-xl text-center font-bold">
                <?= $message ?>
            </div>
        </div>
    <?php endif; ?>

    <!-- MAIN PRODUCT CONTAINER -->
    <main class="max-w-6xl mx-auto px-4 sm:px-6 py-6 md:py-10 w-full flex-grow">
        
        <!-- BREADCRUMB HEADER (SOLID BLACK IN LIGHT MODE) -->
        <div class="text-xs mb-6 flex items-center gap-1.5 font-bold">
            <a href="index.php" class="hover:underline">NoaShop</a>
            <span>/</span>
            <span class="line-clamp-1 font-bold"><?= htmlspecialchars($product['name']) ?></span>
        </div>

        <form method="POST" action="product_detail.php?id=<?= $product['id'] ?>" id="productForm">
            
            <div class="grid grid-cols-1 lg:grid-cols-12 gap-8 items-start">
                
                <!-- LEFT SIDE: VERTICAL THUMBNAILS & MAIN IMAGE (7 COLUMNS) -->
                <div class="lg:col-span-7 flex flex-col-reverse sm:flex-row gap-4">
                    
                    <!-- 3 VERTICAL THUMBNAILS STACKED (FAR LEFT) -->
                    <div class="flex sm:flex-col gap-3 overflow-x-auto sm:overflow-y-auto sm:max-h-[580px] pr-1 flex-shrink-0">
                        <?php foreach (array_slice($galleryImages, 0, 4) as $index => $imgUrl): ?>
                            <button type="button" 
                                    onclick="changeMainImage('<?= htmlspecialchars($imgUrl) ?>', this)"
                                    class="thumb-btn border-2 border-slate-400 dark:border-neutral-700 w-16 h-20 sm:w-20 sm:h-24 rounded-md overflow-hidden flex-shrink-0 opacity-90 hover:opacity-100 transition cursor-pointer <?= $index === 0 ? 'thumb-active' : '' ?>">
                                <img src="<?= htmlspecialchars($imgUrl) ?>" alt="thumb" class="w-full h-full object-cover">
                            </button>
                        <?php endforeach; ?>
                    </div>

                    <!-- MAIN IMAGE SHOWCASE -->
                    <div class="flex-grow aspect-[4/5] bg-slate-100 dark:bg-neutral-900 border-2 border-slate-300 dark:border-neutral-800 rounded-lg overflow-hidden relative">
                        <img id="mainProductImg" 
                             src="<?= htmlspecialchars($galleryImages[0] ?? $product['image']) ?>" 
                             alt="<?= htmlspecialchars($product['name']) ?>" 
                             class="w-full h-full object-cover transition duration-300">
                    </div>

                </div>

                <!-- RIGHT SIDE: PRODUCT DETAILS & PURCHASING OPTIONS (5 COLUMNS) -->
                <div class="lg:col-span-5 flex flex-col justify-start space-y-5">
                    
                    <!-- PRODUCT TITLE -->
                    <div>
                        <h1 class="text-xl md:text-2xl font-extrabold leading-snug">
                            <?= htmlspecialchars($product['name']) ?>
                        </h1>
                        <p class="text-xs mt-1 font-mono font-extrabold tracking-wider">
                            SKU: <?= htmlspecialchars($sku) ?>
                        </p>
                    </div>

                    <!-- PRICE BLOCK -->
                    <div class="flex items-baseline gap-3">
                        <span class="text-2xl font-extrabold text-red-600">
                            ฿<?= number_format($currentPrice, 2) ?>
                        </span>
                        <span class="text-sm line-through font-bold text-slate-500 dark:text-neutral-400">
                            ฿<?= number_format($originalPrice, 0) ?>
                        </span>
                    </div>

                    <hr class="border-slate-300 dark:border-neutral-800 my-2">

                    <!-- COLOR SELECTOR (สี) -->
                    <div class="space-y-2">
                        <div class="flex justify-between items-center text-xs font-extrabold">
                            <span>สี</span>
                        </div>
                        <input type="hidden" name="selected_color" id="selectedColorInput" value="<?= htmlspecialchars($colors[0]) ?>">
                        
                        <div class="flex items-center gap-2.5 flex-wrap">
                            <?php foreach ($colors as $idx => $clr): ?>
                                <button type="button" 
                                        onclick="selectColor('<?= htmlspecialchars($clr) ?>', this)"
                                        class="color-btn w-12 h-14 rounded-md overflow-hidden border-2 border-slate-400 dark:border-neutral-700 relative hover:border-black transition flex flex-col items-center justify-center p-1 text-[11px] <?= $idx === 0 ? 'color-swatch-active' : '' ?>"
                                        title="<?= htmlspecialchars($clr) ?>">
                                    <img src="<?= htmlspecialchars($galleryImages[$idx % count($galleryImages)]) ?>" alt="swatch" class="w-full h-8 object-cover rounded-sm mb-0.5">
                                    <span class="text-[10px] font-extrabold truncate w-full text-center"><?= htmlspecialchars($clr) ?></span>
                                </button>
                            <?php endforeach; ?>
                        </div>
                    </div>

                    <!-- SIZE SELECTOR (ไซส์) -->
                    <div class="space-y-2 pt-2">
                        <div class="flex justify-between items-center text-xs font-extrabold">
                            <span>ไซส์</span>
                            <button type="button" onclick="alert('ขนาดสินค้ามาตรฐาน: S (38 นิ้ว), M (40 นิ้ว), L (42 นิ้ว), XL (44 นิ้ว)')" class="hover:text-amber-600 flex items-center gap-1 font-extrabold transition">
                                📐 <span class="underline">ขนาดสินค้า</span>
                            </button>
                        </div>
                        <input type="hidden" name="selected_size" id="selectedSizeInput" value="<?= htmlspecialchars(end($sizes)) ?>">

                        <div class="flex items-center gap-2.5 flex-wrap">
                            <?php 
                            $lastSize = end($sizes);
                            foreach ($sizes as $sz): 
                                $isSelected = ($sz === $lastSize);
                            ?>
                                <button type="button" 
                                        onclick="selectSize('<?= htmlspecialchars($sz) ?>', this)"
                                        class="size-btn w-10 h-10 rounded-full border-2 border-slate-500 dark:border-neutral-700 text-xs font-extrabold flex items-center justify-center transition cursor-pointer <?= $isSelected ? 'size-btn-active' : 'bg-white dark:bg-neutral-900' ?>">
                                    <?= htmlspecialchars($sz) ?>
                                </button>
                            <?php endforeach; ?>
                        </div>
                    </div>

                    <!-- QUANTITY SELECTOR (จำนวน) -->
                    <div class="space-y-2 pt-2">
                        <label class="block text-xs font-extrabold">จำนวน</label>
                        <div class="flex items-center gap-3">
                            <div class="flex items-center border-2 border-slate-500 dark:border-neutral-800 rounded-full overflow-hidden bg-slate-100 dark:bg-neutral-900">
                                <button type="button" 
                                        onclick="const q = document.getElementById('qtyInput'); if(parseInt(q.value) > 1) q.value = parseInt(q.value) - 1;" 
                                        class="w-10 h-10 flex items-center justify-center font-extrabold hover:bg-slate-200 dark:hover:bg-neutral-800 transition">
                                    —
                                </button>
                                <input type="number" 
                                       id="qtyInput" 
                                       name="quantity" 
                                       value="1" 
                                       min="1" 
                                       class="w-12 text-center text-sm font-extrabold bg-transparent outline-none">
                                <button type="button" 
                                        onclick="const q = document.getElementById('qtyInput'); q.value = parseInt(q.value) + 1;" 
                                        class="w-10 h-10 flex items-center justify-center font-extrabold hover:bg-slate-200 dark:hover:bg-neutral-800 transition">
                                    +
                                </button>
                            </div>
                        </div>
                    </div>

                    <hr class="border-slate-300 dark:border-neutral-800 my-2">

                    <!-- ACTION BUTTONS ROW (WISHLIST + ADD TO CART + BUY NOW) -->
                    <div class="flex items-center gap-3 pt-2">
                        
                        <!-- Wishlist Heart Button -->
                        <button type="button" 
                                onclick="this.classList.toggle('text-red-600'); alert('บันทึกในรายการที่ชอบเรียบร้อยแล้ว')"
                                class="w-12 h-12 rounded-full border-2 border-slate-900 dark:border-neutral-700 flex items-center justify-center font-extrabold hover:bg-slate-100 dark:hover:bg-neutral-800 transition flex-shrink-0 text-base">
                            ♡
                        </button>

                        <!-- Add to Cart Outline Pill Button (SOLID BLACK IN LIGHT MODE) -->
                        <button type="submit" 
                                name="action" 
                                value="add_to_cart" 
                                class="flex-1 border-2 border-slate-900 dark:border-white py-3.5 px-4 rounded-full font-extrabold text-xs hover:bg-slate-100 dark:hover:bg-neutral-800 transition text-center shadow-sm">
                            ใส่ตะกร้า
                        </button>

                        <!-- Buy Now Solid Yellow Pill Button -->
                        <button type="submit" 
                                name="action" 
                                value="buy_now" 
                                class="flex-1 bg-[#ffcc00] hover:bg-[#ebbb00] text-black py-3.5 px-6 rounded-full font-extrabold text-xs tracking-wide shadow-md transition transform active:scale-95 text-center">
                            สั่งซื้อสินค้า
                        </button>

                    </div>

                    <!-- DESCRIPTION SUMMARY -->
                    <?php if (!empty($product['description'])): ?>
                        <div class="pt-4 text-xs font-bold leading-relaxed">
                            <span class="font-extrabold block mb-1 text-sm">รายละเอียดสินค้า:</span>
                            <?= nl2br(htmlspecialchars($product['description'])) ?>
                        </div>
                    <?php endif; ?>

                </div>

            </div>

        </form>

    </main>

    <!-- FOOTER -->
    <footer class="py-8 text-center text-xs border-t border-slate-300 dark:border-neutral-800 font-bold bg-slate-100 dark:bg-neutral-950">
        <p class="font-bold text-xs mb-1">NoaShop E-Commerce Store</p>
        <p class="text-[11px] font-bold">© 2026 NoaShop. All Rights Reserved.</p>
    </footer>

    <script>
        function changeMainImage(src, element) {
            document.getElementById('mainProductImg').src = src;
            document.querySelectorAll('.thumb-btn').forEach(btn => btn.classList.remove('thumb-active'));
            element.classList.add('thumb-active');
        }

        function selectSize(sizeVal, element) {
            document.getElementById('selectedSizeInput').value = sizeVal;
            document.querySelectorAll('.size-btn').forEach(btn => btn.classList.remove('size-btn-active'));
            element.classList.add('size-btn-active');
        }

        function selectColor(colorVal, element) {
            document.getElementById('selectedColorInput').value = colorVal;
            document.querySelectorAll('.color-btn').forEach(btn => btn.classList.remove('color-swatch-active'));
            element.classList.add('color-swatch-active');
        }
    </script>
</body>
</html>
