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

// ระบบตรวจสอบสิทธิ์ (Access Control): อนุญาตเฉพาะผู้ขาย (Seller) หรือ ผู้ดูแลระบบ (Admin)
if (!isset($_SESSION['is_logged_in']) || $_SESSION['is_logged_in'] !== true || !in_array($_SESSION['user_role'], ['seller', 'admin'])) {
    header('Location: login.php');
    exit;
}

$sellerId = $_SESSION['user_id'];
$userRole = $_SESSION['user_role'];
$alertMessage = "";

// 1. ค้นหาร้านค้าของผู้ขายคนนี้
try {
    if ($userRole === 'admin') {
        // แอดมินดูภาพรวมร้านค้าแรก หรือร้านทั้งหมดได้
        $shopId = 2; // ตัวแทนร้านแฟชั่นเสื้อผ้า
        $shopName = "VogueThread Boutique (Admin Mode)";
    } else {
        $stmtShop = $pdo->prepare("SELECT id, name FROM shops WHERE seller_id = ?");
        $stmtShop->execute([$sellerId]);
        $shop = $stmtShop->fetch();
        
        if ($shop) {
            $shopId = $shop['id'];
            $shopName = $shop['name'];
        } else {
            // หากยังไม่มีร้านค้า ให้สมัครออโต้
            $stmtInsertShop = $pdo->prepare("INSERT INTO shops (seller_id, name, description, status) VALUES (?, ?, ?, 'approved')");
            $stmtInsertShop->execute([$sellerId, 'ร้านค้าของ ' . $_SESSION['username'], 'คำอธิบายร้านค้าแฟชั่นเสื้อผ้าเริ่มต้น']);
            $shopId = $pdo->lastInsertId();
            $shopName = 'ร้านค้าของ ' . $_SESSION['username'];
        }
    }
} catch (PDOException $e) {
    die("เชื่อมต่อร้านค้าผิดพลาด: " . $e->getMessage());
}

// 2. จัดการแก้ไขสถานะจัดส่ง (Shipping Status Update)
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_status'])) {
    $orderId = (int)$_POST['order_id'];
    $newStatus = $_POST['shipping_status'];
    
    try {
        $stmtUpdate = $pdo->prepare("UPDATE orders SET status = ? WHERE id = ?");
        $stmtUpdate->execute([$newStatus, $orderId]);
        $alertMessage = "ปรับเปลี่ยนสถานะการสั่งซื้อออเดอร์ #ORD-{$orderId} เป็น '{$newStatus}' เรียบร้อยแล้ว!";
    } catch (PDOException $e) {
        $alertMessage = "เกิดข้อผิดพลาดในการอัปเดตสถานะ: " . $e->getMessage();
    }
}

// 3. คำนวณสถิติยอดขายและร้านค้าแบบเรียลไทม์จาก SQLite
try {
    // ยอดขายรวม
    $stmtSales = $pdo->prepare("SELECT SUM(total_price) FROM orders WHERE shop_id = ? AND status != 'Cancelled'");
    $stmtSales->execute([$shopId]);
    $totalSales = $stmtSales->fetchColumn() ?: 0;

    // ออเดอร์ทั้งหมด
    $stmtOrdersCount = $pdo->prepare("SELECT COUNT(*) FROM orders WHERE shop_id = ?");
    $stmtOrdersCount->execute([$shopId]);
    $totalOrders = $stmtOrdersCount->fetchColumn();

    // รายการสินค้าพร้อมขาย
    $stmtProductsCount = $pdo->prepare("SELECT COUNT(*) FROM products WHERE shop_id = ?");
    $stmtProductsCount->execute([$shopId]);
    $activeProducts = $stmtProductsCount->fetchColumn();

    // รายการสั่งซื้อของร้านนี้
    $stmtOrdersList = $pdo->prepare("
        SELECT orders.*, users.name AS buyer_name, users.email AS buyer_email 
        FROM orders 
        JOIN users ON orders.user_id = users.id
        WHERE orders.shop_id = ? 
        ORDER BY orders.id DESC
    ");
    $stmtOrdersList->execute([$shopId]);
    $sellerOrders = $stmtOrdersList->fetchAll();

} catch (PDOException $e) {
    die("เกิดข้อผิดพลาดในการดึงข้อมูลแดชบอร์ด: " . $e->getMessage());
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Seller Centre - <?= htmlspecialchars($shopName) ?></title>
    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <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;
            background-color: #f8fafc;
        }
    </style>
</head>
<body class="bg-slate-50 text-slate-900 min-h-screen">

    <!-- Top Navbar -->
    <nav class="bg-[#ee4d2d] text-white py-3.5 px-6 shadow-md flex items-center justify-between sticky top-0 z-40">
        <div class="flex items-center gap-3">
            <a href="index.php" class="text-xl font-bold flex items-center gap-1.5 hover:scale-[1.02] transform transition">
                <svg class="w-6 h-6 fill-current" viewBox="0 0 24 24">
                    <path d="M12 2A10 10 0 0 0 2 12a10 10 0 0 0 10 10 10 10 0 0 0 10-10A10 10 0 0 0 12 2zm1 14.5h-2v-2h2v2zm0-4h-2V7.5h2V12.5z"/>
                </svg>
                <span>Shopee<span class="font-normal text-orange-200">Seller Centre</span></span>
            </a>
            <span class="bg-orange-700/60 border border-orange-500 text-xs px-2.5 py-0.5 rounded text-orange-100 hidden sm:inline">
                Shop: <?= htmlspecialchars($shopName) ?>
            </span>
        </div>
        <div class="flex items-center gap-4">
            <a href="index.php" class="text-xs font-semibold hover:underline text-orange-100 hover:text-white transition">
                ← Go to Marketplace
            </a>
        </div>
    </nav>

    <div class="max-w-6xl mx-auto px-4 py-8">
        
        <!-- Welcome banner -->
        <div class="mb-8 flex flex-col md:flex-row md:items-center justify-between gap-4 bg-white p-6 rounded-3xl shadow-sm border border-slate-100">
            <div>
                <h1 class="text-xl font-extrabold text-slate-800">Welcome Back, <?= htmlspecialchars($_SESSION['username']) ?>!</h1>
                <p class="text-slate-500 text-xs mt-1">Here is a quick overview of your merchant store performance for today.</p>
            </div>
            <div class="text-xs bg-slate-100 text-slate-600 px-3.5 py-1.5 rounded-xl font-bold self-start md:self-auto">
                Merchant Live Monitor
            </div>
        </div>

        <!-- Success Toast Alert -->
        <?php if ($alertMessage): ?>
            <div id="toast" class="mb-6 animate__animated animate__fadeIn">
                <div class="bg-emerald-500 text-white px-4 py-3 rounded-2xl relative flex justify-between items-center shadow" role="alert">
                    <span class="text-xs font-bold"><?= htmlspecialchars($alertMessage) ?></span>
                    <button onclick="document.getElementById('toast').remove();" class="font-bold hover:text-slate-200 text-lg">&times;</button>
                </div>
            </div>
        <?php endif; ?>

        <!-- Summary Cards Row -->
        <div class="grid grid-cols-1 sm:grid-cols-3 gap-6 mb-8">
            <!-- Card 1: Revenue -->
            <div class="bg-white rounded-3xl p-6 shadow-sm border border-slate-100 flex items-center justify-between">
                <div>
                    <span class="text-slate-400 text-xs font-bold uppercase tracking-wider block">Total Sales</span>
                    <span class="text-2xl font-black text-slate-800 mt-1 block">฿<?= number_format($totalSales, 2) ?></span>
                </div>
                <div class="bg-green-50 p-3.5 rounded-2xl text-green-500">
                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2.5" stroke="currentColor" class="w-7 h-7">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M12 6v12m-3-2.818.752.376a5.002 5.002 0 0 0 4.496 0L15 15.182m-6-1.996.752.376a5.002 5.002 0 0 0 4.496 0l.752-.376M12 3v3m0 12v3" />
                    </svg>
                </div>
            </div>

            <!-- Card 2: Orders -->
            <div class="bg-white rounded-3xl p-6 shadow-sm border border-slate-100 flex items-center justify-between">
                <div>
                    <span class="text-slate-400 text-xs font-bold uppercase tracking-wider block">Total Orders</span>
                    <span class="text-2xl font-black text-slate-800 mt-1 block"><?= $totalOrders ?></span>
                </div>
                <div class="bg-blue-50 p-3.5 rounded-2xl text-blue-500">
                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2.5" stroke="currentColor" class="w-7 h-7">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M15.75 10.5V6a3.75 3.75 0 1 0-7.5 0v4.5m11.356-1.993 1.263 12c.07.665-.45 1.243-1.119 1.243H4.25a1.125 1.125 0 0 1-1.12-1.243l1.264-12A1.125 1.125 0 0 1 5.513 7.5h12.974c.576 0 1.059.435 1.119 1.007ZM8.625 10.5a.375.375 0 1 1-.75 0 .375.375 0 0 1 .75 0Zm7.5 0a.375.375 0 1 1-.75 0 .375.375 0 0 1 .75 0Z" />
                    </svg>
                </div>
            </div>

            <!-- Card 3: Active Products -->
            <div class="bg-white rounded-3xl p-6 shadow-sm border border-slate-100 flex items-center justify-between">
                <div>
                    <span class="text-slate-400 text-xs font-bold uppercase tracking-wider block">Active Products</span>
                    <span class="text-2xl font-black text-slate-800 mt-1 block"><?= $activeProducts ?></span>
                </div>
                <div class="bg-orange-50 p-3.5 rounded-2xl text-[#ee4d2d]">
                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2.5" stroke="currentColor" class="w-7 h-7">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M20.25 7.5l-.625 10.632a2.25 2.25 0 01-2.247 2.118H6.622a2.25 2.25 0 01-2.247-2.118L3.75 7.5M10 11.25h4M3.375 7.5h17.25c.621 0 1.125-.504 1.125-1.125v-1.5c0-.621-.504-1.125-1.125-1.125H3.375c-.621 0-1.125.504-1.125 1.125v1.5c0 .621.504 1.125 1.125 1.125z" />
                    </svg>
                </div>
            </div>
        </div>

        <!-- Order Management Section -->
        <div class="bg-white rounded-3xl shadow-sm border border-slate-100 overflow-hidden">
            <div class="px-6 py-4.5 border-b border-slate-100 flex justify-between items-center">
                <h2 class="text-base font-extrabold text-slate-850">Order Management</h2>
                <span class="text-[10px] text-slate-400 font-bold uppercase tracking-wide">Live Database Records</span>
            </div>

            <div class="overflow-x-auto">
                <table class="w-full text-left border-collapse">
                    <thead>
                        <tr class="bg-slate-50 text-slate-500 text-[11px] font-bold uppercase tracking-wider border-b border-slate-100">
                            <th class="px-6 py-3.5">Order ID</th>
                            <th class="px-6 py-3.5">Customer</th>
                            <th class="px-6 py-3.5">Product Name Details</th>
                            <th class="px-6 py-3.5 text-center">Quantity</th>
                            <th class="px-6 py-3.5">Total Price</th>
                            <th class="px-6 py-3.5">Payment</th>
                            <th class="px-6 py-3.5">Status</th>
                            <th class="px-6 py-3.5 text-right">Actions</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-100 text-slate-700 text-xs">
                        <?php if (empty($sellerOrders)): ?>
                            <tr>
                                <td colspan="8" class="text-center py-10 text-slate-400 font-semibold">No order transactions found for this merchant.</td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($sellerOrders as $order): ?>
                                <tr class="hover:bg-slate-50/50 transition">
                                    <td class="px-6 py-4 font-mono font-bold text-slate-450">#ORD-<?= $order['id'] ?></td>
                                    <td class="px-6 py-4 font-semibold text-slate-800">
                                        <div><?= htmlspecialchars($order['buyer_name']) ?></div>
                                        <div class="text-[10px] text-slate-400 font-normal"><?= htmlspecialchars($order['buyer_email']) ?></div>
                                    </td>
                                    <td class="px-6 py-4 font-semibold text-slate-800"><?= htmlspecialchars($order['product_name']) ?></td>
                                    <td class="px-6 py-4 text-center font-bold text-slate-600"><?= $order['quantity'] ?></td>
                                    <td class="px-6 py-4 font-black text-slate-900">฿<?= number_format($order['total_price']) ?></td>
                                    <td class="px-6 py-4 font-semibold text-blue-600"><?= htmlspecialchars($order['payment_method'] ?? 'PromptPay') ?></td>
                                    <td class="px-6 py-4">
                                        <?php 
                                        $statusColor = 'bg-gray-100 text-gray-700';
                                        if ($order['status'] === 'Shipped') $statusColor = 'bg-blue-50 text-blue-700 border border-blue-100';
                                        if ($order['status'] === 'Delivered') $statusColor = 'bg-green-50 text-green-700 border border-green-100';
                                        if ($order['status'] === 'Pending') $statusColor = 'bg-amber-50 text-amber-700 border border-amber-100';
                                        if ($order['status'] === 'Cancelled') $statusColor = 'bg-red-50 text-red-700 border border-red-100';
                                        ?>
                                        <span class="inline-block px-2.5 py-1 rounded-full text-[10px] font-bold <?= $statusColor ?>">
                                            <?= htmlspecialchars($order['status']) ?>
                                        </span>
                                    </td>
                                    <td class="px-6 py-4 text-right">
                                        <form method="POST" action="seller_dashboard.php" class="inline-flex items-center gap-2">
                                            <input type="hidden" name="order_id" value="<?= $order['id'] ?>">
                                            <select name="shipping_status" class="bg-white border border-slate-200 rounded-lg text-[10px] font-bold px-2 py-1.5 focus:outline-none focus:ring-1 focus:ring-[#ee4d2d]">
                                                <option value="Pending" <?= $order['status'] == 'Pending' ? 'selected' : '' ?>>Pending</option>
                                                <option value="Shipped" <?= $order['status'] == 'Shipped' ? 'selected' : '' ?>>Shipped</option>
                                                <option value="Delivered" <?= $order['status'] == 'Delivered' ? 'selected' : '' ?>>Delivered</option>
                                                <option value="Cancelled" <?= $order['status'] == 'Cancelled' ? 'selected' : '' ?>>Cancelled</option>
                                            </select>
                                            <button type="submit" name="update_status" class="bg-slate-800 hover:bg-slate-900 text-white text-[10px] font-bold px-3 py-1.5 rounded-lg transition shadow-sm cursor-pointer">
                                                Update
                                            </button>
                                        </form>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

    </div>

    <!-- Footer -->
    <footer class="bg-white border-t border-slate-100 mt-20 py-8 text-center text-xs text-gray-500">
        <p>&copy; 2026 Shopee Clone. Pair programmed with Antigravity.</p>
    </footer>

</body>
</html>
