<?php
session_start();
if (!isset($_SESSION['unohs'])) {
    header("Location: index.php");
    exit();
}

// ⚠️ Path ঠিক আছে কিনা নিশ্চিত করো
$gameListPath = __DIR__ . "/../deepanshu/api/webapi/GetAllGameList.php";

$message = '';

function loadGameList($path) {
    if (!file_exists($path)) return null;
    return json_decode(file_get_contents($path), true);
}

$gameData = loadGameList($gameListPath);
if ($gameData === null) {
    die("❌ File পড়া যায়নি। Path check করো: " . htmlspecialchars($gameListPath));
}

// ─────────────────────────────────────────────
// সব category-র তালিকা বের করা (nested popular.* সহ)
// ─────────────────────────────────────────────
$categories = []; // ['label' => 'fish', 'path' => ['fish']] অথবা ['label' => 'popular.clicksTopList', 'path' => ['popular','clicksTopList']]
foreach ($gameData['data'] as $key => $value) {
    if ($key === 'popular' && is_array($value)) {
        foreach ($value as $subKey => $subValue) {
            if (is_array($subValue)) {
                $categories[] = ['label' => "popular.$subKey", 'path' => ['popular', $subKey]];
            }
        }
    } elseif (is_array($value)) {
        $categories[] = ['label' => $key, 'path' => [$key]];
    }
}

// একটা category থেকে nested array reference বের করার helper
function &getArrayByPath(&$data, $path) {
    $ref = &$data;
    foreach ($path as $key) {
        $ref = &$ref[$key];
    }
    return $ref;
}

// ─────────────────────────────────────────────
// নতুন Game যোগ করা
// ─────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add') {
    $categoryPath = explode('.', $_POST['category']);
    $fieldsJson = $_POST['fields_json']; // পুরো নতুন game object, JSON আকারে (আগেই সঠিক schema মিলিয়ে বানানো)

    $newGame = json_decode($fieldsJson, true);
    if ($newGame === null) {
        $message = '❌ Game data সঠিক format-এ নেই।';
    } else {
        $targetArray = &getArrayByPath($gameData['data'], $categoryPath);
        $targetArray[] = $newGame;

        if (file_put_contents($gameListPath, json_encode($gameData, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE))) {
            $message = '✅ নতুন Game যোগ হয়েছে "' . htmlspecialchars($_POST['category']) . '"-তে।';
            $gameData = loadGameList($gameListPath);
        } else {
            $message = '❌ File-এ লিখতে পারলাম না — Permission (CHMOD) দেখো।';
        }
    }
}

// ─────────────────────────────────────────────
// একটা category-র প্রথম entry থেকে "নমুনা schema" বের করা
// (কোন category-তে কোন field লাগবে সেটা বোঝাতে)
// ─────────────────────────────────────────────
$selectedCategory = $_GET['category'] ?? ($categories[0]['label'] ?? '');
$sampleSchema = null;
$currentGames = [];

foreach ($categories as $cat) {
    if ($cat['label'] === $selectedCategory) {
        $arr = getArrayByPath($gameData['data'], $cat['path']);
        $currentGames = $arr;
        if (!empty($arr) && isset($arr[0])) {
            $sampleSchema = $arr[0];
        }
        break;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Manage Games - RAJ365 Admin</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="admin-gold-theme.css">
    <style>
        body { background: #0A0A0A; padding: 20px; }
        .game-card { background: #171512; border: 1px solid rgba(212,175,55,.25); border-radius: 10px; padding: 10px 14px; margin-bottom: 8px; font-size: 12.5px; }
        .form-box { background: #171512; border: 1px solid rgba(212,175,55,.3); border-radius: 14px; padding: 18px; margin-bottom: 24px; }
        .form-box select, .form-box textarea { background: #0A0A0A; border: 1px solid #3A3226; color: #F5EFDC; border-radius: 8px; padding: 8px 12px; width: 100%; margin-bottom: 10px; }
        .schema-hint { background: #0A0A0A; border: 1px solid #3A3226; border-radius: 8px; padding: 10px; font-size: 11.5px; color: #8A8270; margin-bottom: 12px; white-space: pre-wrap; word-break: break-all; }
    </style>
</head>
<body>
<div class="container" style="max-width:760px;">
    <h3 style="color:#D4AF37;">🎮 Manage Games</h3>

    <?php if ($message): ?>
        <div class="alert" style="background:#171512; border:1px solid #D4AF37; color:#F5EFDC;"><?= $message ?></div>
    <?php endif; ?>

    <form method="GET" style="margin-bottom:20px;">
        <label style="color:#8A8270; font-size:12px;">Category বেছে নাও</label>
        <select name="category" onchange="this.form.submit()" style="background:#171512; border:1px solid #3A3226; color:#F5EFDC; border-radius:8px; padding:8px 12px; width:100%;">
            <?php foreach ($categories as $cat): ?>
                <option value="<?= htmlspecialchars($cat['label']) ?>" <?= $cat['label'] === $selectedCategory ? 'selected' : '' ?>>
                    <?= htmlspecialchars($cat['label']) ?> (<?= count(getArrayByPath($gameData['data'], $cat['path'])) ?>টা game)
                </option>
            <?php endforeach; ?>
        </select>
    </form>

    <div class="form-box">
        <div style="color:#D4AF37; font-weight:700; margin-bottom:10px;">
            ➕ "<?= htmlspecialchars($selectedCategory) ?>"-তে নতুন Game যোগ করো
        </div>

        <?php if ($sampleSchema): ?>
            <div style="color:#8A8270; font-size:11.5px; margin-bottom:6px;">এই category-র জন্য যেসব field লাগবে (existing game থেকে detect করা):</div>
            <div class="schema-hint"><?= htmlspecialchars(json_encode($sampleSchema, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)) ?></div>
        <?php else: ?>
            <div style="color:#F0C419; font-size:11.5px; margin-bottom:6px;">⚠️ এই category-তে এখনো কোনো game নেই, তাই format জানা যাচ্ছে না। GetAllGameList.php-এর অন্য কোনো category থেকে একটা game-এর format দেখে সেই অনুযায়ী নিচে বসাও।</div>
        <?php endif; ?>

        <form method="POST">
            <input type="hidden" name="action" value="add">
            <input type="hidden" name="category" value="<?= htmlspecialchars($selectedCategory) ?>">
            <label style="color:#8A8270; font-size:12px;">নতুন Game-এর সম্পূর্ণ JSON (উপরের format ঠিক অনুসরণ করে, শুধু মান বদলে)</label>
            <textarea name="fields_json" rows="8" placeholder='<?= $sampleSchema ? htmlspecialchars(json_encode($sampleSchema, JSON_PRETTY_PRINT)) : "{...}" ?>' required></textarea>
            <button type="submit" class="btn" style="background:#D4AF37; color:#1A1400; font-weight:700; border-radius:10px;">Game যোগ করো</button>
        </form>
    </div>

    <div style="color:#D4AF37; font-weight:700; margin-bottom:10px;">বর্তমান Game-সমূহ (<?= count($currentGames) ?>টা)</div>
    <?php foreach ($currentGames as $g): ?>
        <div class="game-card">
            <?= htmlspecialchars($g['gameNameEn'] ?? '(নাম নেই)') ?>
            <span style="color:#8A8270;">— <?= htmlspecialchars($g['vendorCode'] ?? '') ?></span>
        </div>
    <?php endforeach; ?>

    <div style="margin-top:16px;">
        <a href="dashboard.php" style="color:#D4AF37;">← Dashboard-এ ফিরে যান</a>
    </div>
</div>
</body>
</html>
