<?php
// 1. ENABLE ERROR REPORTING
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();
$db_path = file_exists('includes/db.php') ? 'includes/db.php' : '../includes/db.php';

if (file_exists($db_path)) {
    require $db_path;
} else {
    $conn = new mysqli('localhost', 'root', '', 'bajipari');
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
}

// Check Login
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

// ---------------------------------------------------
// 1. DYNAMIC CATEGORY LOGIC
// ---------------------------------------------------

// Icon Mapping
$icon_map = [
    'slots'     => 'fa-gamepad',
    'live'      => 'fa-video',
    'crash'     => 'fa-rocket',
    'fishing'   => 'fa-fish',
    'sports'    => 'fa-futbol',
    'table'     => 'fa-dice',
    'arcade'    => 'fa-ghost',
    'poker'     => 'fa-diamond',
    'roulette'  => 'fa-circle-notch',
    'flash'     => 'fa-bolt'
];

$final_categories = [];
$final_categories['all'] = ['name' => 'All Games', 'icon' => 'fa-th-large'];
$final_categories['hot'] = ['name' => 'Hot Games', 'icon' => 'fa-fire'];

// Fetch Categories (Using status='active')
$cat_sql = "SELECT DISTINCT category FROM games WHERE status='active' AND category IS NOT NULL AND category != '' ORDER BY category ASC";
$cat_res = $conn->query($cat_sql);

if ($cat_res) {
    while ($row = $cat_res->fetch_assoc()) {
        $db_slug = strtolower(trim($row['category']));
        $icon = isset($icon_map[$db_slug]) ? $icon_map[$db_slug] : 'fa-puzzle-piece';
        $final_categories[$db_slug] = [
            'name' => ucfirst($db_slug),
            'icon' => $icon
        ];
    }
}

// URL Parameters
$current_cat = isset($_GET['cat']) ? $_GET['cat'] : 'all';
$current_provider = isset($_GET['provider']) ? $_GET['provider'] : '';

// ---------------------------------------------------
// 2. FETCH PROVIDERS (BRANDS) FROM game_providers TABLE
// ---------------------------------------------------
$brands = [];

// [UPDATED] সরাসরি game_providers টেবিল থেকে ডাটা আনা হচ্ছে
$brand_sql = "SELECT provider_id, name, image FROM game_providers WHERE status='active' ORDER BY name ASC";
$brand_res = $conn->query($brand_sql);

if ($brand_res) {
    while($b = $brand_res->fetch_assoc()) {
        // provider_id যদি খালি থাকে তবে name ব্যবহার করবে
        $pid = !empty($b['provider_id']) ? $b['provider_id'] : $b['name'];
        
        $brands[] = [
            'id'    => $pid,
            'name'  => $b['name'],
            'image' => $b['image'] 
        ];
    }
}

// ---------------------------------------------------
// 3. FETCH GAMES (LOGIC)
// ---------------------------------------------------
$games = [];
$where_clauses = ["status = 'active'"];

// Filter Logic: Category
if ($current_cat != 'all') {
    if ($current_cat == 'hot') {
        $where_clauses[] = "is_hot = 1";
    } else {
        $safe_cat = $conn->real_escape_string($current_cat);
        $where_clauses[] = "category = '$safe_cat'";
    }
}

// Filter Logic: Provider (Brand)
if (!empty($current_provider)) {
    $prov_slug = $conn->real_escape_string($current_provider);
    // games টেবিলে provider_id কলামের সাথে ম্যাচ করা হচ্ছে
    $where_clauses[] = "provider_id = '$prov_slug'";
}

$sql = "SELECT * FROM games";
if (count($where_clauses) > 0) {
    $sql .= " WHERE " . implode(' AND ', $where_clauses);
}
$sql .= " ORDER BY id DESC LIMIT 100";

$result = $conn->query($sql);
if ($result && $result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $games[] = $row;
    }
}
?>

<!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>Game Lobby</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 href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap" rel="stylesheet">
    
    <style>
        body { 
            font-family: 'Roboto', sans-serif;
            background-color: #121212; 
            color: #d1d5db; 
            padding-bottom: 90px; 
            -webkit-tap-highlight-color: transparent;
        }
        
        /* --- BRAND MARQUEE SLIDER --- */
        .brand-wrapper {
            background: #1a1a1a;
            border-bottom: 1px solid #333;
            padding: 12px 0;
            overflow: hidden;
            position: relative;
        }
        .marquee-track {
            display: flex;
            gap: 15px;
            width: max-content;
            animation: scroll 40s linear infinite; /* Smooth Slow Scroll */
        }
        .marquee-track:hover { animation-play-state: paused; }

        @keyframes scroll {
            0% { transform: translateX(0); }
            100% { transform: translateX(-50%); }
        }

        .brand-pill {
            background: #252525;
            color: #aaa;
            padding: 0 15px;
            border-radius: 8px;
            border: 1px solid #333;
            font-size: 12px;
            font-weight: 600;
            text-transform: uppercase;
            white-space: nowrap;
            transition: all 0.3s;
            display: flex; align-items: center; justify-content: center;
            text-decoration: none;
            height: 45px;
            min-width: 100px;
            position: relative;
            overflow: hidden;
        }
        
        .brand-pill img {
            max-height: 28px;
            max-width: 80px;
            object-fit: contain;
            filter: grayscale(100%);
            opacity: 0.7;
            transition: 0.3s;
        }

        /* Hover & Active State */
        .brand-pill:hover, .brand-pill.active {
            background: #2A2A2A; 
            border-color: #eab308;
            box-shadow: 0 0 10px rgba(234, 179, 8, 0.1);
        }
        .brand-pill:hover img, .brand-pill.active img {
            filter: grayscale(0%);
            opacity: 1;
        }
        .brand-pill.active span, .brand-pill:hover span {
            color: #eab308;
        }

        /* --- STICKY Categories --- */
        .sticky-cat-nav {
            position: sticky; top: 60px; z-index: 40;
            background-color: #121212;
            padding: 10px 0;
            border-bottom: 1px solid #2a2a2a;
        }
        .cat-scroll::-webkit-scrollbar { display: none; }
        
        .cat-item { 
            min-width: 70px; 
            display: flex; flex-direction: column; align-items: center; gap: 6px; 
            text-decoration: none; opacity: 0.6; transition: 0.3s;
        }
        .cat-item.cat-active { opacity: 1; }

        .cat-icon-box {
            width: 45px; height: 45px;
            border-radius: 10px;
            display: flex; align-items: center; justify-content: center;
            font-size: 20px;
            color: #9ca3af;
            background: #252525;
            border: 1px solid #333;
            transition: all 0.3s;
        }
        
        .cat-active .cat-icon-box { 
            border: 1px solid #eab308; color: #eab308; background: #2A2A2A; 
            box-shadow: 0 0 10px rgba(234, 179, 8, 0.2);
        }
        .cat-active span { color: #eab308; font-weight: bold; }

        /* --- Game Card --- */
        .game-card-new {
            background: #1c1c1c; border-radius: 8px; overflow: hidden;
            border: 1px solid #2a2a2a; position: relative;
            cursor: pointer; transition: transform 0.2s;
        }
        .game-card-new:hover { border-color: #eab308; transform: translateY(-2px); }
        
        .game-img-wrapper {
            width: 100%; aspect-ratio: 1/1; position: relative; background: #000;
        }
        .game-img-wrapper img { width: 100%; height: 100%; object-fit: cover; }
        .game-info { padding: 8px; text-align: center; }
        .game-title-text {
            font-size: 11px; color: #fff; white-space: nowrap; 
            overflow: hidden; text-overflow: ellipsis; font-weight: 600;
        }
        .game-provider-text { font-size: 9px; color: #666; text-transform: uppercase; }
    </style>
</head>
<body>

    <header class="flex justify-between items-center px-4 py-4 bg-[#161616] sticky top-0 z-50 border-b border-gray-800 h-[60px]">
        <a href="index.php" class="text-white text-xl"><i class="fas fa-chevron-left"></i></a>
        <h1 class="text-lg font-bold text-white">Game Lobby</h1>
        <a href="search.php" class="text-white text-lg"><i class="fas fa-search"></i></a> 
    </header>

    <?php if(!empty($brands)): ?>
    <div class="brand-wrapper">
        <div class="marquee-track">
            
            <?php 
            // FUNCTION TO RENDER BRAND PILL
            function renderBrandPill($brand, $current_provider, $current_cat) {
                $isActiveBrand = ($current_provider == $brand['id']) ? 'active' : '';
                // Image handling: assuming path is stored in DB relative to root or full URL
                $hasImage = !empty($brand['image']); 
                $imgSrc = (strpos($brand['image'], 'http') === 0) ? $brand['image'] : "../" . $brand['image'];
                ?>
                <a href="?cat=<?php echo $current_cat; ?>&provider=<?php echo urlencode($brand['id']); ?>" class="brand-pill <?php echo $isActiveBrand; ?>">
                    <?php if($hasImage): ?>
                        <img src="<?php echo $imgSrc; ?>" alt="<?php echo $brand['name']; ?>" onerror="this.style.display='none';this.nextElementSibling.style.display='block';">
                        <span style="display:none;"><?php echo $brand['name']; ?></span>
                    <?php else: ?>
                        <span><?php echo $brand['name']; ?></span>
                    <?php endif; ?>
                </a>
            <?php } ?>

            <?php foreach($brands as $brand) { renderBrandPill($brand, $current_provider, $current_cat); } ?>

            <?php foreach($brands as $brand) { renderBrandPill($brand, $current_provider, $current_cat); } ?>

        </div>
    </div>
    <?php endif; ?>

    <div class="sticky-cat-nav px-2">
        <div class="flex overflow-x-auto cat-scroll gap-3 px-1">
            <?php foreach($final_categories as $slug => $data): 
                $isActive = ($current_cat == $slug);
                $activeClass = $isActive ? 'cat-active' : '';
            ?>
            <a href="?cat=<?php echo $slug; ?>&provider=<?php echo urlencode($current_provider); ?>" class="cat-item <?php echo $activeClass; ?>">
                <div class="cat-icon-box">
                    <i class="fas <?php echo $data['icon']; ?>"></i>
                </div>
                <span class="text-[10px] text-gray-400 font-medium"><?php echo $data['name']; ?></span>
            </a>
            <?php endforeach; ?>
        </div>
    </div>

    <div class="p-3 min-h-[60vh]">
        
        <div class="flex items-center justify-between mb-4 px-1">
            <div class="flex items-center gap-2">
                <div class="w-1 h-5 bg-yellow-500 rounded-full"></div>
                <h2 class="text-white font-bold text-base">
                    <?php echo $final_categories[$current_cat]['name'] ?? ucfirst($current_cat); ?> 
                    <?php echo $current_provider ? "($current_provider)" : ""; ?>
                </h2>
            </div>
            <span class="text-xs text-gray-500 font-mono"><?php echo count($games); ?> games</span>
        </div>

        <?php if(!empty($games)): ?>
            <div class="grid grid-cols-3 sm:grid-cols-4 md:grid-cols-6 gap-3">
                <?php foreach($games as $game): 
                    $img_src = (strpos($game['image'], 'http') === 0) ? $game['image'] : "../" . $game['image'];
                    $launch_link = "launch.php?game_id=" . $game['game_uid']; 
                ?>
                
                <a href="<?php echo $launch_link; ?>" class="game-card-new group block">
                    <div class="game-img-wrapper">
                        <img src="<?php echo $img_src; ?>" loading="lazy" onerror="this.src='https://placehold.co/150x150/252525/FFF?text=GAME'">
                        <?php if(isset($game['is_hot']) && $game['is_hot']): ?>
                            <div class="absolute top-0 right-0 bg-red-600 text-white text-[8px] font-bold px-1.5 py-0.5 rounded-bl shadow">HOT</div>
                        <?php endif; ?>
                    </div>
                    <div class="game-info">
                        <div class="game-title-text"><?php echo htmlspecialchars($game['name']); ?></div>
                        <div class="game-provider-text"><?php echo htmlspecialchars($game['provider_id']); ?></div>
                    </div>
                </a>

                <?php endforeach; ?>
            </div>
        <?php else: ?>
            <div class="flex flex-col items-center justify-center pt-20 opacity-50">
                <div class="w-16 h-16 bg-[#222] rounded-full flex items-center justify-center mb-3">
                    <i class="fas fa-search text-2xl text-gray-600"></i>
                </div>
                <p class="text-gray-400 text-sm font-bold">No Games Found</p>
                <p class="text-gray-600 text-xs mt-1">
                    <?php if($current_provider): ?>
                        No games available for <b><?php echo $current_provider; ?></b> in this category.
                    <?php else: ?>
                        Try a different category.
                    <?php endif; ?>
                </p>
                <a href="?cat=all" class="mt-4 px-4 py-2 bg-[#252525] border border-[#333] rounded text-xs text-yellow-500 hover:bg-[#333] transition">
                    View All Games
                </a>
            </div>
        <?php endif; ?>

    </div>

</body>
</html> 