<?php
require_once 'config.php';

// Fetch all products to group them by name
try {
    $stmt = $pdo->query("SELECT * FROM products ORDER BY name ASC, size ASC");
    $all_products = $stmt->fetchAll();
} catch (PDOException $e) {
    $all_products = [];
}

// Group products by name for elegant variant selection
$grouped_products = [];
foreach ($all_products as $product) {
    $name = $product['name'];
    if (!isset($grouped_products[$name])) {
        $grouped_products[$name] = [
            'name' => $product['name'],
            'description' => $product['description'],
            'image_url' => $product['image_url'],
            'variants' => []
        ];
    }
    $grouped_products[$name]['variants'][] = [
        'id' => $product['id'],
        'price' => $product['price'],
        'size' => $product['size'],
        'stock' => $product['stock']
    ];
}

// Handle Add to Cart action
$alert_message = '';
$alert_type = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add_to_cart') {
    $product_id = filter_input(INPUT_POST, 'product_id', FILTER_VALIDATE_INT);
    $quantity = filter_input(INPUT_POST, 'quantity', FILTER_VALIDATE_INT);

    if ($product_id && $quantity && $quantity > 0) {
        // Fetch product to verify stock
        $stmt = $pdo->prepare("SELECT * FROM products WHERE id = ?");
        $stmt->execute([$product_id]);
        $product = $stmt->fetch();

        if ($product) {
            // Calculate total quantity already in cart
            $current_in_cart = isset($_SESSION['cart'][$product_id]) ? $_SESSION['cart'][$product_id] : 0;
            $new_quantity = $current_in_cart + $quantity;

            if ($new_quantity <= $product['stock']) {
                $_SESSION['cart'][$product_id] = $new_quantity;
                $alert_message = "เพิ่ม " . htmlspecialchars($product['name']) . " (ไซส์ " . htmlspecialchars($product['size']) . ") ลงตะกร้าเรียบร้อยแล้ว";
                $alert_type = "success";
            } else {
                $alert_message = "ไม่สามารถเพิ่มสินค้าได้ เนื่องจากสต็อกมีไม่เพียงพอ (คงเหลือ " . $product['stock'] . " ชิ้น)";
                $alert_type = "danger";
            }
        } else {
            $alert_message = "ไม่พบข้อมูลสินค้า";
            $alert_type = "danger";
        }
    }
}

// Calculate total cart items count
$cart_count = 0;
if (isset($_SESSION['cart'])) {
    foreach ($_SESSION['cart'] as $qty) {
        $cart_count += $qty;
    }
}
?>
<!DOCTYPE html>
<html lang="th">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Minimalist Closet - ระบบจองซื้อเสื้อผ้าออนไลน์</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;
            --text-muted: #757575;
            --font-display: 'Outfit', 'Sarabun', sans-serif;
        }

        body {
            font-family: var(--font-display);
            background-color: var(--bg-color);
            color: var(--primary-color);
            font-weight: 400;
        }

        /* Navbar Styling */
        .navbar {
            background-color: rgba(255, 255, 255, 0.85);
            backdrop-filter: blur(10px);
            border-bottom: 1px solid rgba(0, 0, 0, 0.05);
            transition: all 0.3s ease;
        }
        .navbar-brand {
            font-weight: 700;
            letter-spacing: 2px;
            color: var(--primary-color) !important;
            font-size: 1.5rem;
        }
        .nav-link {
            font-weight: 500;
            color: var(--primary-color) !important;
            letter-spacing: 1px;
            transition: color 0.2s ease;
        }
        .nav-link:hover {
            color: var(--accent-color) !important;
        }

        /* Hero Section */
        .hero-section {
            background: linear-gradient(135deg, #f3f0ea 0%, #e6e1d6 100%);
            padding: 100px 0;
            border-bottom: 1px solid rgba(0,0,0,0.05);
            margin-bottom: 60px;
        }
        .hero-title {
            font-size: 3.5rem;
            font-weight: 700;
            letter-spacing: -1px;
            line-height: 1.15;
        }
        .hero-subtitle {
            font-size: 1.15rem;
            color: var(--text-muted);
            font-weight: 300;
            max-width: 600px;
        }

        /* Product Cards */
        .product-card {
            background-color: var(--card-bg);
            border: none;
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 4px 20px rgba(0,0,0,0.02);
            transition: transform 0.3s ease, box-shadow 0.3s ease;
            height: 100%;
            display: flex;
            flex-direction: column;
        }
        .product-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 30px rgba(0,0,0,0.08);
        }
        .product-img-wrapper {
            position: relative;
            padding-top: 120%; /* 5:6 Aspect Ratio */
            overflow: hidden;
            background-color: #f5f5f5;
        }
        .product-img {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            object-fit: cover;
            transition: transform 0.5s ease;
        }
        .product-card:hover .product-img {
            transform: scale(1.05);
        }
        .product-info {
            padding: 20px;
            display: flex;
            flex-direction: column;
            flex-grow: 1;
        }
        .product-title {
            font-size: 1.15rem;
            font-weight: 600;
            margin-bottom: 8px;
            letter-spacing: 0.5px;
        }
        .product-description {
            font-size: 0.9rem;
            color: var(--text-muted);
            margin-bottom: 15px;
            line-height: 1.5;
            flex-grow: 1;
        }
        .price-badge {
            font-size: 1.25rem;
            font-weight: 700;
            color: var(--primary-color);
        }

        /* Custom Inputs & Buttons */
        .btn-dark-custom {
            background-color: var(--primary-color);
            color: #ffffff;
            border: 1px solid var(--primary-color);
            border-radius: 6px;
            font-weight: 500;
            padding: 10px 20px;
            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;
        }
        .form-select-custom, .form-control-custom {
            border: 1px solid #e0e0e0;
            border-radius: 6px;
            padding: 8px 12px;
            font-size: 0.9rem;
            outline: none;
            transition: border-color 0.2s ease;
        }
        .form-select-custom:focus, .form-control-custom:focus {
            border-color: var(--accent-color);
            box-shadow: none;
        }

        /* Badge count */
        .badge-cart {
            background-color: var(--accent-color);
            color: white;
            font-size: 0.75rem;
            padding: 4px 7px;
            border-radius: 50%;
            position: absolute;
            top: 2px;
            right: -2px;
        }
    </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>

                <a href="cart.php" class="nav-link position-relative px-3 me-2">
                    <i class="bi bi-bag fs-4"></i>
                    <?php if ($cart_count > 0): ?>
                        <span class="badge-cart"><?= $cart_count ?></span>
                    <?php endif; ?>
                </a>

                <?php if (isset($_SESSION['user_id'])): ?>
                    <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-person-circle fs-5"></i>
                            <span><?= htmlspecialchars($_SESSION['user_name']) ?></span>
                        </button>
                        <ul class="dropdown-menu dropdown-menu-end shadow-sm border-0 mt-2">
                            <?php if (($_SESSION['user_role'] ?? 'customer') === 'seller'): ?>
                                <li><a class="dropdown-item small text-primary fw-semibold" href="add-product.php"><i class="bi bi-plus-circle me-2"></i>จัดการ/เพิ่มสินค้า (ผู้ขาย)</a></li>
                                <li><hr class="dropdown-divider"></li>
                            <?php endif; ?>
                            <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>
                <?php else: ?>
                    <a href="login.php" class="btn btn-outline-dark btn-sm px-3 py-1.5 rounded-pill">เข้าสู่ระบบ</a>
                    <a href="register.php" class="btn btn-dark btn-sm px-3 py-1.5 rounded-pill">สมัครสมาชิก</a>
                <?php endif; ?>
            </div>
        </div>
    </nav>

    <!-- Hero Section -->
    <header class="hero-section">
        <div class="container">
            <div class="row align-items-center">
                <div class="col-lg-7">
                    <span class="text-uppercase text-muted tracking-wider fs-7 fw-semibold mb-2 d-inline-block">New Arrival 2026</span>
                    <h1 class="hero-title mb-3 text-uppercase">Elegance In Simplicity</h1>
                    <p class="hero-subtitle mb-4">
                        ค้นพบเสื้อผ้าแฟชั่นสไตล์มินิมอลที่ออกแบบมาอย่างพิถีพิถัน ตัดเย็บด้วยวัสดุพรีเมียม สวมใส่สบายและดูดีได้ในทุกวัน
                    </p>
                    <a href="#collection" class="btn-dark-custom px-4 py-2.5">เลือกซื้อคอลเลคชัน</a>
                </div>
            </div>
        </div>
    </header>

    <!-- Main Content -->
    <main class="container mb-5" id="collection">
        <!-- Toast Notification / Alert -->
        <?php if (!empty($alert_message)): ?>
            <div class="alert alert-<?= $alert_type ?> alert-dismissible fade show border-0 shadow-sm mb-4 rounded-3" role="alert">
                <div class="d-flex align-items-center">
                    <i class="bi <?= $alert_type === 'success' ? 'bi-check-circle-fill' : 'bi-exclamation-triangle-fill' ?> me-2 fs-5"></i>
                    <div><?= $alert_message ?></div>
                </div>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>

        <div class="row mb-4">
            <div class="col">
                <h2 class="h3 fw-semibold text-uppercase mb-1">Our Collection</h2>
                <p class="text-muted">รายการสินค้าทั้งหมด</p>
            </div>
        </div>

        <!-- Products Grid -->
        <div class="row g-4">
            <?php if (empty($grouped_products)): ?>
                <div class="col-12 text-center py-5">
                    <i class="bi bi-inbox fs-1 text-muted"></i>
                    <p class="mt-3 text-muted">ขณะนี้ยังไม่มีสินค้าในร้านค้า</p>
                </div>
            <?php else: ?>
                <?php foreach ($grouped_products as $product_name => $product_data): ?>
                    <?php 
                        // Default to the first variant
                        $first_variant = $product_data['variants'][0];
                    ?>
                    <div class="col-12 col-md-6 col-lg-4">
                        <div class="product-card">
                            <div class="product-img-wrapper">
                                <img src="<?= htmlspecialchars($product_data['image_url']) ?>" alt="<?= htmlspecialchars($product_name) ?>" class="product-img">
                            </div>
                            <div class="product-info">
                                <h3 class="product-title"><?= htmlspecialchars($product_name) ?></h3>
                                <p class="product-description"><?= htmlspecialchars($product_data['description']) ?></p>
                                
                                <form action="index.php#collection" method="POST" class="mt-auto">
                                    <input type="hidden" name="action" value="add_to_cart">
                                    
                                    <!-- Dynamic product variant selection -->
                                    <input type="hidden" name="product_id" id="prod-id-<?= md5($product_name) ?>" value="<?= $first_variant['id'] ?>">

                                    <div class="row g-2 mb-3">
                                        <!-- Size Selector -->
                                        <div class="col-6">
                                            <label class="form-label text-muted fs-8 mb-1">ไซส์</label>
                                            <select class="form-select form-select-custom w-100" 
                                                    onchange="updateVariant('<?= md5($product_name) ?>', this)">
                                                <?php foreach ($product_data['variants'] as $variant): ?>
                                                    <option value="<?= $variant['id'] ?>" 
                                                            data-price="<?= number_format($variant['price'], 2) ?>"
                                                            data-stock="<?= $variant['stock'] ?>">
                                                        <?= htmlspecialchars($variant['size']) ?>
                                                    </option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                        <!-- Quantity Selector -->
                                        <div class="col-6">
                                            <label class="form-label text-muted fs-8 mb-1">จำนวน</label>
                                            <input type="number" name="quantity" class="form-control form-control-custom w-100" value="1" min="1" max="<?= $first_variant['stock'] ?>" id="qty-input-<?= md5($product_name) ?>">
                                        </div>
                                    </div>

                                    <div class="d-flex align-items-center justify-content-between pt-2 border-top">
                                        <div>
                                            <span class="price-badge" id="price-display-<?= md5($product_name) ?>">฿<?= number_format($first_variant['price'], 2) ?></span>
                                            <div class="text-muted fs-8 mt-0.5">
                                                คงเหลือ: <span id="stock-display-<?= md5($product_name) ?>"><?= $first_variant['stock'] ?></span> ชิ้น
                                            </div>
                                        </div>
                                        <div class="d-flex gap-1">
                                            <button type="button" class="btn btn-outline-secondary btn-sm rounded-3" data-bs-toggle="modal" data-bs-target="#modal-<?= md5($product_name) ?>" title="ดูรายละเอียดสินค้า">
                                                <i class="bi bi-eye"></i>
                                            </button>
                                            <button type="submit" class="btn-dark-custom" id="btn-submit-<?= md5($product_name) ?>" <?= $first_variant['stock'] <= 0 ? 'disabled' : '' ?>>
                                                <?= $first_variant['stock'] <= 0 ? 'สินค้าหมด' : '<i class="bi bi-cart-plus me-1"></i> ใส่ตะกร้า' ?>
                                            </button>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>

                    <!-- Product Quick View Modal -->
                    <div class="modal fade" id="modal-<?= md5($product_name) ?>" tabindex="-1" aria-hidden="true">
                        <div class="modal-dialog modal-dialog-centered modal-lg">
                            <div class="modal-content border-0 rounded-4 overflow-hidden shadow-lg">
                                <div class="modal-header border-0 pb-0">
                                    <h5 class="modal-title fw-bold text-uppercase"><?= htmlspecialchars($product_name) ?></h5>
                                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                </div>
                                <div class="modal-body p-4">
                                    <div class="row g-4">
                                        <div class="col-md-6">
                                            <img src="<?= htmlspecialchars($product_data['image_url']) ?>" alt="<?= htmlspecialchars($product_name) ?>" class="img-fluid rounded-3 w-100 object-fit-cover" style="max-height: 380px;">
                                        </div>
                                        <div class="col-md-6 d-flex flex-column">
                                            <h4 class="fw-bold mb-2"><?= htmlspecialchars($product_name) ?></h4>
                                            <h3 class="text-primary fw-bold mb-3">฿<?= number_format($first_variant['price'], 2) ?></h3>
                                            <p class="text-muted small mb-4" style="line-height: 1.6;"><?= nl2br(htmlspecialchars($product_data['description'])) ?></p>
                                            
                                            <div class="mt-auto bg-light p-3 rounded-3">
                                                <div class="fw-semibold small mb-2"><i class="bi bi-check-circle-fill text-success me-1"></i> มีตัวเลือกไซส์และสต็อกดังนี้:</div>
                                                <ul class="list-unstyled mb-0 small text-secondary">
                                                    <?php foreach ($product_data['variants'] as $v): ?>
                                                        <li class="d-flex justify-content-between border-bottom py-1">
                                                            <span>ไซส์: <strong><?= htmlspecialchars($v['size']) ?></strong></span>
                                                            <span>คงเหลือ: <strong><?= $v['stock'] ?></strong> ชิ้น</span>
                                                        </li>
                                                    <?php endforeach; ?>
                                                </ul>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </main>

    <!-- Footer -->
    <footer class="bg-white border-top py-4 text-center mt-5">
        <div class="container">
            <p class="mb-1 text-muted">&copy; 2026 Minimalist Closet. All Rights Reserved.</p>
            <p class="text-muted fs-8 mb-0">Pure PHP + HTML5 + Bootstrap 5 + PDO</p>
        </div>
    </footer>

    <!-- Bootstrap 5 JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
        // Update product ID, price, stock, and maximum quantity based on variant selection
        function updateVariant(productIdHash, selectElement) {
            const selectedOption = selectElement.options[selectElement.selectedIndex];
            const variantId = selectedOption.value;
            const price = selectedOption.getAttribute('data-price');
            const stock = parseInt(selectedOption.getAttribute('data-stock'));

            // Update hidden product ID
            document.getElementById('prod-id-' + productIdHash).value = variantId;

            // Update price display
            document.getElementById('price-display-' + productIdHash).innerText = '฿' + price;

            // Update stock display
            const stockDisplay = document.getElementById('stock-display-' + productIdHash);
            stockDisplay.innerText = stock;

            // Update quantity input max value
            const qtyInput = document.getElementById('qty-input-' + productIdHash);
            qtyInput.max = stock;
            if (parseInt(qtyInput.value) > stock) {
                qtyInput.value = stock;
            }
            if (stock <= 0) {
                qtyInput.value = 0;
                qtyInput.min = 0;
            } else {
                qtyInput.min = 1;
                if (parseInt(qtyInput.value) <= 0) {
                    qtyInput.value = 1;
                }
            }

            // Update submit button state
            const submitBtn = document.getElementById('btn-submit-' + productIdHash);
            if (stock <= 0) {
                submitBtn.disabled = true;
                submitBtn.innerText = 'สินค้าหมด';
            } else {
                submitBtn.disabled = false;
                submitBtn.innerHTML = '<i class="bi bi-cart-plus me-1"></i> ใส่ตะกร้า';
            }
        }
    </script>
</body>
</html>
