<?php
require 'config/db.php';

// 1. CAPTURA DE PARÁMETROS Y FILTROS
$game_slug = $_GET['game'] ?? '';
$current_cat_slug = $_GET['category'] ?? '';
$filter_server = $_GET['server'] ?? '';
$filter_online = isset($_GET['online']) && $_GET['online'] == '1';
$sort = $_GET['sort'] ?? 'price_asc';

try {
    // Datos del Juego
    $stmt_game = $pdo->prepare("SELECT * FROM games WHERE slug = ?");
    $stmt_game->execute([$game_slug]);
    $game = $stmt_game->fetch();
    if (!$game) die("Game not found.");

    // Categorías con Conteo
    $stmt_cats = $pdo->prepare("
        SELECT c.name, c.slug, COUNT(p.id) as total_items 
        FROM categories c
        LEFT JOIN products p ON p.category_id = c.id AND p.game_id = ?
        WHERE c.game_id = ? OR c.game_id IS NULL
        GROUP BY c.id ORDER BY (c.game_id IS NULL) DESC, c.name ASC
    ");
    $stmt_cats->execute([$game['id'], $game['id']]);
    $categories = $stmt_cats->fetchAll();

    // Servidores únicos
    $stmt_servers = $pdo->prepare("SELECT DISTINCT server_name FROM products WHERE game_id = ? AND server_name IS NOT NULL");
    $stmt_servers->execute([$game['id']]);
    $servers = $stmt_servers->fetchAll(PDO::FETCH_COLUMN);

    // 2. CONSTRUCCIÓN DE CONSULTA DE PRODUCTOS
    $query = "SELECT p.*, u.username, u.last_seen, u.created_at as member_since,
              (SELECT AVG(rating) FROM reviews WHERE seller_id = u.id) as avg_rating,
              (SELECT COUNT(*) FROM reviews WHERE seller_id = u.id) as total_reviews
              FROM products p 
              JOIN users u ON p.seller_id = u.id 
              WHERE p.game_id = ?";
    $params = [$game['id']];

    if ($current_cat_slug) {
        $query .= " AND p.category_id = (SELECT id FROM categories WHERE slug = ? LIMIT 1)";
        $params[] = $current_cat_slug;
    }
    if ($filter_server) {
        $query .= " AND p.server_name = ?";
        $params[] = $filter_server;
    }
    if ($filter_online) {
        $query .= " AND u.last_seen > DATE_SUB(NOW(), INTERVAL 5 MINUTE)";
    }

    // Ordenamiento
    switch ($sort) {
        case 'price_desc': $query .= " ORDER BY p.price DESC"; break;
        case 'stock_desc': $query .= " ORDER BY p.stock DESC"; break;
        default: $query .= " ORDER BY p.price ASC"; break;
    }

    $stmt_items = $pdo->prepare($query);
    $stmt_items->execute($params);
    $items = $stmt_items->fetchAll();

} catch (PDOException $e) { die("Error: " . $e->getMessage()); }

include 'includes/header.php';
?>

<style>
    body { background-color: var(--bg-dark); color: #e1e1e1; }
    .catalog-wrapper { max-width: 1300px; margin: 40px auto; padding: 0 20px; }
    
    /* Filtros y Categorías */
    .filter-section { display: flex; flex-wrap: wrap; gap: 15px; align-items: center; justify-content: space-between; margin-bottom: 30px; background: var(--nav-bg); padding: 20px; border-radius: 12px; border: 1px solid var(--border); }
    .pill-group { display: flex; gap: 10px; flex-wrap: wrap; }
    .cat-pill { padding: 8px 16px; background: rgba(255,255,255,0.05); border: 1px solid var(--border); border-radius: 8px; color: var(--text-gray); text-decoration: none; font-size: 13px; transition: 0.3s; }
    .cat-pill:hover, .cat-pill.active { background: var(--primary); color: #000; font-weight: bold; border-color: var(--primary); }
    .cat-pill span { opacity: 0.6; font-size: 11px; margin-left: 5px; }

    /* Controles de Selección */
    .custom-select { background: #000; color: white; border: 1px solid var(--border); padding: 8px 12px; border-radius: 6px; outline: none; font-size: 13px; cursor: pointer; }
    .custom-select:focus { border-color: var(--primary); }

    /* Tabla Estilo PoE */
    .m-table { width: 100%; border-collapse: separate; border-spacing: 0 8px; margin-top: 10px; }
    .m-table th { color: var(--text-gray); font-size: 11px; text-transform: uppercase; padding: 10px 20px; text-align: left; letter-spacing: 1px; }
    .m-row { background: var(--nav-bg); transition: 0.2s; }
    .m-row:hover { background: rgba(255,255,255,0.02); transform: scale(1.002); }
    .m-td { padding: 15px 20px; border-top: 1px solid var(--border); border-bottom: 1px solid var(--border); }
    .m-td:first-child { border-left: 1px solid var(--border); border-radius: 10px 0 0 10px; }
    .m-td:last-child { border-right: 1px solid var(--border); border-radius: 0 10px 10px 0; }

    /* Vendedor y Reputación */
    .seller-info { display: flex; align-items: center; gap: 12px; }
    .status-dot { width: 8px; height: 8px; border-radius: 50%; display: inline-block; }
    .is-online { background: var(--primary); box-shadow: 0 0 8px var(--primary); }
    .is-offline { background: #444; }
    .seller-meta { font-size: 11px; color: var(--text-gray); margin-top: 4px; }
    .stars { color: #ffcc00; font-size: 10px; }

    /* Precio y Botón */
    .price-tag { font-size: 20px; font-weight: 900; color: white; }
    .price-tag span { color: var(--primary); font-size: 14px; margin-right: 2px; }
    .btn-view { background: var(--primary); color: black; padding: 10px 20px; border-radius: 6px; text-decoration: none; font-weight: 800; font-size: 12px; text-transform: uppercase; transition: 0.3s; }
    .btn-view:hover { box-shadow: 0 0 15px rgba(0, 255, 136, 0.3); }
</style>

<div class="catalog-wrapper">
    <header style="margin-bottom: 40px;">
        <h1 style="font-family: 'Syncopate', sans-serif; font-size: 28px; margin-bottom: 10px;">
            <span style="color: var(--primary);">/</span> <?php echo htmlspecialchars($game['name']); ?>
        </h1>
        <div class="pill-group">
            <a href="catalog.php?game=<?php echo $game_slug; ?>" class="cat-pill <?php echo !$current_cat_slug ? 'active' : ''; ?>">All Offers</a>
            <?php foreach($categories as $cat): ?>
                <a href="catalog.php?game=<?php echo $game_slug; ?>&category=<?php echo $cat['slug']; ?>" 
                   class="cat-pill <?php echo ($current_cat_slug == $cat['slug']) ? 'active' : ''; ?>">
                    <?php echo htmlspecialchars($cat['name']); ?> 
                    <span><?php echo $cat['total_items']; ?></span>
                </a>
            <?php endforeach; ?>
        </div>
    </header>

    <form method="GET" class="filter-section">
        <input type="hidden" name="game" value="<?php echo $game_slug; ?>">
        <?php if($current_cat_slug): ?><input type="hidden" name="category" value="<?php echo $current_cat_slug; ?>"><?php endif; ?>

        <div style="display: flex; gap: 15px; align-items: center;">
            <select name="server" class="custom-select" onchange="this.form.submit()">
                <option value="">All Servers</option>
                <?php foreach($servers as $srv): ?>
                    <option value="<?php echo $srv; ?>" <?php echo ($filter_server == $srv) ? 'selected' : ''; ?>><?php echo $srv; ?></option>
                <?php endforeach; ?>
            </select>

            <select name="sort" class="custom-select" onchange="this.form.submit()">
                <option value="price_asc" <?php echo $sort == 'price_asc' ? 'selected' : ''; ?>>Cheapest First</option>
                <option value="price_desc" <?php echo $sort == 'price_desc' ? 'selected' : ''; ?>>Highest Price</option>
                <option value="stock_desc" <?php echo $sort == 'stock_desc' ? 'selected' : ''; ?>>Most Stock</option>
            </select>

            <label style="font-size: 13px; color: var(--text-gray); display: flex; align-items: center; gap: 8px; cursor: pointer;">
                <input type="checkbox" name="online" value="1" <?php echo $filter_online ? 'checked' : ''; ?> onchange="this.form.submit()">
                Online Sellers
            </label>
        </div>
        <div style="font-size: 12px; color: var(--text-gray);"><?php echo count($items); ?> listings found</div>
    </form>

    <table class="m-table">
        <thead>
            <tr>
                <th>Server / Platform</th>
                <th>Seller Info</th>
                <th>Stock</th>
                <th style="text-align: right;">Unit Price</th>
                <th></th>
            </tr>
        </thead>
        <tbody>
            <?php foreach($items as $item): 
                $is_online = (strtotime($item['last_seen']) > strtotime("-5 minutes"));
                $member_years = date('Y') - date('Y', strtotime($item['member_since']));
                $member_txt = ($member_years < 1) ? "New Seller" : "$member_years Year(s) Selling";
            ?>
            <tr class="m-row">
                <td class="m-td">
                    <span style="color: white; font-weight: 600; font-size: 14px;"><?php echo htmlspecialchars($item['server_name']); ?></span>
                    <div style="font-size: 11px; color: var(--text-gray); margin-top: 4px;"><?php echo htmlspecialchars($item['title']); ?></div>
                </td>
                <td class="m-td">
                    <div class="seller-info">
                        <span class="status-dot <?php echo $is_online ? 'is-online' : 'is-offline'; ?>"></span>
                        <div>
                            <a href="user_profile.php?u=<?php echo $item['username']; ?>" style="color: white; font-weight: bold; text-decoration: none;">
                                <?php echo htmlspecialchars($item['username']); ?>
                            </a>
                            <div class="seller-meta">
                                <span class="stars">
                                    <?php 
                                    $rating = round($item['avg_rating'] ?? 0);
                                    for($i=1; $i<=5; $i++) echo ($i <= $rating) ? '★' : '☆'; 
                                    ?>
                                </span>
                                (<?php echo $item['total_reviews']; ?>) • <?php echo $member_txt; ?>
                            </div>
                        </div>
                    </div>
                </td>
                <td class="m-td">
                    <span style="color: #fff; font-family: monospace;"><?php echo $item['stock']; ?></span>
                </td>
                <td class="m-td" style="text-align: right;">
                    <div class="price-tag"><span>$</span><?php echo number_format($item['price'], 2); ?></div>
                </td>
                <td class="m-td" style="text-align: center;">
                    <a href="product.php?id=<?php echo $item['id']; ?>" class="btn-view">Buy Now</a>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>

<?php include 'includes/footer.php'; ?>