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

$message = '';
$messageType = 'info';

// Handle Action: Execute / Import SQL File
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'import_sql') {
        $sqlFile = __DIR__ . '/apex_studio.sql';
        if (!file_exists($sqlFile)) {
            $message = "ไม่พบไฟล์ apex_studio.sql ในโฟลเดอร์โปรเจกต์";
            $messageType = 'error';
        } else {
            try {
                // Connect to MySQL server
                $pdoRoot = new PDO("mysql:host=" . DB_HOST . ";charset=utf8mb4", DB_USER, DB_PASS);
                $pdoRoot->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                
                $sqlContent = file_get_contents($sqlFile);
                
                // Execute multi-statement SQL
                $pdoRoot->exec($sqlContent);
                
                $message = "นำเข้าฐานข้อมูล `apex_studio` จากไฟล์ apex_studio.sql เข้าสู่ MySQL สำเร็จเรียบร้อยแล้ว!";
                $messageType = 'success';
            } catch (PDOException $e) {
                $message = "เกิดข้อผิดพลาดในการนำเข้า MySQL: " . $e->getMessage() . " (โปรดตรวจสอบว่าเปิด MySQL ใน XAMPP Control Panel แล้วหรือยัง)";
                $messageType = 'error';
            }
        }
    }
}

// Check database status
$mysqlConnected = false;
$mysqlError = '';
$mysqlTables = [];
try {
    $mysqlPdo = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4", DB_USER, DB_PASS);
    $mysqlPdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $mysqlConnected = true;
    $stmt = $mysqlPdo->query("SHOW TABLES");
    while ($row = $stmt->fetch(PDO::FETCH_NUM)) {
        $tbl = $row[0];
        $countStmt = $mysqlPdo->query("SELECT COUNT(*) FROM `$tbl`");
        $rowCount = $countStmt->fetchColumn();
        $mysqlTables[$tbl] = $rowCount;
    }
} catch (PDOException $e) {
    $mysqlError = $e->getMessage();
}

$sqliteConnected = false;
$sqliteTables = [];
if (file_exists(DB_FILE)) {
    try {
        $sqlitePdo = new PDO('sqlite:' . DB_FILE);
        $sqlitePdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $sqliteConnected = true;
        $stmt = $sqlitePdo->query("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'");
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $tbl = $row['name'];
            $countStmt = $sqlitePdo->query("SELECT COUNT(*) FROM `$tbl`");
            $rowCount = $countStmt->fetchColumn();
            $sqliteTables[$tbl] = $rowCount;
        }
    } catch (PDOException $e) {
        // SQLite error
    }
}
?>
<!DOCTYPE html>
<html lang="th">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ระบบจัดการฐานข้อมูล SQL - APEX STUDIO (Shopee Mall)</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <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=Prompt:wght@300;400;500;600;700;800&family=Plus+Jakarta+Sans:wght@400;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body { font-family: 'Prompt', 'Plus Jakarta Sans', sans-serif; }
    </style>
</head>
<body class="bg-slate-950 text-slate-100 min-h-screen">
    <!-- Header -->
    <header class="border-b border-slate-800 bg-slate-900/80 backdrop-blur sticky top-0 z-50">
        <div class="max-w-6xl mx-auto px-4 py-4 flex items-center justify-between">
            <div class="flex items-center gap-3">
                <div class="w-10 h-10 rounded-xl bg-gradient-to-tr from-rose-600 to-orange-500 flex items-center justify-center text-white font-bold text-xl shadow-lg shadow-rose-600/30">
                    <i class="fa-solid fa-database"></i>
                </div>
                <div>
                    <h1 class="text-xl font-bold tracking-tight text-white flex items-center gap-2">
                        APEX STUDIO <span class="text-xs px-2 py-0.5 rounded-full bg-rose-500/20 text-rose-400 border border-rose-500/30">SQL Database Manager</span>
                    </h1>
                    <p class="text-xs text-slate-400">ระบบจัดการและติดตั้งฐานข้อมูล MySQL & SQLite</p>
                </div>
            </div>
            <div class="flex items-center gap-3">
                <a href="index.php" class="px-4 py-2 rounded-xl bg-slate-800 hover:bg-slate-700 text-slate-200 text-sm font-medium transition flex items-center gap-2 border border-slate-700">
                    <i class="fa-solid fa-store text-rose-500"></i> ไปหน้าร้านค้า
                </a>
                <a href="http://localhost/phpmyadmin" target="_blank" class="px-4 py-2 rounded-xl bg-gradient-to-r from-orange-500 to-amber-500 hover:opacity-90 text-white text-sm font-semibold shadow-lg shadow-orange-500/20 transition flex items-center gap-2">
                    <i class="fa-solid fa-server"></i> เปิด phpMyAdmin
                </a>
            </div>
        </div>
    </header>

    <main class="max-w-6xl mx-auto px-4 py-8 space-y-8">
        <?php if (!empty($message)): ?>
            <div class="p-4 rounded-2xl flex items-center gap-3 border <?php echo $messageType === 'success' ? 'bg-emerald-950/60 border-emerald-500/40 text-emerald-300' : 'bg-rose-950/60 border-rose-500/40 text-rose-300'; ?>">
                <i class="fa-solid <?php echo $messageType === 'success' ? 'fa-circle-check text-emerald-400' : 'fa-circle-exclamation text-rose-400'; ?> text-xl"></i>
                <div class="text-sm font-medium"><?php echo htmlspecialchars($message); ?></div>
            </div>
        <?php endif; ?>

        <!-- Quick Status & Import Action Banner -->
        <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
            <!-- MySQL Status Card -->
            <div class="p-6 rounded-3xl bg-slate-900/90 border border-slate-800 shadow-xl relative overflow-hidden">
                <div class="flex items-start justify-between">
                    <div>
                        <div class="text-xs font-semibold uppercase tracking-wider text-slate-400 mb-1">MySQL Database</div>
                        <div class="text-2xl font-bold text-white flex items-center gap-2">
                            apex_studio
                            <?php if ($mysqlConnected): ?>
                                <span class="w-2.5 h-2.5 rounded-full bg-emerald-500 animate-pulse"></span>
                            <?php else: ?>
                                <span class="w-2.5 h-2.5 rounded-full bg-rose-500"></span>
                            <?php endif; ?>
                        </div>
                    </div>
                    <div class="w-12 h-12 rounded-2xl <?php echo $mysqlConnected ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/20' : 'bg-rose-500/10 text-rose-400 border border-rose-500/20'; ?> flex items-center justify-center text-xl">
                        <i class="fa-solid fa-server"></i>
                    </div>
                </div>
                <div class="mt-4 pt-4 border-t border-slate-800/80 text-xs text-slate-400 space-y-1.5">
                    <div class="flex justify-between"><span>Host:</span> <span class="text-slate-200 font-mono"><?php echo DB_HOST; ?></span></div>
                    <div class="flex justify-between"><span>Username:</span> <span class="text-slate-200 font-mono"><?php echo DB_USER; ?></span></div>
                    <div class="flex justify-between"><span>Status:</span> 
                        <span class="<?php echo $mysqlConnected ? 'text-emerald-400 font-semibold' : 'text-rose-400'; ?>">
                            <?php echo $mysqlConnected ? 'พร้อมใช้งาน (' . count($mysqlTables) . ' ตาราง)' : 'ยังไม่ได้เชื่อมต่อ/ยังไม่มีฐานข้อมูล'; ?>
                        </span>
                    </div>
                </div>
            </div>

            <!-- SQLite Status Card -->
            <div class="p-6 rounded-3xl bg-slate-900/90 border border-slate-800 shadow-xl relative overflow-hidden">
                <div class="flex items-start justify-between">
                    <div>
                        <div class="text-xs font-semibold uppercase tracking-wider text-slate-400 mb-1">SQLite Database</div>
                        <div class="text-2xl font-bold text-white flex items-center gap-2">
                            database.sqlite
                            <span class="w-2.5 h-2.5 rounded-full bg-emerald-500"></span>
                        </div>
                    </div>
                    <div class="w-12 h-12 rounded-2xl bg-sky-500/10 text-sky-400 border border-sky-500/20 flex items-center justify-center text-xl">
                        <i class="fa-solid fa-file-code"></i>
                    </div>
                </div>
                <div class="mt-4 pt-4 border-t border-slate-800/80 text-xs text-slate-400 space-y-1.5">
                    <div class="flex justify-between"><span>Location:</span> <span class="text-slate-200 font-mono">data/database.sqlite</span></div>
                    <div class="flex justify-between"><span>File Size:</span> <span class="text-slate-200 font-mono"><?php echo file_exists(DB_FILE) ? round(filesize(DB_FILE) / 1024, 1) . ' KB' : '0 KB'; ?></span></div>
                    <div class="flex justify-between"><span>Status:</span> 
                        <span class="text-emerald-400 font-semibold">พร้อมใช้งาน (<?php echo count($sqliteTables); ?> ตาราง)</span>
                    </div>
                </div>
            </div>

            <!-- 1-Click Import Card -->
            <div class="p-6 rounded-3xl bg-gradient-to-br from-rose-950/40 via-slate-900 to-slate-900 border border-rose-500/30 shadow-xl flex flex-col justify-between">
                <div>
                    <div class="text-xs font-semibold uppercase tracking-wider text-rose-400 mb-1">1-Click Auto Import</div>
                    <h3 class="text-lg font-bold text-white">ติดตั้ง / นำเข้าไฟล์ SQL</h3>
                    <p class="text-xs text-slate-400 mt-1">รันไฟล์ <code class="text-rose-300 font-mono">apex_studio.sql</code> เข้า MySQL ทันทีพร้อมโครงสร้างและข้อมูลตัวอย่าง</p>
                </div>
                <form method="POST" class="mt-4">
                    <input type="hidden" name="action" value="import_sql">
                    <button type="submit" onclick="return confirm('ต้องการรันและนำเข้าไฟล์ apex_studio.sql สู่ MySQL ใช่หรือไม่?');" class="w-full py-2.5 px-4 rounded-xl bg-gradient-to-r from-rose-600 to-orange-500 hover:from-rose-500 hover:to-orange-400 text-white font-semibold text-sm shadow-lg shadow-rose-600/30 transition flex items-center justify-center gap-2">
                        <i class="fa-solid fa-bolt"></i> รัน & ติดตั้ง MySQL ทันที
                    </button>
                </form>
            </div>
        </div>

        <!-- SQL Tables Overview -->
        <div class="p-8 rounded-3xl bg-slate-900/70 border border-slate-800 shadow-2xl space-y-6">
            <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4 border-b border-slate-800 pb-5">
                <div>
                    <h2 class="text-xl font-bold text-white flex items-center gap-2">
                        <i class="fa-solid fa-table-cells text-rose-500"></i> ตารางทั้งหมดในระบบ (Database Tables)
                    </h2>
                    <p class="text-xs text-slate-400 mt-0.5">โครงสร้างตาราง 9 ตาราง รองรับระบบร้านค้าและ Shopee VIP Member Club สมบูรณ์แบบ</p>
                </div>
                <div class="flex items-center gap-2">
                    <a href="apex_studio.sql" download class="px-3 py-1.5 rounded-xl bg-slate-800 hover:bg-slate-700 text-xs font-medium text-slate-300 border border-slate-700 transition flex items-center gap-1.5">
                        <i class="fa-solid fa-download text-rose-400"></i> ดาวน์โหลด apex_studio.sql
                    </a>
                    <a href="database.sql" download class="px-3 py-1.5 rounded-xl bg-slate-800 hover:bg-slate-700 text-xs font-medium text-slate-300 border border-slate-700 transition flex items-center gap-1.5">
                        <i class="fa-solid fa-file-arrow-down text-orange-400"></i> ดาวน์โหลด database.sql
                    </a>
                </div>
            </div>

            <!-- Tables Grid -->
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                <?php
                $tableList = [
                    ['name' => 'users', 'desc' => 'ข้อมูลสมาชิก, ระดับ VIP, แต้ม, เหรียญ, รหัสผ่าน', 'icon' => 'fa-users', 'color' => 'from-rose-500/20 to-orange-500/20 text-rose-400'],
                    ['name' => 'membership_tiers', 'desc' => 'ระดับสมาชิก Classic, Silver, Gold, Platinum และสิทธิพิเศษ', 'icon' => 'fa-crown', 'color' => 'from-amber-500/20 to-yellow-500/20 text-amber-400'],
                    ['name' => 'categories', 'desc' => 'หมวดหมู่สินค้า เช่น เสื้อยืด, ฮู้ดดี้, กางเกง, หมวก', 'icon' => 'fa-layer-group', 'color' => 'from-indigo-500/20 to-violet-500/20 text-indigo-400'],
                    ['name' => 'products', 'desc' => 'รายการสินค้า, ราคา, สต็อก, สี, ไซส์, แกลเลอรีรูปภาพ', 'icon' => 'fa-shirt', 'color' => 'from-emerald-500/20 to-teal-500/20 text-emerald-400'],
                    ['name' => 'vouchers', 'desc' => 'โค้ดส่วนลด Shopee, โค้ดส่งฟรี, เงินคืน Coins', 'icon' => 'fa-ticket', 'color' => 'from-pink-500/20 to-rose-500/20 text-pink-400'],
                    ['name' => 'orders', 'desc' => 'คำสั่งซื้อ, ยอดเงิน, สลิปโอน, ที่อยู่จัดส่ง, เลขพัสดุ', 'icon' => 'fa-box', 'color' => 'from-sky-500/20 to-blue-500/20 text-sky-400'],
                    ['name' => 'order_items', 'desc' => 'รายการสินค้าแต่ละชิ้นในคำสั่งซื้อ (Relational)', 'icon' => 'fa-list-check', 'color' => 'from-purple-500/20 to-indigo-500/20 text-purple-400'],
                    ['name' => 'reviews', 'desc' => 'รีวิวจากลูกค้า, คะแนน 5 ดาว, ความคิดเห็น, รูปรีวิว', 'icon' => 'fa-star', 'color' => 'from-yellow-500/20 to-amber-500/20 text-yellow-400'],
                    ['name' => 'coin_logs', 'desc' => 'ประวัติธุรกรรมรับ/ใช้ Shopee Coins รายบุคคล', 'icon' => 'fa-coins', 'color' => 'from-orange-500/20 to-amber-500/20 text-orange-400'],
                ];

                foreach ($tableList as $tbl):
                    $mCount = $mysqlTables[$tbl['name']] ?? '-';
                    $sCount = $sqliteTables[$tbl['name']] ?? '-';
                ?>
                <div class="p-4 rounded-2xl bg-slate-950/60 border border-slate-800/80 hover:border-slate-700 transition flex flex-col justify-between">
                    <div>
                        <div class="flex items-center justify-between mb-2">
                            <div class="flex items-center gap-2">
                                <div class="w-8 h-8 rounded-lg bg-gradient-to-br <?php echo $tbl['color']; ?> flex items-center justify-center text-sm">
                                    <i class="fa-solid <?php echo $tbl['icon']; ?>"></i>
                                </div>
                                <span class="font-bold text-white font-mono text-sm"><?php echo $tbl['name']; ?></span>
                            </div>
                            <span class="text-xs px-2 py-0.5 rounded-md bg-slate-800 text-slate-300 font-mono">
                                <?php echo $mysqlConnected ? $mCount . ' แถว' : 'พร้อมใช้งาน'; ?>
                            </span>
                        </div>
                        <p class="text-xs text-slate-400 leading-relaxed"><?php echo $tbl['desc']; ?></p>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>

        <!-- How to Import Guide -->
        <div class="p-8 rounded-3xl bg-slate-900/70 border border-slate-800 shadow-2xl space-y-6">
            <h2 class="text-xl font-bold text-white flex items-center gap-2">
                <i class="fa-solid fa-circle-question text-orange-400"></i> ขั้นตอนการนำเข้าฐานข้อมูลผ่าน phpMyAdmin
            </h2>
            
            <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                <div class="p-5 rounded-2xl bg-slate-950/60 border border-slate-800 space-y-3">
                    <div class="w-8 h-8 rounded-full bg-rose-500/20 text-rose-400 font-bold flex items-center justify-center text-sm border border-rose-500/30">1</div>
                    <h3 class="font-bold text-white text-sm">เปิด XAMPP & phpMyAdmin</h3>
                    <p class="text-xs text-slate-400 leading-relaxed">
                        เปิดโปรแกรม XAMPP Control Panel กดปุ่ม <strong>Start</strong> ที่ <span class="text-rose-400 font-mono">Apache</span> และ <span class="text-rose-400 font-mono">MySQL</span> จากนั้นเข้าเบราว์เซอร์ไปที่ <a href="http://localhost/phpmyadmin" target="_blank" class="text-rose-400 underline font-mono">localhost/phpmyadmin</a>
                    </p>
                </div>

                <div class="p-5 rounded-2xl bg-slate-950/60 border border-slate-800 space-y-3">
                    <div class="w-8 h-8 rounded-full bg-orange-500/20 text-orange-400 font-bold flex items-center justify-center text-sm border border-orange-500/30">2</div>
                    <h3 class="font-bold text-white text-sm">สร้างฐานข้อมูล หรือ กด Import</h3>
                    <p class="text-xs text-slate-400 leading-relaxed">
                        กดที่เมนู <strong>Import (นำเข้า)</strong> ด้านบน แล้วกดปุ่ม <strong>Choose File</strong> เลือกไฟล์ <code class="text-orange-300 font-mono">apex_studio.sql</code> จากโฟลเดอร์โปรเจกต์
                    </p>
                </div>

                <div class="p-5 rounded-2xl bg-slate-950/60 border border-slate-800 space-y-3">
                    <div class="w-8 h-8 rounded-full bg-emerald-500/20 text-emerald-400 font-bold flex items-center justify-center text-sm border border-emerald-500/30">3</div>
                    <h3 class="font-bold text-white text-sm">กด Go (ดำเนินการ)</h3>
                    <p class="text-xs text-slate-400 leading-relaxed">
                        เลื่อนลงมาด้านล่างแล้วกดปุ่ม <strong>Go</strong> หรือ <strong>นำเข้า</strong> ระบบจะสร้างฐานข้อมูล <code class="text-emerald-300 font-mono">apex_studio</code> พร้อมทุกตารางและข้อมูลตัวอย่างทันที 100%
                    </p>
                </div>
            </div>
        </div>
    </main>

    <footer class="border-t border-slate-800 py-6 text-center text-xs text-slate-500">
        APEX STUDIO &copy; 2026 - ระบบฐานข้อมูลมาตรฐาน MySQL & SQLite สำหรับร้านค้าออนไลน์และสมาชิก VIP
    </footer>
</body>
</html>
