<?php
require_once 'config.php';

// Allow seller check (if not seller or not logged in, redirect)
if (!isset($_SESSION['user_id']) || ($_SESSION['user_role'] ?? 'customer') !== 'seller') {
    $_SESSION['login_error'] = "กรุณาเข้าสู่ระบบด้วยบัญชีผู้ขายสินค้าเพื่อใช้งานหน้านี้";
    header("Location: login.php");
    exit;
}

$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $price = floatval($_POST['price'] ?? 0);
    $size = trim($_POST['size'] ?? 'M');
    $stock = intval($_POST['stock'] ?? 0);
    $image_url = trim($_POST['image_url'] ?? '');

    // Default placeholder image if empty
    if (empty($image_url)) {
        $image_url = 'https://images.unsplash.com/photo-1521572267360-ee0c2909d518?w=500&auto=format&fit=crop&q=80';
    }

    if (empty($name) || $price <= 0 || $stock < 0) {
        $error = "กรุณากรอกชื่อสินค้า ราคา และจำนวนสต็อกให้ถูกต้อง";
    } else {
        try {
            $stmt = $pdo->prepare("INSERT INTO products (name, description, price, size, stock, image_url) VALUES (?, ?, ?, ?, ?, ?)");
            if ($stmt->execute([$name, $description, $price, $size, $stock, $image_url])) {
                $success = "เพิ่มสินค้า '$name' เรียบร้อยแล้ว!";
            } else {
                $error = "เกิดข้อผิดพลาดในการบันทึกสินค้า";
            }
        } catch (PDOException $e) {
            $error = "เกิดข้อผิดพลาด: " . $e->getMessage();
        }
    }
}

// Fetch all existing products
$products = $pdo->query("SELECT * FROM products ORDER BY id DESC")->fetchAll();
?>
<!DOCTYPE html>
<html lang="th">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>จัดการสินค้า (สำหรับผู้ขาย) - วิทยาลัยเทคนิคเชียงใหม่</title>
    <!-- Google Fonts -->
    <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=Outfit:wght@300;400;500;600;700&family=Sarabun:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Bootstrap Icons -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.2/font/bootstrap-icons.min.css">
    
    <style>
        :root {
            --primary-color: #1a1a1a;
            --accent-color: #8f8270;
            --bg-color: #faf9f6;
            --card-bg: #ffffff;
            --font-display: 'Outfit', 'Sarabun', sans-serif;
        }

        body {
            font-family: var(--font-display);
            background-color: var(--bg-color);
            color: var(--primary-color);
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }

        .navbar {
            background-color: rgba(255, 255, 255, 0.85);
            backdrop-filter: blur(10px);
            border-bottom: 1px solid rgba(0, 0, 0, 0.05);
        }

        .seller-card {
            background-color: var(--card-bg);
            border: none;
            border-radius: 16px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.03);
            padding: 30px;
        }

        .btn-dark-custom {
            background-color: var(--primary-color);
            color: #ffffff;
            border: 1px solid var(--primary-color);
            border-radius: 6px;
            font-weight: 500;
            padding: 10px 24px;
            letter-spacing: 0.5px;
            transition: all 0.2s ease;
        }
        .btn-dark-custom:hover {
            background-color: var(--accent-color);
            border-color: var(--accent-color);
            color: white;
        }
    </style>
    <!-- Custom Theme & Dark Mode CSS -->
    <link rel="stylesheet" href="assets/css/style.css">
    <script src="assets/js/theme-toggle.js"></script>
</head>
<body>

    <!-- Header Navbar -->
    <nav class="navbar navbar-expand-lg sticky-top navbar-light">
        <div class="container">
            <a class="navbar-brand d-flex align-items-center gap-2" href="index.php">
                <img src="assets/images/logo.png" alt="CMTC Logo" style="height: 42px; width: auto;">
                <div class="d-flex flex-column" style="line-height: 1.2;">
                    <span class="fs-6 fw-bold">วิทยาลัยเทคนิคเชียงใหม่</span>
                    <span class="small text-muted" style="font-size: 0.75rem; letter-spacing: 1px;">MINIMALIST CLOSET</span>
                </div>
            </a>
            <div class="ms-auto d-flex align-items-center gap-2">
                <button type="button" class="theme-toggle-btn me-2" id="themeToggleBtn" title="เปลี่ยนธีม (Light/Dark)">
                    <i class="bi bi-moon-stars-fill" id="themeIcon"></i>
                </button>

                <div class="dropdown">
                    <button class="btn btn-outline-dark btn-sm dropdown-toggle d-flex align-items-center gap-2 px-3 py-1.5 rounded-pill" type="button" data-bs-toggle="dropdown" aria-expanded="false">
                        <i class="bi bi-shop fs-5 text-primary"></i>
                        <span><?= htmlspecialchars($_SESSION['user_name']) ?> (ผู้ขาย)</span>
                    </button>
                    <ul class="dropdown-menu dropdown-menu-end shadow-sm border-0 mt-2">
                        <li><a class="dropdown-item small text-danger" href="logout.php"><i class="bi bi-box-arrow-right me-2"></i>ออกจากระบบ</a></li>
                    </ul>
                </div>
            </div>
        </div>
    </nav>

    <!-- Main Content -->
    <main class="container py-5 my-3">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h2 class="fw-bold mb-1"><i class="bi bi-plus-circle me-2"></i>ระบบเพิ่มและจัดการสินค้า (สำหรับผู้ขาย)</h2>
                <p class="text-muted small">เพิ่มรายการสินค้าใหม่เข้าสู่ระบบ เพื่อวางจำหน่ายบนหน้าเว็บไซต์</p>
            </div>
            <a href="index.php" class="btn btn-outline-dark btn-sm rounded-pill px-3">
                <i class="bi bi-eye me-1"></i> ดูหน้าหน้าร้าน
            </a>
        </div>

        <div class="row g-4">
            <!-- Form Add Product -->
            <div class="col-lg-5">
                <div class="seller-card">
                    <h4 class="fw-bold mb-4 pb-2 border-bottom"><i class="bi bi-box-seam me-2"></i>ฟอร์มเพิ่มสินค้าใหม่</h4>

                    <?php if ($success): ?>
                        <div class="alert alert-success border-0 small py-2.5 mb-4" role="alert">
                            <i class="bi bi-check-circle-fill me-2"></i><?= htmlspecialchars($success) ?>
                        </div>
                    <?php endif; ?>

                    <?php if ($error): ?>
                        <div class="alert alert-danger border-0 small py-2.5 mb-4" role="alert">
                            <i class="bi bi-exclamation-triangle-fill me-2"></i><?= htmlspecialchars($error) ?>
                        </div>
                    <?php endif; ?>

                    <form method="POST" action="add-product.php">
                        <div class="mb-3">
                            <label class="form-label small fw-semibold">ชื่อสินค้า <span class="text-danger">*</span></label>
                            <input type="text" name="name" class="form-control" placeholder="เช่น เสื้อยืดคอกลม Minimal" required>
                        </div>

                        <div class="mb-3">
                            <label class="form-label small fw-semibold">รายละเอียดสินค้า</label>
                            <textarea name="description" class="form-control" rows="3" placeholder="ระบุรายละเอียด วัสดุ ทรงเสื้อ ฯลฯ"></textarea>
                        </div>

                        <div class="row">
                            <div class="col-6 mb-3">
                                <label class="form-label small fw-semibold">ราคา (บาท) <span class="text-danger">*</span></label>
                                <input type="number" step="0.01" name="price" class="form-control" placeholder="590.00" required>
                            </div>
                            <div class="col-6 mb-3">
                                <label class="form-label small fw-semibold">ไซส์ <span class="text-danger">*</span></label>
                                <select name="size" class="form-select" required>
                                    <option value="S">S</option>
                                    <option value="M" selected>M</option>
                                    <option value="L">L</option>
                                    <option value="XL">XL</option>
                                    <option value="Free Size">Free Size</option>
                                </select>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label class="form-label small fw-semibold">จำนวนสต็อก (ชิ้น) <span class="text-danger">*</span></label>
                            <input type="number" name="stock" class="form-control" value="10" min="0" required>
                        </div>

                        <div class="mb-4">
                            <label class="form-label small fw-semibold">รูปภาพสินค้า (URL Image)</label>
                            <input type="url" name="image_url" class="form-control" placeholder="https://images.unsplash.com/...">
                            <div class="form-text small text-muted">เว้นว่างไว้หากต้องการใช้รูปภาพเริ่มต้นของระบบ</div>
                        </div>

                        <button type="submit" class="btn btn-dark-custom w-100 py-2.5">
                            <i class="bi bi-cloud-upload me-1"></i> บันทึกและเพิ่มสินค้า
                        </button>
                    </form>
                </div>
            </div>

            <!-- Existing Products List -->
            <div class="col-lg-7">
                <div class="seller-card">
                    <h4 class="fw-bold mb-4 pb-2 border-bottom"><i class="bi bi-list-stars me-2"></i>รายการสินค้าทั้งหมดในระบบ (<?= count($products) ?> รายการ)</h4>

                    <div class="table-responsive">
                        <table class="table table-hover align-middle small">
                            <thead>
                                <tr class="table-light">
                                    <th>รูป</th>
                                    <th>ชื่อสินค้า</th>
                                    <th>ไซส์</th>
                                    <th>ราคา</th>
                                    <th>สต็อก</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($products as $item): ?>
                                    <tr>
                                        <td>
                                            <img src="<?= htmlspecialchars($item['image_url']) ?>" alt="Product" style="width: 45px; height: 45px; object-fit: cover; border-radius: 6px;">
                                        </td>
                                        <td>
                                            <div class="fw-semibold"><?= htmlspecialchars($item['name']) ?></div>
                                            <small class="text-muted d-inline-block text-truncate" style="max-width: 180px;"><?= htmlspecialchars($item['description']) ?></small>
                                        </td>
                                        <td><span class="badge bg-secondary"><?= htmlspecialchars($item['size']) ?></span></td>
                                        <td class="fw-bold">฿<?= number_format($item['price'], 2) ?></td>
                                        <td>
                                            <?php if ($item['stock'] > 5): ?>
                                                <span class="badge bg-success"><?= $item['stock'] ?> ชิ้น</span>
                                            <?php elseif ($item['stock'] > 0): ?>
                                                <span class="badge bg-warning text-dark"><?= $item['stock'] ?> ชิ้น</span>
                                            <?php else: ?>
                                                <span class="badge bg-danger">สินค้าหมด</span>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </main>

    <!-- Footer -->
    <footer class="bg-white border-top py-4 text-center mt-auto">
        <div class="container">
            <p class="mb-1 text-muted">&copy; 2026 วิทยาลัยเทคนิคเชียงใหม่ Minimalist Closet.</p>
        </div>
    </footer>

    <!-- Bootstrap 5 JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
