<?php
// NEXUS Commerce - Database Initialization & Seed Script (MySQL Compatible)
require_once __DIR__ . '/db.php';

try {
    $pdo->exec("SET FOREIGN_KEY_CHECKS = 0");

    // ---- CREATE TABLES (MySQL syntax) ----
    $pdo->exec("CREATE TABLE IF NOT EXISTS `users` (
        `id` INT AUTO_INCREMENT PRIMARY KEY,
        `name` VARCHAR(100) NOT NULL,
        `username` VARCHAR(50) UNIQUE,
        `phone` VARCHAR(20) UNIQUE,
        `email` VARCHAR(150),
        `password_hash` VARCHAR(255),
        `role` ENUM('customer','seller','creator','admin') DEFAULT 'customer',
        `level` ENUM('Explorer','Shopper','Insider','VIP','Elite') DEFAULT 'Explorer',
        `xp` INT DEFAULT 120,
        `coins` INT DEFAULT 250,
        `avatar_url` VARCHAR(255),
        `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");

    $pdo->exec("CREATE TABLE IF NOT EXISTS `stores` (
        `id` INT AUTO_INCREMENT PRIMARY KEY,
        `user_id` INT NOT NULL,
        `store_name` VARCHAR(100) NOT NULL,
        `logo_url` VARCHAR(255),
        `banner_url` VARCHAR(255),
        `rating` DECIMAL(3,2) DEFAULT 4.90,
        `trust_score` INT DEFAULT 96,
        `response_rate` INT DEFAULT 98,
        `is_verified` TINYINT(1) DEFAULT 1
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");

    $pdo->exec("CREATE TABLE IF NOT EXISTS `categories` (
        `id` INT AUTO_INCREMENT PRIMARY KEY,
        `name` VARCHAR(100) NOT NULL,
        `icon_class` VARCHAR(50),
        `slug` VARCHAR(100) UNIQUE NOT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");

    $pdo->exec("DROP TABLE IF EXISTS `products`");
    $pdo->exec("CREATE TABLE IF NOT EXISTS `products` (
        `id` INT AUTO_INCREMENT PRIMARY KEY,
        `store_id` INT NOT NULL,
        `category_id` INT NOT NULL,
        `title` VARCHAR(255) NOT NULL,
        `description` TEXT,
        `price` DECIMAL(10,2) NOT NULL,
        `original_price` DECIMAL(10,2),
        `stock` INT DEFAULT 45,
        `sku` VARCHAR(50),
        `trust_score` INT DEFAULT 94,
        `sales_count` INT DEFAULT 1420,
        `view_count` INT DEFAULT 8900,
        `rating_avg` DECIMAL(3,2) DEFAULT 4.85,
        `review_count` INT DEFAULT 328,
        `is_group_buy` TINYINT(1) DEFAULT 0,
        `group_price` DECIMAL(10,2),
        `image_url` VARCHAR(255),
        `gallery` JSON,
        `specs` JSON,
        `variants` JSON,
        `ai_summary` JSON,
        `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");

    $pdo->exec("CREATE TABLE IF NOT EXISTS `collections` (
        `id` INT AUTO_INCREMENT PRIMARY KEY,
        `user_id` INT NOT NULL,
        `title` VARCHAR(150) NOT NULL,
        `description` TEXT,
        `cover_image` VARCHAR(255),
        `likes_count` INT DEFAULT 142,
        `items` JSON,
        `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");

    $pdo->exec("CREATE TABLE IF NOT EXISTS `orders` (
        `id` INT AUTO_INCREMENT PRIMARY KEY,
        `order_sn` VARCHAR(50) UNIQUE NOT NULL,
        `user_id` INT NOT NULL,
        `total_amount` DECIMAL(10,2) NOT NULL,
        `discount_amount` DECIMAL(10,2) DEFAULT 0.00,
        `coins_used` INT DEFAULT 0,
        `final_amount` DECIMAL(10,2) NOT NULL,
        `status` ENUM('pending','preparing','packed','shipped','out_for_delivery','delivered','returned') DEFAULT 'preparing',
        `tracking_number` VARCHAR(100),
        `shipping_address` TEXT,
        `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");

    $pdo->exec("CREATE TABLE IF NOT EXISTS `order_items` (
        `id` INT AUTO_INCREMENT PRIMARY KEY,
        `order_id` INT NOT NULL,
        `product_id` INT NOT NULL,
        `quantity` INT NOT NULL,
        `unit_price` DECIMAL(10,2) NOT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");

    $pdo->exec("CREATE TABLE IF NOT EXISTS `quests` (
        `id` INT AUTO_INCREMENT PRIMARY KEY,
        `title` VARCHAR(100) NOT NULL,
        `description` VARCHAR(255),
        `reward_coins` INT DEFAULT 20,
        `reward_xp` INT DEFAULT 100,
        `is_completed` TINYINT(1) DEFAULT 0
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");

    // ---- CLEAR OLD DATA ----
    $pdo->exec("DELETE FROM `products`");
    $pdo->exec("DELETE FROM `categories`");
    $pdo->exec("DELETE FROM `stores`");

    // ---- SEED CATEGORIES ----
    $pdo->exec("INSERT IGNORE INTO `categories` (`id`,`name`,`icon_class`,`slug`) VALUES
        (1,'Tech & Gadgets','ph-cpu','tech'),
        (2,'Cyber Fashion','ph-t-shirt','fashion'),
        (3,'Smart Home','ph-house-line','home'),
        (4,'Audio & Studio','ph-headphones','audio'),
        (5,'Gaming Gear','ph-game-controller','gaming')");

    // ---- SEED USERS ----
    $pdo->exec("INSERT IGNORE INTO `users` (`id`,`name`,`username`,`phone`,`email`,`password_hash`,`role`,`level`,`xp`,`coins`,`avatar_url`) VALUES
        (1,'Alex Vance','alexvance','0812345678','alex@nexus.io','password123','customer','Insider',450,380,'https://images.unsplash.com/photo-1534528741775-53994a69daeb?w=150'),
        (2,'CyberPulse Store','cyberpulse','0898765432','seller@cyberpulse.com','password123','seller','Elite',2400,1500,'https://images.unsplash.com/photo-1618005182384-a83a8bd57fbe?w=150'),
        (3,'John Creator','johncreator','0877778888','john@creators.com','password123','creator','VIP',1200,890,'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=150'),
        (4,'Super Admin NEXUS','admin_nexus','0800000000','admin@nexus.io','adminpass','admin','Elite',9999,9999,'https://images.unsplash.com/photo-1535713875002-d1d0cf377fde?w=150')");

    // ---- SEED STORES ----
    $pdo->exec("INSERT IGNORE INTO `stores` (`id`,`user_id`,`store_name`,`logo_url`,`rating`,`trust_score`,`response_rate`,`is_verified`) VALUES
        (1,2,'CyberPulse Official','https://images.unsplash.com/photo-1618005182384-a83a8bd57fbe?w=150',4.90,98,99,1),
        (2,3,'Aura Audio Lab','https://images.unsplash.com/photo-1590658268037-6bf12165a8df?w=150',4.80,94,96,1)");

    // ---- SEED PRODUCTS ----
    $products = [
        [1,1,4,'หูฟังไร้สาย NEXUS Pro Wireless ANC Headphones - Obsidian Black',
         'Active Noise Cancelling หูฟังไร้สายพร้อม ANC 45dB แบตเตอรี่ 50 ชม. Bluetooth 5.3',
         2490.00,3290.00,38,'NEX-AUD-01',97,840,4.90,1,1990.00,
         'https://images.unsplash.com/photo-1505740420928-5e560c06d30e?w=600',
         json_encode(['https://images.unsplash.com/photo-1505740420928-5e560c06d30e?w=600','https://images.unsplash.com/photo-1484704849700-f032a568e944?w=600']),
         json_encode(['ระบบตัดเสียง'=>'Hybrid ANC 45dB','แบตเตอรี่'=>'50 ชม.','Bluetooth'=>'v5.3','น้ำหนัก'=>'240g']),
         json_encode(['colors'=>[['name'=>'ดำ Obsidian Black','image'=>'https://images.unsplash.com/photo-1505740420928-5e560c06d30e?w=600'],['name'=>'ขาว Platinum Silver','image'=>'https://images.unsplash.com/photo-1484704849700-f032a568e944?w=600']],'editions'=>[['name'=>'Standard Edition','price_offset'=>0],['name'=>'Pro Bundle +เคสหนัง','price_offset'=>400]]]),
         json_encode(['verdict'=>'หูฟัง ANC คุ้มค่าที่สุดในงบไม่เกิน 3,000 บาท','pros'=>['ตัดเสียง 45dB','แบต 50 ชม.','ชาร์จไว 10 นาทีฟังได้ 5 ชม.'],'cons'=>['เคสมีขนาดใหญ่เล็กน้อย'],'best_for'=>'นักเดินทาง, คนทำงานออฟฟิศ'])],

        [2,1,5,'คีย์บอร์ดเกมมิ่ง CyberDeck V1 Ergonomic Mechanical RGB Keyboard',
         'Gasket mount hot-swappable คีย์บอร์ดกด Thocky สวิตช์ Yellow Linear Pre-lubed',
         1890.00,2450.00,18,'NEX-KB-02',95,1250,4.80,1,1490.00,
         'https://images.unsplash.com/photo-1587829741301-dc798b83add3?w=600',
         json_encode(['https://images.unsplash.com/photo-1587829741301-dc798b83add3?w=600','https://images.unsplash.com/photo-1618384887929-16ec33fab9ef?w=600']),
         json_encode(['สวิตช์'=>'Hot-swap Yellow Linear (Pre-lubed)','คีย์แคป'=>'Double-shot PBT','การเชื่อมต่อ'=>'Tri-Mode 2.4GHz/BT5.1/USB-C','แบตเตอรี่'=>'4000mAh 200 ชม.']),
         json_encode(['colors'=>[['name'=>'ดำ Cyber Black','image'=>'https://images.unsplash.com/photo-1587829741301-dc798b83add3?w=600'],['name'=>'ขาว Retro White','image'=>'https://images.unsplash.com/photo-1618384887929-16ec33fab9ef?w=600']],'switches'=>[['name'=>'Yellow Linear (นุ่ม)','price_offset'=>0],['name'=>'Blue Clicky (คลิกๆ)','price_offset'=>0],['name'=>'Brown Tactile','price_offset'=>100]]]),
         json_encode(['verdict'=>'ฟีลพิมพ์ Thock นุ่มแน่น ไร้สาย 3 ระบบ','pros'=>['Pre-lubed ลื่นเงียบ','ไร้สาย 3 ระบบ','แบต 4000mAh'],'cons'=>['ไม่มีที่พักข้อมือแถม'],'best_for'=>'เกมเมอร์, โปรแกรมเมอร์'])],

        [3,2,1,'โคมไฟแขวนจอคอม Aura LightBar Pro - พร้อมปุ่มหมุนไร้สาย',
         'ไฟแขวนจอ Zero Glare CRI>95 ปรับอุณหภูมิสี 2700K-6500K ปุ่มควบคุมไร้สาย',
         1290.00,1690.00,50,'NEX-LGT-03',98,2100,4.95,0,1290.00,
         'https://images.unsplash.com/photo-1527443224154-c4a3942d3acf?w=600',
         json_encode(['https://images.unsplash.com/photo-1527443224154-c4a3942d3acf?w=600']),
         json_encode(['ความถูกต้องสี'=>'CRI (Ra) > 95','อุณหภูมิสี'=>'2700K-6500K','ระบบควบคุม'=>'2.4GHz Wireless Dial','กำลังไฟ'=>'USB-C 5V/1A']),
         json_encode(['colors'=>[['name'=>'ดำ Matte Black','image'=>'https://images.unsplash.com/photo-1527443224154-c4a3942d3acf?w=600'],['name'=>'เงิน Space Gray','image'=>'https://images.unsplash.com/photo-1527443224154-c4a3942d3acf?w=600']],'sizes'=>[['name'=>'44cm สำหรับจอ 17-27 นิ้ว','price_offset'=>0],['name'=>'52cm Pro สำหรับจอ 28-34 นิ้ว','price_offset'=>300]]]),
         json_encode(['verdict'=>'ของดีจำเป็นสำหรับคนทำงานดึก ไม่สะท้อนจอ','pros'=>['ตัดแสงสะท้อน 100%','ปุ่มหมุนไร้สาย','CRI สูง'],'cons'=>['ไม่รองรับจอโค้งหนากว่า 45mm'],'best_for'=>'กราฟิกดีไซเนอร์, คนทำงานดึก'])],

        [4,1,2,'เสื้อฮู้ดดี้ Cyberpunk Oversized Hoodie - Neon Purple',
         'ผ้า Organic Cotton 450 GSM สกรีน 3M Reflective Print กระเป๋าซิปกันน้ำ',
         1490.00,1990.00,12,'NEX-CLO-04',93,630,4.75,1,1190.00,
         'https://images.unsplash.com/photo-1556905055-8f358a7a47b2?w=600',
         json_encode(['https://images.unsplash.com/photo-1556905055-8f358a7a47b2?w=600']),
         json_encode(['ส่วนประกอบผ้า'=>'80% Organic Cotton, 20% Tech Polyester','ความหนาผ้า'=>'450 GSM Heavyweight','ทรงเสื้อ'=>'Cyberpunk Oversized Fit']),
         json_encode(['colors'=>[['name'=>'ม่วง Neon Purple','image'=>'https://images.unsplash.com/photo-1556905055-8f358a7a47b2?w=600'],['name'=>'ดำ Cyber Black','image'=>'https://images.unsplash.com/photo-1556905055-8f358a7a47b2?w=600'],['name'=>'เทา Acid Grey','image'=>'https://images.unsplash.com/photo-1556905055-8f358a7a47b2?w=600']],'sizes'=>[['name'=>'S','price_offset'=>0],['name'=>'M','price_offset'=>0],['name'=>'L','price_offset'=>0],['name'=>'XL','price_offset'=>0],['name'=>'2XL','price_offset'=>100]]]),
         json_encode(['verdict'=>'ผ้าหนา 450 GSM สกรีนสะท้อนแสงโดดเด่น','pros'=>['ผ้าหนานุ่ม','สกรีนสะท้อนแสง','กระเป๋าซิปกันน้ำ'],'cons'=>['ไซส์ใหญ่กว่ามาตรฐานเล็กน้อย'],'best_for'=>'สายแฟชั่น, คอนเสิร์ต, เที่ยวกลางคืน'])],

        [5,2,3,'กระติกน้ำอัจฉริยะ Smart Hydro Flask V2 - หน้าจอ OLED บอกอุณหภูมิ',
         'กระบอกน้ำสุญญากาศ หน้าจอ OLED ฝา UV-C LED ฆ่าเชื้อ 99.9% เก็บเย็น 24 ชม.',
         890.00,1200.00,65,'NEX-BOT-05',96,3400,4.90,1,690.00,
         'https://images.unsplash.com/photo-1602143407151-7111542de6e8?w=600',
         json_encode(['https://images.unsplash.com/photo-1602143407151-7111542de6e8?w=600']),
         json_encode(['ความจุ'=>'650 ml','ระบบฆ่าเชื้อ'=>'UV-C LED 99.9%','อุณหภูมิ'=>'เย็น 24 ชม. / ร้อน 12 ชม.','วัสดุ'=>'Stainless 18/8 BPA Free']),
         json_encode(['colors'=>[['name'=>'ขาว Matte White','image'=>'https://images.unsplash.com/photo-1602143407151-7111542de6e8?w=600'],['name'=>'ดำ Stealth Black','image'=>'https://images.unsplash.com/photo-1602143407151-7111542de6e8?w=600'],['name'=>'ชมพู Sakura Pink','image'=>'https://images.unsplash.com/photo-1602143407151-7111542de6e8?w=600']],'sizes'=>[['name'=>'650ml (พกพา)','price_offset'=>0],['name'=>'1000ml (ฟิตเนส)','price_offset'=>200]]]),
         json_encode(['verdict'=>'แก้วน้ำอัจฉริยะ UV สะอาดไร้กลิ่น','pros'=>['UV-C ฆ่าเชื้อในตัว','เก็บเย็น 24 ชม.','OLED บอกอุณหภูมิ'],'cons'=>['ต้องชาร์จฝาเดือนละครั้ง'],'best_for'=>'คนออกกำลังกาย, พนักงานออฟฟิศ'])],

        [6,1,5,'เมาส์ไร้สายเกมมิ่ง CyberMouse Ultra Light 49g - เซ็นเซอร์ PAW3395',
         'น้ำหนักเบาเพียง 49g เซ็นเซอร์ PAW3395 26,000 DPI 4000Hz Polling Rate',
         1590.00,2190.00,25,'NEX-MSE-06',97,1890,4.90,1,1290.00,
         'https://images.unsplash.com/photo-1615663245857-ac93bb7c39e7?w=600',
         json_encode(['https://images.unsplash.com/photo-1615663245857-ac93bb7c39e7?w=600']),
         json_encode(['น้ำหนัก'=>'49g Ultra Lightweight','เซ็นเซอร์'=>'PixArt PAW3395 26,000 DPI','Polling Rate'=>'4000Hz','แบตเตอรี่'=>'80 ชม.']),
         json_encode(['colors'=>[['name'=>'ขาว Pure White','image'=>'https://images.unsplash.com/photo-1615663245857-ac93bb7c39e7?w=600'],['name'=>'ดำ Phantom Black','image'=>'https://images.unsplash.com/photo-1615663245857-ac93bb7c39e7?w=600']]]),
         json_encode(['verdict'=>'เมาส์เบาที่สุด เซ็นเซอร์ระดับท็อป','pros'=>['เบา 49g','PAW3395 แม่นยำ','สวิตช์ออปติคัลไม่ดับเบิล'],'cons'=>['ไม่มีไฟ RGB'],'best_for'=>'เกมเมอร์ FPS, Esports'])],

        [7,2,4,'ลำโพงบลูทูธพกพา Aura Boom Sound 360 - เบสแน่น กันน้ำ IPX7',
         'ลำโพง 30W RMS เสียงรอบทิศทาง 360° กันน้ำ IPX7 แบตเตอรี่ 18 ชม.',
         1190.00,1690.00,40,'NEX-SPK-07',95,2750,4.85,1,890.00,
         'https://images.unsplash.com/photo-1545454675-3531b543be5d?w=600',
         json_encode(['https://images.unsplash.com/photo-1545454675-3531b543be5d?w=600']),
         json_encode(['กำลังขับ'=>'30W RMS','การกันน้ำ'=>'IPX7','แบตเตอรี่'=>'18 ชม.']),
         json_encode(['colors'=>[['name'=>'ดำ Midnight Black','image'=>'https://images.unsplash.com/photo-1545454675-3531b543be5d?w=600'],['name'=>'น้ำเงิน Ocean Blue','image'=>'https://images.unsplash.com/photo-1545454675-3531b543be5d?w=600']]]),
         json_encode(['verdict'=>'ลำโพงพกพากันน้ำ เบสแน่น คุ้มราคา','pros'=>['เสียง 360° ดัง 30W','กันน้ำ IPX7','แบต 18 ชม.'],'cons'=>['น้ำหนักหนักกว่าลำโพงเล็กเล็กน้อย'],'best_for'=>'แคมป์ปิ้ง, ปาร์ตี้ริมสระ'])],

        [8,1,1,'สมาร์ทวอทช์ออกกำลังกาย CyberWatch Pro AMOLED - วัดชีพจร & SpO2',
         'หน้าจอ AMOLED 1.43 นิ้ว GPS ในตัว 100 โหมดออกกำลังกาย กันน้ำ 5ATM แบต 14 วัน',
         2290.00,3190.00,30,'NEX-WTC-08',98,1430,4.92,1,1890.00,
         'https://images.unsplash.com/photo-1579586337278-3befd40fd17a?w=600',
         json_encode(['https://images.unsplash.com/photo-1579586337278-3befd40fd17a?w=600']),
         json_encode(['หน้าจอ'=>'1.43" AMOLED 466x466px','GPS'=>'Dual-Band Built-in','กันน้ำ'=>'5ATM','แบตเตอรี่'=>'14 วัน']),
         json_encode(['colors'=>[['name'=>'ดำ Space Black','image'=>'https://images.unsplash.com/photo-1579586337278-3befd40fd17a?w=600'],['name'=>'เงิน Platinum Silver','image'=>'https://images.unsplash.com/photo-1579586337278-3befd40fd17a?w=600']]]),
         json_encode(['verdict'=>'สมาร์ทวอทช์สุขภาพคุ้มค่า จอสวย GPS แม่น แบตอึด 14 วัน','pros'=>['AMOLED สดใส','GPS ในตัว','5ATM ว่ายน้ำได้','แบต 14 วัน'],'cons'=>['โทรออกผ่านซิมไม่ได้'],'best_for'=>'คนรักสุขภาพ, สายวิ่ง'])]
    ];

    $stmtProd = $pdo->prepare("INSERT INTO `products`
        (`id`,`store_id`,`category_id`,`title`,`description`,`price`,`original_price`,`stock`,`sku`,
         `trust_score`,`sales_count`,`rating_avg`,`is_group_buy`,`group_price`,
         `image_url`,`gallery`,`specs`,`variants`,`ai_summary`)
        VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");

    foreach ($products as $p) {
        $stmtProd->execute($p);
    }

    // ---- SEED ORDERS ----
    $pdo->exec("INSERT IGNORE INTO `orders` (`id`,`order_sn`,`user_id`,`total_amount`,`discount_amount`,`final_amount`,`status`,`tracking_number`,`shipping_address`) VALUES
        (1,'NEX-2026-001',1,2490.00,200.00,2290.00,'preparing','TH902847291','Alex Vance, 123 Sukhumvit Rd, Bangkok 10110'),
        (2,'NEX-2026-002',1,1890.00,0.00,1890.00,'packed','TH902847292','Somsak P., 45 Silom Rd, Bangkok 10500')");

    $pdo->exec("INSERT IGNORE INTO `order_items` (`id`,`order_id`,`product_id`,`quantity`,`unit_price`) VALUES
        (1,1,1,1,2490.00),
        (2,2,2,1,1890.00)");

    // ---- SEED QUESTS ----
    $pdo->exec("INSERT IGNORE INTO `quests` (`id`,`title`,`description`,`reward_coins`,`reward_xp`,`is_completed`) VALUES
        (1,'Daily Attendance Check-In','Claim your daily login attendance reward',15,50,0),
        (2,'Try Interactive 360 Product Room','Rotate products in 3D room',30,100,0)");

    $pdo->exec("SET FOREIGN_KEY_CHECKS = 1");

    echo json_encode(['status' => 'success', 'message' => 'Database initialized and seeded successfully (MySQL).']);

} catch (Exception $e) {
    echo json_encode(['error' => 'Seeding failed: ' . $e->getMessage()]);
}
