<?php
/**
 * CMTC Shopping Home Page (Landing Page / Product Catalog)
 * CMTC Shopping
 */
require_once __DIR__ . '/includes/header.php';
require_once __DIR__ . '/includes/navbar.php';

// Auto-migration: Check and add purchase_type column if it doesn't exist
try {
    $check_col = $db->query("SHOW COLUMNS FROM products LIKE 'purchase_type'");
    if ($check_col->rowCount() === 0) {
        $db->exec("ALTER TABLE products ADD COLUMN purchase_type ENUM('normal', 'booking') DEFAULT 'normal' AFTER status");
    }
    
    // Check and add image_path column to product_sizes
    $check_sz_col = $db->query("SHOW COLUMNS FROM product_sizes LIKE 'image_path'");
    if ($check_sz_col->rowCount() === 0) {
        $db->exec("ALTER TABLE product_sizes ADD COLUMN image_path VARCHAR(255) NULL");
    }
    
    // Auto-update system settings name to CMTC Smart Outfit Shopping & Booking
    $db->exec("UPDATE system_settings SET system_name = 'CMTC Smart Outfit Shopping & Booking' WHERE system_name = 'CMTC Shopping'");
} catch (Exception $e) {
    // Ignore migration error
}

$banners = [];
$news = [];
$products = [];
$categories = [];

if ($db) {
    try {
        $stmt_b = $db->query("SELECT * FROM banners WHERE status = 'active' ORDER BY sort_order ASC");
        if ($stmt_b) $banners = $stmt_b->fetchAll();
    } catch (Throwable $e) {}

    try {
        $stmt_n = $db->query("SELECT * FROM news WHERE status = 'active' ORDER BY id DESC LIMIT 3");
        if ($stmt_n) $news = $stmt_n->fetchAll();
    } catch (Throwable $e) {}

    // Filter values
    $cat_filter = isset($_GET['category']) ? intval($_GET['category']) : 0;
    $search_query = isset($_GET['search']) ? trim($_GET['search']) : '';

    $sql = "SELECT p.*, c.name as category_name, 
            (SELECT image_path FROM product_images WHERE product_id = p.id ORDER BY is_main DESC, id ASC LIMIT 1) as main_image,
            (SELECT COALESCE(SUM(quantity), 0) FROM product_stock WHERE product_id = p.id) as total_stock
            FROM products p 
            LEFT JOIN categories c ON p.category_id = c.id 
            WHERE p.status = 'active'";

    $params = [];
    if ($cat_filter > 0) {
        $sql .= " AND p.category_id = ?";
        $params[] = $cat_filter;
    }
    if (!empty($search_query)) {
        $sql .= " AND (p.name LIKE ? OR p.sku LIKE ?)";
        $params[] = "%$search_query%";
        $params[] = "%$search_query%";
    }
    $sql .= " ORDER BY p.id DESC";

    try {
        $stmt = $db->prepare($sql);
        $stmt->execute($params);
        $products = $stmt->fetchAll();
    } catch (Throwable $e) {}

    try {
        $stmt_c = $db->query("SELECT * FROM categories ORDER BY name ASC");
        if ($stmt_c) $categories = $stmt_c->fetchAll();
    } catch (Throwable $e) {}
}
?>

<style>
    /* Premium High-Contrast Page Styles */
    .product-card {
        background: var(--bs-card-bg) !important;
        border: 1px solid var(--bs-border-color, rgba(0, 0, 0, 0.08)) !important;
        border-top: 4px solid #0d6efd !important;
        border-radius: 16px !important;
        overflow: hidden;
        transition: all 0.4s cubic-bezier(0.165, 0.84, 0.44, 1);
        box-shadow: 0 10px 25px rgba(0, 0, 0, 0.05) !important;
    }
    .product-card:hover {
        transform: translateY(-8px);
        box-shadow: 0 25px 40px rgba(13, 110, 253, 0.15) !important;
        border-color: #0d6efd !important;
    }
    .product-img-container {
        overflow: hidden;
        position: relative;
        border-top-left-radius: 12px;
        border-top-right-radius: 12px;
        background-color: var(--bs-tertiary-bg, #f8fafc);
    }
    .product-img-hover {
        transition: transform 0.6s cubic-bezier(0.165, 0.84, 0.44, 1);
    }
    .product-card:hover .product-img-hover {
        transform: scale(1.06);
    }
    
    .filter-card {
        background: var(--bs-card-bg) !important;
        border: 1px solid var(--bs-border-color, rgba(0, 0, 0, 0.08)) !important;
        border-top: 4px solid #4f46e5 !important;
        border-radius: 16px !important;
        box-shadow: 0 10px 25px rgba(0, 0, 0, 0.05) !important;
    }
    
    .price-text {
        font-family: 'Outfit', 'Sarabun', sans-serif;
        font-weight: 800;
        color: #0d6efd !important;
        font-size: 1.3rem;
    }
    
    .btn-detail {
        border-radius: 10px;
        font-weight: 700;
        padding: 9px 16px;
        border: 2px solid #0d6efd !important;
        color: #0d6efd !important;
        transition: all 0.3s ease;
    }
    .btn-detail:hover {
        background: linear-gradient(135deg, #0d6efd 0%, #4f46e5 100%) !important;
        color: #ffffff !important;
        border-color: transparent !important;
        box-shadow: 0 4px 15px rgba(13, 110, 253, 0.3);
        transform: scale(1.02);
    }
    
    .news-card {
        background: var(--bs-card-bg) !important;
        border: 1px solid var(--bs-border-color, rgba(0, 0, 0, 0.08)) !important;
        border-left: 4px solid #dc3545 !important;
        border-radius: 12px !important;
        box-shadow: 0 6px 15px rgba(0, 0, 0, 0.04) !important;
        transition: all 0.3s ease;
    }
    .news-card:hover {
        transform: translateY(-4px);
        box-shadow: 0 15px 30px rgba(0, 0, 0, 0.08) !important;
    }
    
    .scrollbar-hidden::-webkit-scrollbar {
        display: none;
    }
    .scrollbar-hidden {
        -ms-overflow-style: none;
        scrollbar-width: none;
    }
    .category-item-card {
        border-color: var(--bs-border-color, rgba(0, 0, 0, 0.12)) !important;
    }
    .category-item-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
    }
    .category-item-card.active {
        box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12) !important;
    }
    .category-item-card.active span {
        color: #ffffff !important;
        font-weight: 700 !important;
    }
    .category-item-card.active .category-icon-wrapper {
        background: #ffffff !important;
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.12) !important;
    }
</style>

<!-- AI Premium Hero Section -->
<div class="ai-hero-section position-relative d-flex align-items-center justify-content-center text-center text-white overflow-hidden" style="
    min-height: 480px;
    padding: 90px 20px;
    margin-bottom: 30px;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);
">
    <!-- Animated background wrapper -->
    <div class="position-absolute top-0 start-0 w-100 h-100" style="
        background: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.6)), url('<?php echo base_url('uploads/hero_bg.png'); ?>') no-repeat center center;
        background-size: cover;
        animation: kenBurnsBg 24s ease-in-out infinite alternate;
        z-index: 1;
    "></div>
    
    <!-- Blur Overlay -->
    <div class="position-absolute top-0 start-0 w-100 h-100" style="backdrop-filter: blur(2px); pointer-events: none; z-index: 2;"></div>
    
    <div class="container position-relative" style="z-index: 3; max-width: 850px;">
        <!-- Badge -->
        <div class="mb-4 animate-fade-up">
            <span class="badge rounded-pill px-3 py-2 text-uppercase fw-bold" style="
                background: rgba(99, 102, 241, 0.2);
                border: 1px solid rgba(99, 102, 241, 0.5);
                color: #a5b4fc;
                font-size: 0.75rem;
                letter-spacing: 1px;
                animation: pulseGlowBadge 2.5s infinite;
            ">
                <i class="fa-solid fa-wand-magic-sparkles me-1"></i> POWERED BY ADVANCED AI MATCHING
            </span>
        </div>
        
        <!-- Main Title -->
        <h1 class="display-4 fw-extrabold mb-3 text-white animate-fade-up" style="
            font-family: 'Sarabun', 'Inter', sans-serif;
            font-weight: 850;
            letter-spacing: -0.5px;
            text-shadow: 0 4px 15px rgba(0, 0, 0, 0.4);
            animation-delay: 150ms;
        ">
            ช้อปสินค้าพรีเมียมและจอง
        </h1>
        
        <!-- Subtitle -->
        <p class="lead mb-0 text-light opacity-90 mx-auto animate-fade-up" style="
            max-width: 720px;
            font-size: 1.1rem;
            line-height: 1.6;
            font-weight: 400;
            text-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
            animation-delay: 300ms;
        ">
            แหล่งรวมของที่ระลึกและบริการจองชุดหรูหราสำหรับทุกโอกาสสำคัญ
        </p>
    </div>
</div>

<style>
    /* Hero animations */
    @keyframes kenBurnsBg {
        0% { transform: scale(1); }
        100% { transform: scale(1.07); }
    }
    @keyframes pulseGlowBadge {
        0% { box-shadow: 0 0 0 0 rgba(99, 102, 241, 0.4); }
        70% { box-shadow: 0 0 0 8px rgba(99, 102, 241, 0); }
        100% { box-shadow: 0 0 0 0 rgba(99, 102, 241, 0); }
    }
    @keyframes fadeInUpHero {
        from {
            opacity: 0;
            transform: translateY(24px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }
    .animate-fade-up {
        opacity: 0;
        animation: fadeInUpHero 0.8s cubic-bezier(0.16, 1, 0.3, 1) forwards;
    }
</style>

<div class="container my-4">
    <!-- Catalog section anchor -->
    <div id="catalog-section"></div>

    <!-- News Section -->
    <?php if (count($news) > 0): ?>
        <div class="row mb-5">
            <div class="col-12">
                <h4 class="fw-bold mb-3"><i class="bi bi-megaphone-fill text-danger me-2"></i>ข่าวประชาสัมพันธ์</h4>
                <marquee direction="right" scrollamount="5" onmouseover="this.stop();" onmouseout="this.start();" style="border-radius: 12px; padding: 10px 0;">
                    <div class="d-flex gap-3 px-2">
                        <?php foreach ($news as $item): ?>
                            <div style="min-width: 320px; max-width: 320px;">
                                <div class="card h-100 shadow-sm news-card border-0">
                                    <?php if (!empty($item['image'])): ?>
                                        <img src="<?php echo base_url('uploads/news/' . sanitize($item['image'])); ?>" class="card-img-top" style="height: 160px; object-fit: cover; border-top-left-radius: 12px; border-top-right-radius: 12px;">
                                    <?php endif; ?>
                                    <div class="card-body">
                                        <?php if (!empty($item['title'])): ?>
                                            <h6 class="card-title fw-bold text-truncate"><?php echo sanitize($item['title']); ?></h6>
                                        <?php endif; ?>
                                        <?php if (!empty($item['content'])): ?>
                                            <p class="card-text text-muted small text-truncate-3"><?php echo sanitize($item['content']); ?></p>
                                        <?php endif; ?>
                                        <div class="text-end text-muted small mt-2"><?php echo format_thai_date($item['created_at'], false); ?></div>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </marquee>
            </div>
        </div>
    <?php endif; ?>

    <!-- Catalog Section -->
    <div class="row">
        <!-- Unified Catalog Controls (Full Width) -->
        <div class="col-12 mb-4">
            <div class="card glass-card border-0 p-4" style="border-radius: 20px;">
                <form method="GET" action="index.php">
                    <div class="row g-3">
                        <!-- Search Bar -->
                        <div class="col-12 col-md-9">
                            <label class="form-label fw-bold text-muted small mb-2"><i class="bi bi-search me-1"></i>ค้นหาสินค้าด่วน</label>
                            <div class="input-group">
                                <span class="input-group-text bg-light border-end-0 text-muted" style="border-radius: 12px 0 0 12px; border: 1px solid var(--bs-border-color, rgba(0,0,0,0.12));"><i class="bi bi-search"></i></span>
                                <input type="text" name="search" class="form-control border-start-0 ps-2" placeholder="พิมพ์ชื่อสินค้า หรือ SKU..." value="<?php echo sanitize($search_query); ?>" style="border-radius: 0 12px 12px 0; border: 1px solid var(--bs-border-color, rgba(0,0,0,0.12)); height: 46px;">
                            </div>
                        </div>
                        <div class="col-12 col-md-3 d-flex align-items-end">
                            <input type="hidden" name="category" value="<?php echo $cat_filter; ?>">
                            <button type="submit" class="btn btn-primary w-100 d-flex align-items-center justify-content-center gap-2" style="height: 46px; border-radius: 12px; font-weight: 600;">
                                <i class="bi bi-search"></i>
                                <span>ค้นหาสินค้า</span>
                            </button>
                        </div>

                        <!-- Categories Bar (Full Width & Flex Wrap) -->
                        <div class="col-12 mt-3 pt-2 border-top">
                            <label class="form-label fw-bold text-muted small mb-2"><i class="bi bi-grid-3x3-gap-fill me-1"></i>หมวดหมู่สินค้าทั้งหมด</label>
                            <div class="d-flex flex-wrap gap-2 align-items-center">
                                <!-- All Categories Pill -->
                                <a href="index.php?category=0&search=<?php echo urlencode($search_query); ?>" class="text-decoration-none">
                                    <div class="category-item-card d-flex align-items-center px-3 py-2 rounded-3 border <?php echo $cat_filter === 0 ? 'active' : ''; ?>" style="height: 42px; transition: all 0.3s ease; background: <?php echo $cat_filter === 0 ? '#0d6efd' : 'var(--bs-card-bg)'; ?>; color: <?php echo $cat_filter === 0 ? '#fff' : 'var(--bs-body-color)'; ?>;">
                                        <div class="category-icon-wrapper d-flex align-items-center justify-content-center rounded-circle me-2" style="width: 26px; height: 26px; background: <?php echo $cat_filter === 0 ? '#fff' : 'rgba(13, 110, 253, 0.1)'; ?>; color: #0d6efd;">
                                            <i class="fa-solid fa-border-all" style="font-size: 0.8rem;"></i>
                                        </div>
                                        <span class="small fw-semibold" style="font-size: 0.85rem;">ทั้งหมด</span>
                                    </div>
                                </a>
                                
                                <?php foreach ($categories as $cat): 
                                    $cat_name = $cat['name'];
                                    $icon_class = 'fa-solid fa-layer-group';
                                    $bg_color = 'rgba(108, 117, 125, 0.12)';
                                    $text_color = '#4b5563';
                                    
                                    if (mb_strpos($cat_name, 'เสื้อ') !== false) {
                                        $icon_class = 'fa-solid fa-shirt';
                                        $bg_color = 'rgba(13, 110, 253, 0.12)';
                                        $text_color = '#0d6efd';
                                    } elseif (mb_strpos($cat_name, 'กางเกง') !== false || mb_strpos($cat_name, 'กระโปรง') !== false) {
                                        $icon_class = 'fa-solid fa-person-running';
                                        $bg_color = 'rgba(2, 132, 199, 0.12)';
                                        $text_color = '#0284c7';
                                    } elseif (mb_strpos($cat_name, 'รองเท้า') !== false) {
                                        $icon_class = 'fa-solid fa-shoe-prints';
                                        $bg_color = 'rgba(111, 66, 193, 0.12)';
                                        $text_color = '#6f42c1';
                                    } elseif (mb_strpos($cat_name, 'เข็ม') !== false || mb_strpos($cat_name, 'เครื่องหมาย') !== false) {
                                        $icon_class = 'fa-solid fa-award';
                                        $bg_color = 'rgba(232, 62, 140, 0.12)';
                                        $text_color = '#e83e8c';
                                    } elseif (mb_strpos($cat_name, 'เรียน') !== false || mb_strpos($cat_name, 'เขียน') !== false) {
                                        $icon_class = 'fa-solid fa-pen-ruler';
                                        $bg_color = 'rgba(234, 88, 12, 0.12)';
                                        $text_color = '#ea580c';
                                    } elseif (mb_strpos($cat_name, 'กระเป๋า') !== false || mb_strpos($cat_name, 'เป้') !== false) {
                                        $icon_class = 'fa-solid fa-bag-shopping';
                                        $bg_color = 'rgba(25, 135, 84, 0.12)';
                                        $text_color = '#198754';
                                    } elseif (mb_strpos($cat_name, 'ไอที') !== false || mb_strpos($cat_name, 'อิเล็กทรอนิกส์') !== false) {
                                        $icon_class = 'fa-solid fa-laptop';
                                        $bg_color = 'rgba(13, 148, 136, 0.12)';
                                        $text_color = '#0d9488';
                                    } elseif (mb_strpos($cat_name, 'ที่ระลึก') !== false) {
                                        $icon_class = 'fa-solid fa-gift';
                                        $bg_color = 'rgba(217, 119, 6, 0.12)';
                                        $text_color = '#d97706';
                                    } elseif (mb_strpos($cat_name, 'หนังสือ') !== false || mb_strpos($cat_name, 'ตำรา') !== false) {
                                        $icon_class = 'fa-solid fa-book-open';
                                        $bg_color = 'rgba(102, 16, 242, 0.12)';
                                        $text_color = '#6610f2';
                                    } elseif (mb_strpos($cat_name, 'อาหาร') !== false || mb_strpos($cat_name, 'ขนม') !== false) {
                                        $icon_class = 'fa-solid fa-utensils';
                                        $bg_color = 'rgba(214, 51, 132, 0.12)';
                                        $text_color = '#d63384';
                                    }

                                    $is_active = ($cat_filter === intval($cat['id']));
                                ?>
                                    <a href="index.php?category=<?php echo $cat['id']; ?>&search=<?php echo urlencode($search_query); ?>" class="text-decoration-none">
                                        <div class="category-item-card d-flex align-items-center px-3 py-2 rounded-3 border <?php echo $is_active ? 'active' : ''; ?>" style="height: 42px; transition: all 0.3s ease; background: <?php echo $is_active ? $text_color : 'var(--bs-card-bg)'; ?>; color: <?php echo $is_active ? '#fff' : 'var(--bs-body-color)'; ?>;">
                                            <div class="category-icon-wrapper d-flex align-items-center justify-content-center rounded-circle me-2" style="width: 26px; height: 26px; background: <?php echo $is_active ? '#fff' : $bg_color; ?>; color: <?php echo $is_active ? $text_color : $text_color; ?>;">
                                                <i class="<?php echo $icon_class; ?>" style="font-size: 0.8rem;"></i>
                                            </div>
                                            <span class="small fw-semibold" style="font-size: 0.85rem;"><?php echo sanitize($cat['name']); ?></span>
                                        </div>
                                    </a>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>

        <!-- Product Listing Grid -->
        <div class="col-md-12">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h4 class="fw-bold mb-0">รายการสินค้า (<?php echo count($products); ?> รายการ)</h4>
            </div>

            <div class="row g-3">
                <?php if (count($products) > 0): ?>
                    <?php foreach ($products as $prod): ?>
                        <?php 
                        $display_price = $prod['promo_price'] ?? $prod['price'];
                        $is_promo = !empty($prod['promo_price']);
                        ?>
                        <div class="col-6 col-md-4 col-lg-3">
                            <div class="card h-100 shadow-sm border-0 product-card">
                                <div class="product-img-container position-relative" style="height: 180px;">
                                    <?php if ($is_promo): ?>
                                        <?php $discount_percent = round((($prod['price'] - $prod['promo_price']) / $prod['price']) * 100); ?>
                                        <span class="position-absolute top-0 start-0 bg-danger text-white px-2 py-1 m-2 rounded-2 fw-bold small shadow-sm" style="z-index: 2; font-size: 0.75rem;">
                                            ลด <?php echo $discount_percent; ?>%
                                        </span>
                                    <?php endif; ?>
                                    <?php if (!empty($prod['main_image'])): ?>
                                        <img src="<?php echo product_image_url($prod['main_image']); ?>" class="w-100 h-100 object-fit-cover product-img-hover" alt="Product Image" onerror="this.onerror=null; this.parentElement.innerHTML='<div class=\'w-100 h-100 bg-secondary d-flex align-items-center justify-content-center text-white\'><i class=\'bi bi-image fs-1\'></i></div>';">
                                    <?php else: ?>
                                        <div class="w-100 h-100 bg-secondary d-flex align-items-center justify-content-center text-white">
                                            <i class="bi bi-image fs-1"></i>
                                        </div>
                                    <?php endif; ?>
                                </div>
                                <div class="card-body d-flex flex-column justify-content-between p-3">
                                    <div>
                                        <div class="d-flex justify-content-between align-items-center mb-1">
                                            <span class="badge bg-secondary" style="font-size: 0.7rem;"><?php echo sanitize($prod['category_name'] ?? 'ของทั่วไป'); ?></span>
                                            <div class="d-flex gap-1">
                                                <?php if (($prod['purchase_type'] ?? 'normal') === 'booking'): ?>
                                                    <span class="badge bg-primary" style="font-size: 0.65rem;">เปิดจอง</span>
                                                <?php endif; ?>
                                                <span class="badge <?php echo $prod['total_stock'] > 0 ? 'bg-success-subtle text-success' : 'bg-danger-subtle text-danger'; ?>" style="font-size: 0.65rem;">
                                                    <?php echo $prod['total_stock'] > 0 ? 'เหลือ ' . $prod['total_stock'] . ' ชิ้น' : 'หมดสต๊อก'; ?>
                                                </span>
                                            </div>
                                        </div>
                                        <h6 class="card-title fw-bold mb-1 text-truncate-2"><?php echo sanitize($prod['name']); ?></h6>
                                        <code class="d-block mb-2 text-muted" style="font-size: 0.8rem;">SKU: <?php echo sanitize($prod['sku']); ?></code>
                                    </div>
                                    
                                    <div>
                                        <div class="d-flex align-items-center gap-2 mb-2 flex-wrap">
                                            <span class="fs-5 fw-bold price-text"><?php echo format_price($display_price); ?></span>
                                            <?php if ($is_promo): ?>
                                                <span class="text-decoration-line-through text-muted small"><?php echo format_price($prod['price']); ?></span>
                                                <span class="badge bg-danger-subtle text-danger rounded-1" style="font-size: 0.7rem; font-weight: 700;">ลด <?php echo $discount_percent; ?>%</span>
                                            <?php endif; ?>
                                        </div>
                                        <a href="<?php echo base_url('views/product_detail.php?id=' . $prod['id']); ?>" class="btn btn-sm btn-outline-primary btn-detail w-100">ดูรายละเอียด</a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <div class="col-12">
                        <div class="text-center py-5 text-muted">
                            <i class="bi bi-inbox fs-1 d-block mb-2"></i>
                            ไม่พบสินค้าในระบบ
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
