<?php
require_once __DIR__ . '/includes/header.php';

// Parse query params
$selected_category = isset($_GET['category']) ? trim($_GET['category']) : '';
$search_query = isset($_GET['search']) ? trim($_GET['search']) : '';
$featured_only = isset($_GET['featured']) ? intval($_GET['featured']) : 0;

// Build query
$query_parts = [];
$params = [];

if (!empty($selected_category)) {
    $query_parts[] = "c.slug = :category";
    $params['category'] = $selected_category;
}

if (!empty($search_query)) {
    $query_parts[] = "(p.name LIKE :search OR p.description LIKE :search)";
    $params['search'] = '%' . $search_query . '%';
}

if ($featured_only === 1) {
    $query_parts[] = "p.is_featured = TRUE";
}

$where_clause = "";
if (!empty($query_parts)) {
    $where_clause = "WHERE " . implode(" AND ", $query_parts);
}

try {
    $sql = "SELECT p.*, c.name as category_name 
            FROM products p 
            LEFT JOIN categories c ON p.category_id = c.id 
            $where_clause 
            ORDER BY p.id DESC";
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $products = $stmt->fetchAll();
} catch (Exception $e) {
    $products = [];
}

// Fetch all categories for navigation/filter buttons
try {
    $stmt = $pdo->query("SELECT * FROM categories ORDER BY id ASC");
    $all_categories = $stmt->fetchAll();
} catch (Exception $e) {
    $all_categories = [];
}
?>

<!-- Shop Page Header Banner -->
<section class="py-5 text-center bg-black border-bottom border-dark position-relative" style="background: linear-gradient(rgba(0,0,0,0.75), rgba(0,0,0,0.85)), url('assets/images/hero_fashion.png') no-repeat center 20%/cover; padding: 5rem 0 !important;">
    <div class="container py-4">
        <h1 class="text-white fw-bold display-4">
            <?php 
            if (!empty($selected_category)) {
                // Find matching category name
                $cat_title = "Shop Collection";
                foreach ($all_categories as $c) {
                    if ($c['slug'] === $selected_category) {
                        $cat_title = $c['name'] . " Collection";
                        break;
                    }
                }
                echo htmlspecialchars($cat_title);
            } elseif ($featured_only === 1) {
                echo "Featured Masterpieces";
            } else {
                echo "MARTLUX Catalog";
            }
            ?>
        </h1>
        <p class="text-warning small text-uppercase fw-bold mb-0 mt-2" style="letter-spacing: 3px;">Atelier Couture</p>
    </div>
</section>

<!-- Main Catalog Container -->
<section class="py-5" style="background-color: var(--bg-dark); min-height: 50vh;">
    <div class="container">
        
        <!-- Search and Filter Bar -->
        <div class="row mb-5 g-3 align-items-center justify-content-between">
            <!-- Categories Filters -->
            <div class="col-lg-8 col-md-12">
                <div class="d-flex flex-wrap gap-2">
                    <a href="shop.php" class="btn btn-outline-light rounded-pill px-4 btn-sm <?php echo (empty($selected_category) && $featured_only !== 1) ? 'active bg-warning text-black border-warning' : ''; ?>">All Couture</a>
                    
                    <?php foreach ($all_categories as $cat): ?>
                        <a href="shop.php?category=<?php echo urlencode($cat['slug']); ?>" 
                           class="btn btn-outline-light rounded-pill px-4 btn-sm <?php echo ($selected_category === $cat['slug']) ? 'active bg-warning text-black border-warning' : ''; ?>">
                            <?php echo htmlspecialchars($cat['name']); ?>
                        </a>
                    <?php endforeach; ?>

                    <a href="shop.php?featured=1" class="btn btn-outline-warning rounded-pill px-4 btn-sm <?php echo ($featured_only === 1) ? 'active bg-warning text-black border-warning' : ''; ?>">Featured</a>
                </div>
            </div>

            <!-- Search form on page (especially for mobile/responsive) -->
            <div class="col-lg-4 col-md-6 col-sm-8 ms-auto">
                <form action="shop.php" method="GET" class="input-group">
                    <?php if (!empty($selected_category)): ?>
                        <input type="hidden" name="category" value="<?php echo htmlspecialchars($selected_category); ?>">
                    <?php endif; ?>
                    <?php if ($featured_only === 1): ?>
                        <input type="hidden" name="featured" value="1">
                    <?php endif; ?>
                    <input type="text" name="search" class="form-control bg-black border-secondary text-white placeholder-secondary" placeholder="Search boutique..." value="<?php echo htmlspecialchars($search_query); ?>" style="border-radius: 30px 0 0 30px; box-shadow: none;">
                    <button class="btn btn-warning text-black" type="submit" style="border-radius: 0 30px 30px 0; border: none; font-size: 0.9rem;"><i class="fa-solid fa-magnifying-glass"></i></button>
                </form>
            </div>
        </div>

        <!-- Products Grid -->
        <div class="row g-3 g-md-4">
            <?php if (empty($products)): ?>
                <div class="col-12 text-center py-5">
                    <div class="py-5" style="border: 1px dashed rgba(255,255,255,0.1); border-radius: 15px; background-color: var(--bg-card);">
                        <i class="fa-solid fa-bag-shopping text-warning display-4 mb-3"></i>
                        <h4 class="text-white">No Items Match Your Search</h4>
                        <p class="text-muted small">Try modifying your text criteria, categories, or filters.</p>
                        <a href="shop.php" class="btn btn-warning rounded-pill px-4 mt-2">Clear Filters</a>
                    </div>
                </div>
            <?php else: ?>
                <?php foreach ($products as $prod): ?>
                    <div class="col-lg-4 col-md-6 col-6">
                        <div class="product-card">
                            <!-- Image Section -->
                            <div class="product-img-wrapper">
                                <a href="product.php?id=<?php echo $prod['id']; ?>">
                                    <img src="assets/images/<?php echo htmlspecialchars($prod['image']); ?>" alt="<?php echo htmlspecialchars($prod['name']); ?>" loading="lazy">
                                </a>
                                <?php if ($prod['is_featured']): ?>
                                    <span class="badge-new bg-warning text-black"><i class="fa-solid fa-star me-1"></i>FEATURED</span>
                                <?php endif; ?>
                                <button type="button" class="wishlist-btn" onclick="addToWishlist(<?php echo $prod['id']; ?>)">
                                    <i class="fa-regular fa-heart"></i>
                                </button>
                            </div>
                            
                            <!-- Information Section -->
                            <div class="product-details position-relative">
                                <div class="mb-1 text-muted text-uppercase small" style="font-size: 0.7rem; letter-spacing: 1px;">
                                    <?php echo htmlspecialchars($prod['category_name'] ?? 'Couture'); ?>
                                </div>
                                <h3 class="product-name">
                                    <a href="product.php?id=<?php echo $prod['id']; ?>" class="text-white text-decoration-none hover-gold">
                                        <?php echo htmlspecialchars($prod['name']); ?>
                                    </a>
                                </h3>
                                <div class="product-price">LKR <?php echo number_format($prod['price'], 2); ?></div>
                                
                                <!-- AJAX Add To Cart -->
                                <button type="button" class="cart-icon-btn add-to-cart-btn" data-product-id="<?php echo $prod['id']; ?>" title="Add to Cart">
                                    <i class="fa-solid fa-bag-shopping text-dark" style="font-size: 0.95rem;"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>
</section>

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