<?php
require_once __DIR__ . '/db/config.php';

$category_slug = $_GET['name'] ?? '';

if (empty($category_slug)) {
    die("Category not specified.");
}

$pdo = db();

// Get category details
$stmt = $pdo->prepare("SELECT * FROM categories WHERE slug = ?");
$stmt->execute([$category_slug]);
$category = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$category) {
    die("Category not found.");
}

$sort = $_GET['sort'] ?? 'popularity'; // New default for categories
$filter_brand = $_GET['filter_brand'] ?? '';

$results = [];
$brands = [];

// Get all products in this category
$sql = "SELECT p.id, p.name, p.brand, p.image_url FROM products p WHERE p.category_id = ?";
$params = [$category['id']];

// Get all possible brands for the current category
$brand_stmt = $pdo->prepare("SELECT DISTINCT brand FROM products WHERE category_id = ? AND brand IS NOT NULL ORDER BY brand");
$brand_stmt->execute([$category['id']]);
$brands = $brand_stmt->fetchAll(PDO::FETCH_COLUMN);

// Add brand filter
if (!empty($filter_brand)) {
    $sql .= " AND p.brand = ?";
    $params[] = $filter_brand;
}

// Sorting logic for category page
switch ($sort) {
    case 'price_asc':
        $sql .= " ORDER BY (SELECT MIN(effective_price) FROM product_listings WHERE product_id = p.id) ASC";
        break;
    case 'price_desc':
        $sql .= " ORDER BY (SELECT MIN(effective_price) FROM product_listings WHERE product_id = p.id) DESC";
        break;
    case 'rating':
        $sql .= " ORDER BY (SELECT AVG(rating) FROM product_listings WHERE product_id = p.id) DESC";
        break;
    default: // Popularity/relevance for categories could be based on number of listings or other metrics
        $sql .= " ORDER BY p.id DESC"; // Simple default: newest products first
        break;
}

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$products = $stmt->fetchAll(PDO::FETCH_ASSOC);

$product_ids = array_column($products, 'id');
if (!empty($product_ids)) {
    $placeholders = implode(',', array_fill(0, count($product_ids), '?'));
    $stmt = $pdo->prepare("SELECT *, pl.id as listing_id, plat.name as platform_name FROM product_listings pl JOIN platforms plat ON pl.platform_id = plat.id WHERE pl.product_id IN ($placeholders)");
    $stmt->execute($product_ids);
    $listings = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $listings_by_product = [];
    foreach ($listings as $listing) {
        $listings_by_product[$listing['product_id']][] = $listing;
    }

    foreach ($products as $product) {
        $product['listings'] = $listings_by_product[$product['id']] ?? [];
        if (!empty($product['listings'])) {
            $cheapest = array_reduce($product['listings'], fn($c, $i) => ($c === null || $i['effective_price'] < $c['effective_price']) ? $i : $c);
            $product['cheapest_price'] = $cheapest['effective_price'];
            $product['badge'] = $cheapest['badge'];
        }
        $results[] = $product;
    }
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($category['name']); ?> - XUPER MALL</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="assets/css/custom.css?v=<?php echo time(); ?>">
</head>
<body>
    <div class="container mt-5">
        <a href="index.php" class="text-decoration-none">&larr; Back to Home</a>
        <h1 class="my-4"><?php echo htmlspecialchars($category['name']); ?></h1>

        <form method="GET" action="category.php" class="row g-3 mb-4 align-items-center bg-light p-3 rounded">
            <input type="hidden" name="name" value="<?php echo htmlspecialchars($category_slug); ?>">
            <div class="col-md-4">
                <label for="sort" class="form-label">Sort by</label>
                <select name="sort" id="sort" class="form-select">
                    <option value="popularity" <?php if ($sort == 'popularity') echo 'selected'; ?>>Popularity</option>
                    <option value="price_asc" <?php if ($sort == 'price_asc') echo 'selected'; ?>>Price: Low to High</option>
                    <option value="price_desc" <?php if ($sort == 'price_desc') echo 'selected'; ?>>Price: High to Low</option>
                    <option value="rating" <?php if ($sort == 'rating') echo 'selected'; ?>>Rating</option>
                </select>
            </div>
            <div class="col-md-4">
                <label for="filter_brand" class="form-label">Brand</label>
                <select name="filter_brand" id="filter_brand" class="form-select">
                    <option value="">All Brands</option>
                    <?php foreach ($brands as $brand): ?>
                        <option value="<?php echo htmlspecialchars($brand); ?>" <?php if ($filter_brand == $brand) echo 'selected'; ?>><?php echo htmlspecialchars($brand); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2 d-flex align-items-end">
                <button type="submit" class="btn btn-primary w-100">Apply</button>
            </div>
        </form>

        <?php if (empty($results)): ?>
            <div class="alert alert-info">No products found in this category yet.</div>
        <?php else: ?>
            <div class="row g-4">
                <?php foreach ($results as $product): ?>
                <div class="col-12">
                    <div class="card product-card-list">
                        <div class="row g-0">
                            <div class="col-md-2">
                                <img src="<?php echo htmlspecialchars($product['image_url'] ?? 'https://via.placeholder.com/150'); ?>" class="img-fluid rounded-start" alt="<?php echo htmlspecialchars($product['name']); ?>">
                            </div>
                            <div class="col-md-7">
                                <div class="card-body">
                                    <h5 class="card-title"><?php echo htmlspecialchars($product['name']); ?></h5>
                                    <p class="card-text text-muted"><?php echo htmlspecialchars($product['brand']); ?></p>
                                    <p class="card-text">From: <span class="fw-bold text-success">$<?php echo htmlspecialchars($product['cheapest_price'] ?? 'N/A'); ?></span></p>
                                    <?php if (!empty($product['badge'])): ?>
                                        <span class="badge bg-info"><?php echo htmlspecialchars($product['badge']); ?></span>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="card-body">
                                    <h6 class="mb-2">Available on:</h6>
                                    <ul class="list-group list-group-flush">
                                        <?php foreach ($product['listings'] as $listing): ?>
                                            <li class="list-group-item d-flex justify-content-between align-items-center">
                                                <a href="<?php echo htmlspecialchars($listing['product_url']); ?>" target="_blank" rel="noopener noreferrer">
                                                    <?php echo htmlspecialchars($listing['platform_name']); ?>
                                                </a>
                                                <span class="fw-bold">$<?php echo htmlspecialchars($listing['effective_price']); ?></span>
                                            </li>
                                        <?php endforeach; ?>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>