<?php
session_start();

require '../includes/db.php'; 

// 1. Validation
if (!isset($_GET['cat_id']) || empty($_GET['cat_id'])) {
    header("Location: dashboard.php");
    exit;
}

$cat_id = (int)$_GET['cat_id'];
$selected_provider = isset($_GET['provider']) ? $_GET['provider'] : 'all';

// 2. Fetch Category Name
$cat_query = $conn->query("SELECT name FROM front_categories WHERE id = $cat_id LIMIT 1");
if ($cat_query->num_rows == 0) {
    header("Location: dashboard.php");
    exit;
}
$category = $cat_query->fetch_assoc();
$cat_name = $category['name'];

// 3. Fetch Unique Providers (Only those available in this category)
$prov_query = $conn->query("
    SELECT DISTINCT g.provider_id 
    FROM front_category_games fcg 
    JOIN games g ON fcg.game_uid = g.game_uid 
    WHERE fcg.category_id = $cat_id
    ORDER BY g.provider_id ASC
");

// 4. Build Game Query with Filter
$sql = "SELECT g.* FROM front_category_games fcg 
        JOIN games g ON fcg.game_uid = g.game_uid 
        WHERE fcg.category_id = $cat_id";

if ($selected_provider != 'all') {
    $safe_prov = $conn->real_escape_string($selected_provider);
    $sql .= " AND g.provider_id = '$safe_prov'";
}

$sql .= " ORDER BY fcg.id DESC";
$games_query = $conn->query($sql);

// 5. User Balance
$is_logged_in = isset($_SESSION['user_id']);
$balance = 0.00;
if ($is_logged_in) {
    $uid = $_SESSION['user_id'];
    $u_res = $conn->query("SELECT balance FROM users WHERE id=$uid");
    if($u_res && $u_res->num_rows > 0){
        $balance = $u_res->fetch_assoc()['balance'];
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title><?php echo $cat_name; ?> - All Games</title>
    
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swiper@10/swiper-bundle.min.css" />
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700;900&display=swap" rel="stylesheet">

    <style>
        :root {
            --bg-color: #013328;
            --header-color: #126E51;
            --accent-color: #FFDF1B;
            --card-bg: #104239;
            --text-gray: #b2d6ce;
        }

        body { 
            font-family: 'Roboto', sans-serif;
            background-color: var(--bg-color); 
            color: #ffffff;
            padding-bottom: 20px;
            -webkit-tap-highlight-color: transparent;
            user-select: none;
        }

        /* Header */
        .header-fixed {
            position: sticky; top: 0; z-index: 50;
            background-color: var(--header-color);
            border-bottom: 1px solid #0e5640;
            box-shadow: 0 2px 8px rgba(0,0,0,0.3);
            height: 60px; display: flex; align-items: center; justify-content: space-between;
            padding: 0 15px;
        }

        .back-btn {
            color: white; font-size: 18px; display: flex; align-items: center; gap: 5px;
            padding: 5px; transition: all 0.2s;
        }
        .back-btn:active { color: var(--accent-color); transform: scale(0.9); }

        /* --- BRAND SLIDER STYLES --- */
        .brand-slider-container {
            background: #0e3027;
            padding: 10px 0;
            border-bottom: 1px solid #1a5c4e;
            position: sticky; top: 60px; z-index: 40; /* Stick below header */
        }
        
        .brand-chip {
            display: flex; flex-direction: column; align-items: center; justify-content: center;
            width: auto; height: 50px; min-width: 60px;
            background: #1c5244; 
            border: 1px solid #236353;
            border-radius: 8px;
            padding: 5px 10px;
            transition: all 0.2s;
            cursor: pointer;
        }

        /* Active Brand State */
        .brand-chip.active {
            border-color: var(--accent-color);
            background: #2a6b5a;
            box-shadow: 0 0 8px rgba(255, 223, 27, 0.2);
        }
        .brand-chip.active .brand-name { color: var(--accent-color); font-weight: bold; }
        .brand-chip.active .brand-icon { color: var(--accent-color); }

        /* Touch Effect */
        .brand-chip:active { transform: scale(0.95); }

        .brand-icon { font-size: 16px; color: var(--text-gray); margin-bottom: 2px; }
        .brand-name { font-size: 10px; color: #ccc; text-transform: uppercase; white-space: nowrap; }

        .swiper-slide { width: auto !important; } /* Allow variable width chips */

        /* --- Game Card --- */
        .game-card-new {
            background: var(--card-bg); 
            border-radius: 8px;
            overflow: hidden;
            display: flex; flex-direction: column; align-items: center;
            padding: 6px; 
            border: 1px solid #236353;
            position: relative;
            transition: all 0.15s ease-out;
        }
        .game-card-new:active { 
            transform: scale(0.95); 
            border-color: var(--accent-color);
            box-shadow: 0 0 12px rgba(255, 223, 27, 0.3);
        }

        .game-img-wrapper {
            width: 100%; aspect-ratio: 1 / 1; margin-bottom: 6px; position: relative; overflow: hidden; border-radius: 6px;
        }
        .game-img-wrapper img {
            width: 100%; height: 100%; object-fit: cover; object-position: center;
            box-shadow: 0 4px 10px rgba(0,0,0,0.4);
        }
        
        .game-title-text {
            font-size: 11px; color: #e5e7eb; text-align: center;
            white-space: nowrap; overflow: hidden; text-overflow: ellipsis; width: 100%; font-weight: 500;
        }

        .text-accent { color: var(--accent-color); }
        .bg-accent { background-color: var(--accent-color); color: black; }
        
        /* Hide scrollbar */
        .no-scrollbar::-webkit-scrollbar { display: none; }
        .no-scrollbar { -ms-overflow-style: none; scrollbar-width: none; }
    </style>
</head>
<body>

    <header class="header-fixed">
        <div class="flex items-center gap-4">
            <a href="dashboard.php" class="back-btn">
                <i class="fas fa-arrow-left"></i> 
            </a>
            <h1 class="text-lg font-bold text-white uppercase tracking-wide truncate max-w-[150px]">
                <?php echo htmlspecialchars($cat_name); ?>
            </h1>
        </div>

        <?php if($is_logged_in): ?>
            <div class="flex flex-col items-end leading-none">
                <span class="text-[10px] text-gray-300">Balance</span>
                <span class="text-accent text-sm font-bold">৳<?php echo number_format($balance, 2); ?></span>
            </div>
        <?php else: ?>
            <a href="login.php" class="bg-accent px-3 py-1 rounded text-xs font-bold active:scale-95 transition">Login</a>
        <?php endif; ?>
    </header>

    <div class="brand-slider-container">
        <div class="swiper brandSlider px-3">
            <div class="swiper-wrapper">
                
                <div class="swiper-slide">
                    <a href="?cat_id=<?php echo $cat_id; ?>&provider=all" 
                       class="brand-chip <?php echo ($selected_provider == 'all') ? 'active' : ''; ?>">
                        <i class="fas fa-th-large brand-icon"></i>
                        <span class="brand-name">All</span>
                    </a>
                </div>

                <?php while($prov = $prov_query->fetch_assoc()): 
                    $pName = htmlspecialchars($prov['provider_id']);
                    $isActive = ($selected_provider == $prov['provider_id']) ? 'active' : '';
                ?>
                <div class="swiper-slide">
                    <a href="?cat_id=<?php echo $cat_id; ?>&provider=<?php echo urlencode($prov['provider_id']); ?>" 
                       class="brand-chip <?php echo $isActive; ?>">
                        <i class="fas fa-gamepad brand-icon"></i> <span class="brand-name"><?php echo $pName; ?></span>
                    </a>
                </div>
                <?php endwhile; ?>

            </div>
        </div>
    </div>

    <div class="p-3">
        
        <div class="flex items-center justify-between mb-4">
            <p class="text-gray-400 text-xs">
                Found <span class="text-white font-bold"><?php echo $games_query->num_rows; ?></span> games 
                <?php if($selected_provider != 'all') echo "for <span class='text-accent'>".htmlspecialchars($selected_provider)."</span>"; ?>
            </p>
        </div>

        <?php if($games_query->num_rows > 0): ?>
            <div class="grid grid-cols-3 sm:grid-cols-4 md:grid-cols-5 gap-3 pb-10">
                <?php while($g = $games_query->fetch_assoc()): 
                    if ($is_logged_in) {
                        $link = "launch.php?game_id=" . $g['game_uid'];
                    } else {
                        $redirect = urlencode("launch.php?game_id=" . $g['game_uid']);
                        $link = "login.php?redirect=" . $redirect;
                    }
                ?>
                    <a href="<?php echo $link; ?>" class="game-card-new group">
                        <div class="game-img-wrapper">
                            <img src="<?php echo $g['image']; ?>" onerror="this.src='https://placehold.co/100x100/104239/FFF?text=GAME'">
                        </div>
                        <div class="game-title-text"><?php echo $g['name']; ?></div>
                    </a>
                <?php endwhile; ?>
            </div>
        <?php else: ?>
            <div class="flex flex-col items-center justify-center h-[50vh] text-gray-500">
                <i class="fas fa-search text-4xl mb-3 opacity-50"></i>
                <p>No games found for this provider.</p>
                <a href="?cat_id=<?php echo $cat_id; ?>&provider=all" class="mt-4 text-accent text-sm font-bold border border-accent px-4 py-2 rounded active:scale-95 transition">Show All</a>
            </div>
        <?php endif; ?>

    </div>

    <script src="https://cdn.jsdelivr.net/npm/swiper@10/swiper-bundle.min.js"></script>
    <script>
        // Init Brand Slider
        new Swiper(".brandSlider", { 
            slidesPerView: "auto", // Width based on content
            spaceBetween: 10,
            freeMode: true, // Smooth scrolling
        });
    </script>

</body>
</html>