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

// -------------------------------------------------------------
// [1] ระบบความปลอดภัย ป้องกันผู้บุกรุก (Security Guard)
// -------------------------------------------------------------
if (!isset($_SESSION['is_logged_in']) || $_SESSION['is_logged_in'] !== true || $_SESSION['user_role'] !== 'admin') {
    header('Location: index.php');
    exit;
}

// ป้องกันข้อผิดพลาด Undefined Index สำหรับ preorders
if (!isset($_SESSION['preorders'])) {
    $_SESSION['preorders'] = [];
}

// -------------------------------------------------------------
// [2] ตรรกะจัดการการจัดการสินค้า (Business Logic)
// -------------------------------------------------------------
$alert_message = "";

if (isset($_GET['added']) && $_GET['added'] == 1) {
    $alert_message = ($_SESSION['lang'] == 'th') ? "✅ เพิ่มสินค้าเข้าร้านสำเร็จและจัดเก็บลงฐานข้อมูลเรียบร้อย!" : "✅ Product added and saved persistently in SQLite database!";
}
if (isset($_GET['deleted']) && $_GET['deleted'] == 1) {
    $alert_message = ($_SESSION['lang'] == 'th') ? "🗑️ ลบสินค้าออกจากฐานข้อมูลแล้ว" : "🗑️ Product deleted from SQLite database!";
}

// 1. เพิ่มสินค้าชิ้นใหม่เข้าคลังสินค้าฐานข้อมูลจริง
if (isset($_POST['process_add_product'])) {
    $name_th = trim($_POST['p_name_th']);
    $name_en = trim($_POST['p_name_en']);
    $price = (float)$_POST['p_price'];
    $stock = (int)$_POST['p_stock'];
    $category = trim($_POST['p_category']);
    $sizes = trim($_POST['p_sizes']);
    $colors_th = trim($_POST['p_colors_th']);
    $colors_en = trim($_POST['p_colors_en']);
    $image = !empty($_POST['p_image']) ? trim($_POST['p_image']) : 'https://images.unsplash.com/photo-1523381210434-271e8be1f52b?w=600';
    
    // หา ID ร้านค้ายีนส์แฟชั่นเสื้อผ้า
    $shopId = $pdo->query("SELECT id FROM shops WHERE name = 'VogueThread Boutique'")->fetchColumn() ?: 2;

    try {
        $stmt = $pdo->prepare("
            INSERT INTO products (shop_id, name, name_th, name_en, description, price, image, category, sizes, colors_th, colors_en, stock)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");
        $stmt->execute([
            $shopId,
            $name_th,
            $name_th,
            $name_en,
            'เสื้อผ้าสำเร็จรูปแนวสตรีทแวร์และมินิมอลแฟชั่นนำเข้าระดับพรีเมียม',
            $price,
            $image,
            $category,
            $sizes,
            $colors_th,
            $colors_en,
            $stock
        ]);
        
        header('Location: admin.php?added=1');
        exit;
    } catch (PDOException $e) {
        $alert_message = "เกิดข้อผิดพลาดในการบันทึกสินค้า: " . $e->getMessage();
    }
}

// 2. จัดการลบสินค้าจากคลังสินค้าฐานข้อมูลจริง
if (isset($_GET['action']) && $_GET['action'] === 'delete_product') {
    $prod_id = (int)$_GET['id'];
    try {
        $stmt = $pdo->prepare("DELETE FROM products WHERE id = ?");
        $stmt->execute([$prod_id]);
        
        header('Location: admin.php?deleted=1');
        exit;
    } catch (PDOException $e) {
        $alert_message = "เกิดข้อผิดพลาดในการลบสินค้า: " . $e->getMessage();
    }
}
?>
<!DOCTYPE html>
<html lang="<?= $lang ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= ($lang == 'th') ? 'หลังบ้านแอดมิน' : 'Admin Panel' ?> - Noa Shop</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css"/>
    <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;600;800&family=Sarabun:wght@300;400;600;800&display=swap" rel="stylesheet">
    <style>
        body { font-family: 'Outfit', 'Sarabun', sans-serif; }
    </style>
</head>
<body class="<?= $tc['bg'] ?> min-h-screen p-6 transition-colors duration-300">

    <div class="max-w-6xl mx-auto">
        
        <!-- Navbar ของหน้าแอดมิน -->
        <div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-8 pb-4 border-b border-red-500/40 gap-4">
            <div>
                <span class="bg-red-500 text-white text-[10px] font-black px-2.5 py-1 rounded-md tracking-wider">ROOT SYSTEM ACCESS</span>
                <h1 class="text-3xl font-extrabold text-red-500 mt-1">🛡️ Admin Control Centre</h1>
                <p class="text-xs opacity-60">ระบบจัดการคลังสินค้าเสื้อผ้าแฟชั่น Noa Shop</p>
            </div>
            <a href="index.php" class="bg-neutral-600 hover:bg-neutral-700 text-white font-bold text-xs px-5 py-2.5 rounded-xl shadow transition duration-200">
                ← กลับหน้าร้านหลัก
            </a>
        </div>

        <?php if (!empty($alert_message)): ?>
            <div class="mb-6 p-4 bg-emerald-500 text-white font-bold rounded-2xl text-center shadow animate__animated animate__fadeIn">
                <?= htmlspecialchars($alert_message) ?>
            </div>
        <?php endif; ?>

        <!-- GRID Layout หน้าแอดมิน -->
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8 items-start">
            
            <!-- ซ้าย: ฟอร์มแอดสินค้าใหม่ -->
            <div class="lg:col-span-2 rounded-3xl p-6 <?= $tc['card'] ?>">
                <h2 class="text-xl font-bold text-amber-500 mb-5 flex items-center gap-2">
                    <span>➕</span> เพิ่มสินค้าใหม่เข้า Session
                </h2>

                <form action="admin.php" method="POST" class="space-y-4 text-xs">
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label class="block font-bold mb-1.5 opacity-70">ชื่อสินค้าภาษาไทย</label>
                            <input type="text" name="p_name_th" required class="w-full p-3 rounded-xl outline-none <?= $tc['input'] ?>" placeholder="เสื้อฮู้ดดี้สตรีทพรีเมียม">
                        </div>
                        <div>
                            <label class="block font-bold mb-1.5 opacity-70">ชื่อสินค้าภาษาอังกฤษ (English Name)</label>
                            <input type="text" name="p_name_en" required class="w-full p-3 rounded-xl outline-none <?= $tc['input'] ?>" placeholder="Premium Streetwear Hoodie">
                        </div>
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                        <div>
                            <label class="block font-bold mb-1.5 opacity-70">ราคาขายสินค้า (บาท)</label>
                            <input type="number" name="p_price" required class="w-full p-3 rounded-xl outline-none <?= $tc['input'] ?>" placeholder="590">
                        </div>
                        <div>
                            <label class="block font-bold mb-1.5 opacity-70">จำนวนสต็อกพร้อมขาย (stock)</label>
                            <input type="number" name="p_stock" required class="w-full p-3 rounded-xl outline-none <?= $tc['input'] ?>" placeholder="20">
                        </div>
                        <div>
                            <label class="block font-bold mb-1.5 opacity-70">หมวดหมู่เสื้อผ้า</label>
                            <input type="text" name="p_category" required class="w-full p-3 rounded-xl outline-none <?= $tc['input'] ?>" placeholder="Hoodie / Jacket">
                        </div>
                    </div>

                    <div>
                        <label class="block font-bold mb-1.5 opacity-70">ไซส์เสื้อผ้าที่มี (คั่นด้วยเครื่องหมายจุลภาค `,` )</label>
                        <input type="text" name="p_sizes" required class="w-full p-3 rounded-xl outline-none <?= $tc['input'] ?>" placeholder="S, M, L, XL">
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label class="block font-bold mb-1.5 opacity-70">สีภาษาไทย (คั่นด้วยเครื่องหมาย `,` )</label>
                            <input type="text" name="p_colors_th" required class="w-full p-3 rounded-xl outline-none <?= $tc['input'] ?>" placeholder="ดำ, ขาว, ครีม">
                        </div>
                        <div>
                            <label class="block font-bold mb-1.5 opacity-70">สีภาษาอังกฤษ (คั่นด้วยเครื่องหมาย `,` )</label>
                            <input type="text" name="p_colors_en" required class="w-full p-3 rounded-xl outline-none <?= $tc['input'] ?>" placeholder="Black, White, Cream">
                        </div>
                    </div>

                    <div>
                        <label class="block font-bold mb-1.5 opacity-70">ที่อยู่ลิงก์รูปภาพสินค้า (Image URL)</label>
                        <input type="url" name="p_image" class="w-full p-3 rounded-xl outline-none <?= $tc['input'] ?>" placeholder="https://images.unsplash.com/photo-...">
                    </div>

                    <button type="submit" name="process_add_product" class="w-full bg-red-500 hover:bg-red-600 font-bold text-white py-4 rounded-xl text-xs tracking-wider transition shadow-md duration-200">
                        🚀 อัปโหลดสินค้าเข้าสู่ระบบแบบเรียลไทม์
                    </button>
                </form>
            </div>

            <!-- ขวา: บอร์ดสรุปยอด -->
            <div class="space-y-4">
                <div class="rounded-3xl p-6 <?= $tc['card'] ?>">
                    <h3 class="font-bold opacity-60 text-xs uppercase tracking-widest mb-1.5">Total SKU Items</h3>
                    <p class="text-5xl font-black text-amber-500"><?= count($_SESSION['clothing_products']) ?> <span class="text-xs font-normal text-slate-400">แบบเสื้อผ้า</span></p>
                </div>
                <div class="rounded-3xl p-6 <?= $tc['card'] ?>">
                    <h3 class="font-bold opacity-60 text-xs uppercase tracking-widest mb-1.5">Server Performance</h3>
                    <span class="inline-flex items-center gap-1.5 text-xs font-bold text-green-500">
                        <span class="w-2 h-2 rounded-full bg-green-500 animate-ping"></span> Safe Session Online
                    </span>
                </div>
            </div>

        </div>

        <!-- รายการสินค้าปัจจุบัน -->
        <div class="rounded-3xl p-6 mt-8 <?= $tc['card'] ?>">
            <h2 class="text-xl font-bold mb-5">📦 รายการสินค้าปัจจุบันในระบบ</h2>
            
            <div class="overflow-x-auto">
                <table class="w-full text-left text-xs border-collapse">
                    <thead>
                        <tr class="<?= $tc['table_header'] ?> uppercase tracking-wider">
                            <th class="p-3 rounded-l-xl">รูปสินค้า</th>
                            <th class="p-3">ชื่อสินค้า</th>
                            <th class="p-3">ราคา</th>
                            <th class="p-3">หมวดหมู่</th>
                            <th class="p-3">ไซส์</th>
                            <th class="p-3">สินค้าคงเหลือ (stock)</th>
                            <th class="p-3 text-right rounded-r-xl">การจัดการ</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-700/10">
                        <?php foreach ($_SESSION['clothing_products'] as $item): ?>
                            <tr class="hover:bg-slate-500/5 transition">
                                <td class="p-3">
                                    <img src="<?= htmlspecialchars($item['image']) ?>" alt="thumbnail" class="w-12 h-12 object-cover rounded-xl shadow border border-slate-400/20">
                                </td>
                                <td class="p-3">
                                    <div class="font-bold"><?= htmlspecialchars($item['name_th']) ?></div>
                                    <div class="text-[10px] opacity-60 italic"><?= htmlspecialchars($item['name_en']) ?></div>
                                </td>
                                <td class="p-3 font-black text-amber-500 text-sm">฿<?= number_format($item['price']) ?></td>
                                <td class="p-3 font-semibold opacity-70"><?= htmlspecialchars($item['category']) ?></td>
                                <td class="p-3 font-mono"><?= implode(', ', $item['sizes']) ?></td>
                                <td class="p-3">
                                    <span class="px-2.5 py-1 rounded bg-neutral-500/10 font-bold"><?= $item['stock'] ?> ชิ้น</span>
                                </td>
                                <td class="p-3 text-right">
                                    <a href="admin.php?action=delete_product&id=<?= $item['id'] ?>" onclick="return confirm('ยืนยันลบสินค้านี้?')" class="bg-red-500 hover:bg-red-600 text-white font-bold px-3 py-1.5 rounded-lg transition duration-200">
                                        ลบออก
                                    </a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>

    </div>

</body>
</html>
