<?php
/**
 * get_all_slots_combined.php
 * "ALL" Tab-এর জন্য — data/ Folder-এর সব Vendor-JSON File
 * একসাথে Combine করে, Pagination-সহ ফেরত দেয়।
 */
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');

$dataDir = __DIR__ . '/deepanshu/api/webapi/data/';

// ✅ get_vendor_games.php-এর সাথে একই তালিকা — সব Vendor-File
$vendorFileMap = [
    'CQ9' => 'cq9.json', 'JDB' => 'jdb.json', 'JILI' => 'jili.json',
    'PG' => 'pgsoft.json', 'KM' => 'km.json', 'EG' => 'eg.json',
    'IDG' => 'idg.json', 'V8' => 'v8.json', 'MG' => 'mg.json',
    'MG_FISH' => 'mg_fish.json', 'G9' => 'g9.json', '5G' => '5g.json',
    '2J' => '2j.json', 'BNG' => 'bng.json', 'BTG' => 'btg.json',
    '100HP' => '100hp.json', 'EAZYGAME' => 'eazygame.json',
    'FASTSPIN' => 'fastspin.json', 'INOUT' => 'inout.json',
    'BGAMING' => 'bgaming.json', 'TURBO' => 'turbo.json',
    'CARD365' => 'card365.json', 'PP' => 'pp.json',
    'PRAGMATIC' => 'PRAGMATIC.json',
];

$page = max(1, intval($_GET['page'] ?? 1));
$limit = max(1, intval($_GET['limit'] ?? 21));

// ✅ প্রতিটা Unique File একবারই পড়া হচ্ছে (একই File একাধিক
// Vendor-Code-এ Map হলেও, Duplicate এড়াতে)
$uniqueFiles = array_unique(array_values($vendorFileMap));
$allGames = [];

foreach ($uniqueFiles as $fileName) {
    $filePath = $dataDir . $fileName;
    if (!file_exists($filePath)) continue;

    $jsonData = json_decode(file_get_contents($filePath), true);
    if ($jsonData === null) continue; // Invalid JSON হলে Skip

    // ✅ bgaming.json-এর মতো "data.gameLists" Structure-ও Support করা
    $games = $jsonData['data']['gameLists'] ?? $jsonData['gameLists'] ?? $jsonData ?? [];
    if (!is_array($games)) continue;

    // ✅ কোন Vendor-Code এই File-এর সাথে Map করা, তা খুঁজে বের করা
    $vendorCode = array_search($fileName, $vendorFileMap) ?: '';

    foreach ($games as $g) {
        if (!is_array($g)) continue;
        $g['vendorCode'] = $g['vendorCode'] ?? $vendorCode;
        if ($g['vendorCode'] === '0' || empty($g['vendorCode'])) {
            $g['vendorCode'] = $vendorCode;
        }
        $allGames[] = $g;
    }
}

$total = count($allGames);
$offset = ($page - 1) * $limit;
$pagedGames = array_slice($allGames, $offset, $limit);

echo json_encode([
    'code' => 0,
    'games' => $pagedGames,
    'total' => $total,
    'page' => $page,
    'has_more' => ($offset + $limit) < $total
]);
