<?php

declare(strict_types=1);

/*
|--------------------------------------------------------------------------
| LOGIN SEMENTARA
|--------------------------------------------------------------------------
| GANTI password ini sebelum halaman diunggah.
*/

$temporaryPassword = 'Rute28@Popular2026';

if (session_status() === PHP_SESSION_NONE) {
    session_name('POPULARMANAGERSESSID');
    session_start();
}

/*
|--------------------------------------------------------------------------
| Koneksi database PDO
|--------------------------------------------------------------------------
| Struktur project menggunakan public_html/config/database.php
| dan menyediakan variabel $pdo.
*/

$connectionFile = __DIR__ . '/config/database.php';

if (!is_file($connectionFile)) {
    http_response_code(500);
    exit('File config/database.php tidak ditemukan.');
}

require_once $connectionFile;

if (!isset($pdo) || !($pdo instanceof PDO)) {
    http_response_code(500);
    exit('Koneksi PDO $pdo tidak tersedia dari config/database.php.');
}

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

if (!function_exists('e')) {
    function e($value)
    {
        return htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8');
    }
}

if (empty($_SESSION['popular_manager_csrf'])) {
    $_SESSION['popular_manager_csrf'] = bin2hex(random_bytes(32));
}

$csrfToken = (string) $_SESSION['popular_manager_csrf'];

function validCsrf($token)
{
    return is_string($token) &&
        isset($_SESSION['popular_manager_csrf']) &&
        hash_equals(
            (string) $_SESSION['popular_manager_csrf'],
            $token
        );
}

function setFlash($type, $message)
{
    $_SESSION['popular_manager_flash'] = [
        'type' => (string) $type,
        'message' => (string) $message,
    ];
}

function redirectTo($url)
{
    header('Location: ' . $url);
    exit;
}

$self = basename((string) $_SERVER['PHP_SELF']);

/*
|--------------------------------------------------------------------------
| Logout
|--------------------------------------------------------------------------
*/

if (isset($_GET['logout'])) {
    unset($_SESSION['popular_manager_auth']);
    redirectTo($self);
}

/*
|--------------------------------------------------------------------------
| Proses login sementara
|--------------------------------------------------------------------------
*/

if (
    $_SERVER['REQUEST_METHOD'] === 'POST' &&
    isset($_POST['login_password'])
) {
    if (!validCsrf($_POST['csrf_token'] ?? '')) {
        $loginError = 'Token keamanan tidak valid. Muat ulang halaman.';
    } elseif (
        hash_equals(
            $temporaryPassword,
            (string) $_POST['login_password']
        )
    ) {
        $_SESSION['popular_manager_auth'] = 1;
        session_regenerate_id(true);
        redirectTo($self);
    } else {
        $loginError = 'Password salah.';
    }
}

$isAuthenticated = !empty($_SESSION['popular_manager_auth']);

if (!$isAuthenticated):
?>
<!doctype html>
<html lang="id">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Login Popular Game</title>
    <style>
        * { box-sizing: border-box; }
        body {
            margin: 0;
            min-height: 100vh;
            display: grid;
            place-items: center;
            padding: 20px;
            color: #eef6ff;
            background: #020817;
            font-family: Arial, Helvetica, sans-serif;
        }
        .login-box {
            width: min(100%, 390px);
            padding: 24px;
            border: 1px solid #1f90ff;
            border-radius: 18px;
            background: linear-gradient(145deg, #08264c, #031126);
            box-shadow: 0 20px 50px rgba(0,0,0,.45), 0 0 25px rgba(0,132,255,.18);
        }
        h1 { margin: 0 0 7px; font-size: 23px; }
        p { margin: 0 0 18px; color: #9eb4ce; font-size: 13px; line-height: 1.5; }
        label { display: block; margin-bottom: 7px; font-size: 12px; font-weight: 800; }
        input {
            width: 100%;
            height: 45px;
            padding: 0 13px;
            border: 1px solid #265a91;
            border-radius: 10px;
            color: #fff;
            background: #020b1d;
            outline: none;
        }
        input:focus { border-color: #36b8ff; box-shadow: 0 0 0 3px rgba(54,184,255,.13); }
        button {
            width: 100%;
            height: 44px;
            margin-top: 12px;
            border: 0;
            border-radius: 10px;
            color: #06130d;
            background: linear-gradient(180deg, #baffdc, #27d989 65%, #09814c);
            font-weight: 900;
            cursor: pointer;
        }
        .error {
            margin-bottom: 12px;
            padding: 10px;
            border: 1px solid #ff5555;
            border-radius: 9px;
            color: #ffd3d3;
            background: rgba(255,0,0,.10);
            font-size: 12px;
        }
    </style>
</head>
<body>
    <form class="login-box" method="post" autocomplete="off">
        <h1>Popular Game Manager</h1>
        <p>Halaman sementara untuk memilih game populer dari tabel games_sgx dan games_nexus.</p>

        <?php if (!empty($loginError)): ?>
            <div class="error"><?= e($loginError); ?></div>
        <?php endif; ?>

        <input type="hidden" name="csrf_token" value="<?= e($csrfToken); ?>">

        <label for="login_password">Password sementara</label>
        <input
            type="password"
            id="login_password"
            name="login_password"
            required
            autofocus
        >

        <button type="submit">Masuk</button>
    </form>
</body>
</html>
<?php
exit;
endif;

/*
|--------------------------------------------------------------------------
| Sumber tabel yang diperbolehkan
|--------------------------------------------------------------------------
*/

$tableMap = [
    'sgx' => [
        'table' => 'games_sgx',
        'provider_column' => 'game_provider',
        'label' => 'SGX',
    ],
    'nexus' => [
        'table' => 'games_nexus',
        'provider_column' => 'provider_code',
        'label' => 'NEXUS',
    ],
];

$typeLabels = [
    'SL' => 'Slot',
    'LC' => 'Live Casino',
    'SB' => 'Sports',
    'FH' => 'Fishing',
    'CB' => 'Card',
    'PK' => 'Poker',
    'ES' => 'E-Sports',
    'MN' => 'Mini Game',
    'OT' => 'Other / Sabung',
    'LK' => 'Lottery / Togel',
    'UNMAPPED' => 'Belum Dipetakan',
];

function updateOneGame(PDO $pdo, array $tableMap, $source, $id, $isPopular, $popularOrder)
{
    if (!isset($tableMap[$source])) {
        throw new RuntimeException('Sumber game tidak valid.');
    }

    $id = (int) $id;
    $isPopular = $isPopular ? 1 : 0;
    $popularOrder = max(0, (int) $popularOrder);

    if ($id < 1) {
        throw new RuntimeException('ID game tidak valid.');
    }

    if ($isPopular === 0) {
        $popularOrder = 0;
    }

    $table = $tableMap[$source]['table'];

    $stmt = $pdo->prepare(
        "UPDATE `{$table}`
         SET `is_popular` = :is_popular,
             `popular_order` = :popular_order
         WHERE `id` = :id
         LIMIT 1"
    );

    $stmt->execute([
        ':is_popular' => $isPopular,
        ':popular_order' => $popularOrder,
        ':id' => $id,
    ]);
}

/*
|--------------------------------------------------------------------------
| Filter halaman
|--------------------------------------------------------------------------
*/

$source = isset($_GET['source'])
    ? strtolower(trim((string) $_GET['source']))
    : 'all';

if (!in_array($source, ['all', 'sgx', 'nexus'], true)) {
    $source = 'all';
}

$type = isset($_GET['type'])
    ? strtoupper(trim((string) $_GET['type']))
    : '';

if (!preg_match('/^[A-Z0-9_-]{0,30}$/', $type)) {
    $type = '';
}

$provider = isset($_GET['provider'])
    ? trim((string) $_GET['provider'])
    : '';

if (strlen($provider) > 80) {
    $provider = substr($provider, 0, 80);
}

$popularFilter = isset($_GET['popular'])
    ? (string) $_GET['popular']
    : 'all';

if (!in_array($popularFilter, ['all', '1', '0'], true)) {
    $popularFilter = 'all';
}

$search = isset($_GET['q'])
    ? trim((string) $_GET['q'])
    : '';

if (strlen($search) > 100) {
    $search = substr($search, 0, 100);
}

$perPage = isset($_GET['per_page'])
    ? (int) $_GET['per_page']
    : 24;

if (!in_array($perPage, [24, 48, 96], true)) {
    $perPage = 24;
}

$page = isset($_GET['page'])
    ? max(1, (int) $_GET['page'])
    : 1;

$returnParams = [
    'source' => $source,
    'type' => $type,
    'provider' => $provider,
    'popular' => $popularFilter,
    'q' => $search,
    'per_page' => $perPage,
    'page' => $page,
];

$returnUrl = $self . '?' . http_build_query($returnParams);

/*
|--------------------------------------------------------------------------
| Proses perubahan data
|--------------------------------------------------------------------------
*/

if (
    $_SERVER['REQUEST_METHOD'] === 'POST' &&
    !isset($_POST['login_password'])
) {
    $postedReturn = isset($_POST['return_url'])
        ? (string) $_POST['return_url']
        : $returnUrl;

    if (strpos($postedReturn, $self) !== 0) {
        $postedReturn = $returnUrl;
    }

    try {
        if (!validCsrf($_POST['csrf_token'] ?? '')) {
            throw new RuntimeException('Token keamanan tidak valid.');
        }

        $action = isset($_POST['action'])
            ? (string) $_POST['action']
            : '';

        if ($action === 'toggle') {
            $postedSource = strtolower((string) ($_POST['source'] ?? ''));
            $gameId = (int) ($_POST['game_id'] ?? 0);
            $newPopular = (int) ($_POST['new_popular'] ?? 0) === 1;
            $order = (int) ($_POST['popular_order'] ?? 0);

            if ($newPopular && $order < 1) {
                $order = 999;
            }

            updateOneGame(
                $pdo,
                $tableMap,
                $postedSource,
                $gameId,
                $newPopular,
                $order
            );

            setFlash(
                'success',
                $newPopular
                    ? 'Game berhasil dijadikan populer.'
                    : 'Status populer berhasil dibatalkan.'
            );
        } elseif ($action === 'save_order') {
            $postedSource = strtolower((string) ($_POST['source'] ?? ''));
            $gameId = (int) ($_POST['game_id'] ?? 0);
            $order = max(1, (int) ($_POST['popular_order'] ?? 1));

            updateOneGame(
                $pdo,
                $tableMap,
                $postedSource,
                $gameId,
                true,
                $order
            );

            setFlash('success', 'Urutan populer berhasil disimpan.');
        } elseif ($action === 'bulk') {
            $operation = isset($_POST['bulk_operation'])
                ? (string) $_POST['bulk_operation']
                : '';

            $selected = isset($_POST['selected']) && is_array($_POST['selected'])
                ? $_POST['selected']
                : [];

            if (!in_array($operation, ['popular', 'unpopular'], true)) {
                throw new RuntimeException('Aksi massal tidak valid.');
            }

            if (empty($selected)) {
                throw new RuntimeException('Pilih minimal satu game.');
            }

            $pdo->beginTransaction();
            $changed = 0;
            $nextOrder = 1;

            if ($operation === 'popular') {
                $maxOrder = (int) $pdo->query(
                    "SELECT MAX(popular_order) FROM (
                        SELECT popular_order FROM games_sgx WHERE is_popular = 1
                        UNION ALL
                        SELECT popular_order FROM games_nexus WHERE is_popular = 1
                    ) AS popular_orders"
                )->fetchColumn();

                $nextOrder = max(1, $maxOrder + 1);
            }

            foreach ($selected as $selectedKey) {
                $parts = explode(':', (string) $selectedKey, 2);

                if (count($parts) !== 2) {
                    continue;
                }

                $selectedSource = strtolower($parts[0]);
                $selectedId = (int) $parts[1];

                if (!isset($tableMap[$selectedSource]) || $selectedId < 1) {
                    continue;
                }

                updateOneGame(
                    $pdo,
                    $tableMap,
                    $selectedSource,
                    $selectedId,
                    $operation === 'popular',
                    $operation === 'popular' ? $nextOrder : 0
                );

                if ($operation === 'popular') {
                    $nextOrder++;
                }

                $changed++;
            }

            $pdo->commit();

            setFlash(
                'success',
                $changed . ' game berhasil diperbarui.'
            );
        } else {
            throw new RuntimeException('Aksi tidak dikenali.');
        }
    } catch (Throwable $exception) {
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }

        setFlash('error', $exception->getMessage());
    }

    redirectTo($postedReturn);
}

/*
|--------------------------------------------------------------------------
| Ambil opsi filter
|--------------------------------------------------------------------------
*/

$typeRows = $pdo->query(
    "SELECT DISTINCT UPPER(game_type) AS game_type
     FROM (
        SELECT game_type FROM games_sgx WHERE game_status = 1 AND is_active = 1
        UNION ALL
        SELECT game_type FROM games_nexus WHERE game_status = 1 AND is_active = 1
     ) AS game_types
     WHERE game_type IS NOT NULL AND TRIM(game_type) <> ''
     ORDER BY game_type ASC"
)->fetchAll();

$providerSql = "
    SELECT DISTINCT provider_code
    FROM (
        SELECT game_provider AS provider_code
        FROM games_sgx
        WHERE game_status = 1 AND is_active = 1

        UNION ALL

        SELECT provider_code
        FROM games_nexus
        WHERE game_status = 1 AND is_active = 1
    ) AS providers
    WHERE provider_code IS NOT NULL
      AND TRIM(provider_code) <> ''
";

$providerParams = [];

if ($source === 'sgx') {
    $providerSql = "
        SELECT DISTINCT game_provider AS provider_code
        FROM games_sgx
        WHERE game_status = 1 AND is_active = 1
    ";
} elseif ($source === 'nexus') {
    $providerSql = "
        SELECT DISTINCT provider_code
        FROM games_nexus
        WHERE game_status = 1 AND is_active = 1
    ";
}

$providerSql .= ' ORDER BY provider_code ASC';
$providerRows = $pdo->query($providerSql)->fetchAll();

/*
|--------------------------------------------------------------------------
| Query gabungan game
|--------------------------------------------------------------------------
*/

$baseUnionSql = "
    SELECT
        'sgx' AS source,
        id,
        game_provider AS provider_code,
        game_code,
        game_name,
        UPPER(game_type) AS game_type,
        game_image,
        game_status,
        is_active,
        is_popular,
        popular_order
    FROM games_sgx

    UNION ALL

    SELECT
        'nexus' AS source,
        id,
        provider_code,
        game_code,
        game_name,
        UPPER(game_type) AS game_type,
        game_image,
        game_status,
        is_active,
        is_popular,
        popular_order
    FROM games_nexus
";

$where = [
    'games.game_status = 1',
    'games.is_active = 1',
];

$params = [];

if ($source !== 'all') {
    $where[] = 'games.source = :source';
    $params[':source'] = $source;
}

if ($type !== '') {
    $where[] = 'games.game_type = :game_type';
    $params[':game_type'] = $type;
}

if ($provider !== '') {
    $where[] = 'games.provider_code = :provider_code';
    $params[':provider_code'] = $provider;
}

if ($popularFilter !== 'all') {
    $where[] = 'games.is_popular = :is_popular';
    $params[':is_popular'] = (int) $popularFilter;
}

if ($search !== '') {
    $where[] = '(
        games.game_name LIKE :search_name
        OR games.game_code LIKE :search_code
        OR games.provider_code LIKE :search_provider
    )';

    $like = '%' . $search . '%';
    $params[':search_name'] = $like;
    $params[':search_code'] = $like;
    $params[':search_provider'] = $like;
}

$whereSql = implode(' AND ', $where);

$countSql = "
    SELECT COUNT(*)
    FROM ({$baseUnionSql}) AS games
    WHERE {$whereSql}
";

$countStmt = $pdo->prepare($countSql);
$countStmt->execute($params);
$totalGames = (int) $countStmt->fetchColumn();

$totalPages = max(1, (int) ceil($totalGames / $perPage));

if ($page > $totalPages) {
    $page = $totalPages;
}

$offset = ($page - 1) * $perPage;

$listSql = "
    SELECT games.*
    FROM ({$baseUnionSql}) AS games
    WHERE {$whereSql}
    ORDER BY
        games.is_popular DESC,
        CASE
            WHEN games.is_popular = 1 AND games.popular_order > 0
            THEN 0
            ELSE 1
        END ASC,
        games.popular_order ASC,
        games.game_name ASC
    LIMIT {$perPage} OFFSET {$offset}
";

$listStmt = $pdo->prepare($listSql);
$listStmt->execute($params);
$games = $listStmt->fetchAll();

/*
|--------------------------------------------------------------------------
| Ringkasan
|--------------------------------------------------------------------------
*/

$summary = $pdo->query(
    "SELECT
        COUNT(*) AS total_active,
        SUM(is_popular = 1) AS total_popular,
        SUM(source = 'sgx') AS total_sgx,
        SUM(source = 'nexus') AS total_nexus
     FROM (
        SELECT 'sgx' AS source, is_popular
        FROM games_sgx
        WHERE game_status = 1 AND is_active = 1

        UNION ALL

        SELECT 'nexus' AS source, is_popular
        FROM games_nexus
        WHERE game_status = 1 AND is_active = 1
     ) AS summary_games"
)->fetch();

$flash = isset($_SESSION['popular_manager_flash'])
    ? $_SESSION['popular_manager_flash']
    : null;

unset($_SESSION['popular_manager_flash']);

function pageUrl($self, array $params, $page)
{
    $params['page'] = max(1, (int) $page);
    return $self . '?' . http_build_query($params);
}

?>
<!doctype html>
<html lang="id">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Popular Game Manager</title>
    <style>
        :root {
            --bg: #020817;
            --panel: #071a34;
            --panel2: #031126;
            --line: #174c7e;
            --blue: #25a8ff;
            --gold: #ffc83d;
            --green: #32df91;
            --red: #ff5b66;
            --text: #eef7ff;
            --muted: #95abc4;
        }
        * { box-sizing: border-box; }
        html { color-scheme: dark; }
        body {
            margin: 0;
            color: var(--text);
            background:
                radial-gradient(circle at 50% -10%, rgba(0,136,255,.20), transparent 400px),
                var(--bg);
            font-family: Arial, Helvetica, sans-serif;
        }
        a { color: inherit; }
        button, input, select { font: inherit; }
        .wrap { width: min(1450px, 100%); margin: 0 auto; padding: 18px; }
        .topbar {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 14px;
            margin-bottom: 15px;
        }
        .title h1 { margin: 0; font-size: clamp(22px, 3vw, 34px); }
        .title p { margin: 5px 0 0; color: var(--muted); font-size: 12px; }
        .logout {
            padding: 10px 14px;
            border: 1px solid #8f3038;
            border-radius: 9px;
            color: #ffd8da;
            background: #321016;
            text-decoration: none;
            font-size: 12px;
            font-weight: 800;
        }
        .flash {
            margin-bottom: 14px;
            padding: 11px 13px;
            border-radius: 10px;
            font-size: 12px;
            font-weight: 700;
        }
        .flash.success { border: 1px solid #238b60; background: rgba(33,184,116,.13); color: #bbffe1; }
        .flash.error { border: 1px solid #b43b45; background: rgba(255,55,68,.12); color: #ffd4d7; }
        .stats {
            display: grid;
            grid-template-columns: repeat(4, minmax(0, 1fr));
            gap: 9px;
            margin-bottom: 14px;
        }
        .stat {
            padding: 13px;
            border: 1px solid var(--line);
            border-radius: 12px;
            background: linear-gradient(145deg, var(--panel), var(--panel2));
        }
        .stat small { display: block; color: var(--muted); font-size: 10px; }
        .stat strong { display: block; margin-top: 3px; font-size: 21px; color: var(--gold); }
        .filters {
            display: grid;
            grid-template-columns: 1.35fr repeat(4, minmax(120px, .7fr)) auto;
            gap: 8px;
            margin-bottom: 10px;
            padding: 12px;
            border: 1px solid var(--line);
            border-radius: 13px;
            background: rgba(5,22,45,.94);
        }
        .filters input,
        .filters select,
        .order-input {
            width: 100%;
            height: 40px;
            padding: 0 10px;
            border: 1px solid #285981;
            border-radius: 8px;
            color: #fff;
            background: #020b1c;
            outline: none;
        }
        .filters input:focus,
        .filters select:focus,
        .order-input:focus { border-color: var(--blue); box-shadow: 0 0 0 3px rgba(37,168,255,.11); }
        .btn {
            min-height: 40px;
            padding: 0 13px;
            border: 0;
            border-radius: 8px;
            cursor: pointer;
            font-size: 11px;
            font-weight: 900;
        }
        .btn-blue { color: #fff; background: linear-gradient(180deg, #36b9ff, #0877cb); }
        .btn-green { color: #041b11; background: linear-gradient(180deg, #aaffd7, #27dc8e 65%, #0a8751); }
        .btn-red { color: #fff; background: linear-gradient(180deg, #ff7780, #cf2430); }
        .btn-gold { color: #2b1900; background: linear-gradient(180deg, #fff3a1, #ffc529 65%, #b96a00); }
        .bulkbar {
            display: flex;
            flex-wrap: wrap;
            align-items: center;
            gap: 8px;
            margin-bottom: 12px;
            padding: 9px 11px;
            border: 1px solid #294d71;
            border-radius: 11px;
            background: #041126;
        }
        .bulkbar label { font-size: 11px; color: var(--muted); }
        .bulkbar select {
            height: 36px;
            padding: 0 9px;
            border: 1px solid #285981;
            border-radius: 7px;
            background: #020b1c;
        }
        .result-info { margin-left: auto; color: var(--muted); font-size: 11px; }
        .grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(210px, 1fr));
            gap: 11px;
        }
        .card {
            position: relative;
            overflow: hidden;
            border: 1px solid #174e7d;
            border-radius: 13px;
            background: linear-gradient(145deg, #082344, #020d20);
            box-shadow: 0 8px 20px rgba(0,0,0,.25);
        }
        .card.popular { border-color: #e9a914; box-shadow: 0 0 14px rgba(255,183,24,.18), 0 8px 20px rgba(0,0,0,.28); }
        .image {
            position: relative;
            width: 100%;
            aspect-ratio: 16 / 10;
            overflow: hidden;
            background: #010714;
        }
        .image img { width: 100%; height: 100%; object-fit: cover; display: block; }
        .image::after {
            content: '';
            position: absolute;
            inset: auto 0 0;
            height: 45%;
            background: linear-gradient(transparent, rgba(0,0,0,.78));
            pointer-events: none;
        }
        .check {
            position: absolute;
            z-index: 5;
            top: 8px;
            left: 8px;
            width: 21px;
            height: 21px;
            accent-color: #19b9ff;
        }
        .badges {
            position: absolute;
            z-index: 4;
            right: 7px;
            bottom: 7px;
            display: flex;
            gap: 4px;
        }
        .badge {
            padding: 3px 6px;
            border-radius: 5px;
            color: #fff;
            background: rgba(0,0,0,.72);
            font-size: 8px;
            font-weight: 900;
        }
        .badge.pop { color: #2b1900; background: #ffd13d; }
        .card-body { padding: 10px; }
        .game-name {
            min-height: 34px;
            margin: 0;
            font-size: 13px;
            line-height: 1.28;
        }
        .meta {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 4px;
            margin-top: 7px;
            color: var(--muted);
            font-size: 9px;
        }
        .meta span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
        .actions {
            display: grid;
            grid-template-columns: 1fr;
            gap: 6px;
            margin-top: 9px;
        }
        .toggle-form { display: grid; grid-template-columns: 1fr; }
        .order-form {
            display: grid;
            grid-template-columns: 68px 1fr;
            gap: 6px;
        }
        .order-input { height: 36px; text-align: center; }
        .order-form .btn, .toggle-form .btn { min-height: 36px; }
        .empty {
            grid-column: 1 / -1;
            padding: 40px 20px;
            border: 1px dashed #285981;
            border-radius: 13px;
            color: var(--muted);
            text-align: center;
        }
        .pagination {
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
            gap: 6px;
            margin-top: 18px;
        }
        .pagination a, .pagination span {
            min-width: 36px;
            height: 36px;
            display: grid;
            place-items: center;
            padding: 0 9px;
            border: 1px solid #285981;
            border-radius: 8px;
            color: #dcecff;
            background: #05152d;
            text-decoration: none;
            font-size: 11px;
            font-weight: 800;
        }
        .pagination .active { color: #231400; border-color: #ffc83d; background: #ffc83d; }
        .warning {
            margin-top: 18px;
            padding: 12px;
            border: 1px solid #7d5c13;
            border-radius: 10px;
            color: #ffe6a3;
            background: rgba(255,182,27,.08);
            font-size: 11px;
            line-height: 1.5;
        }
        @media (max-width: 900px) {
            .filters { grid-template-columns: repeat(2, minmax(0, 1fr)); }
            .filters .search-field { grid-column: 1 / -1; }
            .stats { grid-template-columns: repeat(2, minmax(0, 1fr)); }
        }
        @media (max-width: 560px) {
            .wrap { padding: 10px; }
            .topbar { align-items: flex-start; }
            .filters { grid-template-columns: 1fr; }
            .filters .search-field { grid-column: auto; }
            .grid { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 7px; }
            .card-body { padding: 8px; }
            .game-name { font-size: 11px; min-height: 30px; }
            .meta { grid-template-columns: 1fr; font-size: 8px; }
            .order-form { grid-template-columns: 54px 1fr; }
            .btn { padding: 0 8px; font-size: 9px; }
            .result-info { width: 100%; margin-left: 0; }
        }
    </style>
</head>
<body>
<div class="wrap">
    <div class="topbar">
        <div class="title">
            <h1>Popular Game Manager</h1>
            <p>Pilih game populer dari SGX dan Nexus. Perubahan langsung tersimpan ke SQL.</p>
        </div>
        <a class="logout" href="<?= e($self); ?>?logout=1">Keluar</a>
    </div>

    <?php if (is_array($flash)): ?>
        <div class="flash <?= e($flash['type']); ?>">
            <?= e($flash['message']); ?>
        </div>
    <?php endif; ?>

    <div class="stats">
        <div class="stat"><small>Total game aktif</small><strong><?= number_format((int) ($summary['total_active'] ?? 0)); ?></strong></div>
        <div class="stat"><small>Total populer</small><strong><?= number_format((int) ($summary['total_popular'] ?? 0)); ?></strong></div>
        <div class="stat"><small>Game SGX</small><strong><?= number_format((int) ($summary['total_sgx'] ?? 0)); ?></strong></div>
        <div class="stat"><small>Game Nexus</small><strong><?= number_format((int) ($summary['total_nexus'] ?? 0)); ?></strong></div>
    </div>

    <form class="filters" method="get">
        <input class="search-field" type="search" name="q" value="<?= e($search); ?>" placeholder="Cari nama, kode game, atau provider...">

        <select name="source">
            <option value="all" <?= $source === 'all' ? 'selected' : ''; ?>>Semua sumber</option>
            <option value="sgx" <?= $source === 'sgx' ? 'selected' : ''; ?>>SGX</option>
            <option value="nexus" <?= $source === 'nexus' ? 'selected' : ''; ?>>Nexus</option>
        </select>

        <select name="type">
            <option value="">Semua kategori</option>
            <?php foreach ($typeRows as $row): ?>
                <?php $rowType = strtoupper((string) $row['game_type']); ?>
                <option value="<?= e($rowType); ?>" <?= $type === $rowType ? 'selected' : ''; ?>>
                    <?= e(isset($typeLabels[$rowType]) ? $typeLabels[$rowType] . ' (' . $rowType . ')' : $rowType); ?>
                </option>
            <?php endforeach; ?>
        </select>

        <select name="provider">
            <option value="">Semua provider</option>
            <?php foreach ($providerRows as $row): ?>
                <?php $rowProvider = (string) $row['provider_code']; ?>
                <option value="<?= e($rowProvider); ?>" <?= $provider === $rowProvider ? 'selected' : ''; ?>><?= e($rowProvider); ?></option>
            <?php endforeach; ?>
        </select>

        <select name="popular">
            <option value="all" <?= $popularFilter === 'all' ? 'selected' : ''; ?>>Semua status</option>
            <option value="1" <?= $popularFilter === '1' ? 'selected' : ''; ?>>Populer saja</option>
            <option value="0" <?= $popularFilter === '0' ? 'selected' : ''; ?>>Belum populer</option>
        </select>

        <select name="per_page">
            <option value="24" <?= $perPage === 24 ? 'selected' : ''; ?>>24 / halaman</option>
            <option value="48" <?= $perPage === 48 ? 'selected' : ''; ?>>48 / halaman</option>
            <option value="96" <?= $perPage === 96 ? 'selected' : ''; ?>>96 / halaman</option>
        </select>

        <button class="btn btn-blue" type="submit">Terapkan</button>
    </form>

    <form id="bulkForm" class="bulkbar" method="post">
        <input type="hidden" name="csrf_token" value="<?= e($csrfToken); ?>">
        <input type="hidden" name="action" value="bulk">
        <input type="hidden" name="return_url" value="<?= e($returnUrl); ?>">

        <label><input type="checkbox" id="selectAll"> Pilih semua halaman ini</label>

        <select name="bulk_operation" required>
            <option value="">Aksi game terpilih</option>
            <option value="popular">Jadikan populer</option>
            <option value="unpopular">Batalkan populer</option>
        </select>

        <button class="btn btn-gold" type="submit">Jalankan</button>

        <span class="result-info">
            Menampilkan <?= number_format(count($games)); ?> dari <?= number_format($totalGames); ?> hasil
        </span>
    </form>

    <div class="grid">
        <?php if (empty($games)): ?>
            <div class="empty">Game tidak ditemukan untuk filter tersebut.</div>
        <?php endif; ?>

        <?php foreach ($games as $game): ?>
            <?php
            $gameSource = (string) $game['source'];
            $gameId = (int) $game['id'];
            $isPopular = (int) $game['is_popular'] === 1;
            $image = trim((string) $game['game_image']);
            $gameType = strtoupper((string) $game['game_type']);

            if ($image === '') {
                $image = 'assets/images/game-default.png';
            }
            ?>
            <article class="card <?= $isPopular ? 'popular' : ''; ?>">
                <div class="image">
                    <input
                        class="check game-select"
                        type="checkbox"
                        name="selected[]"
                        value="<?= e($gameSource . ':' . $gameId); ?>"
                        form="bulkForm"
                        aria-label="Pilih <?= e($game['game_name']); ?>"
                    >

                    <img
                        src="<?= e($image); ?>"
                        alt="<?= e($game['game_name']); ?>"
                        loading="lazy"
                        decoding="async"
                        onerror="this.onerror=null;this.src='assets/images/game-default.png';"
                    >

                    <div class="badges">
                        <?php if ($isPopular): ?><span class="badge pop">POPULAR #<?= (int) $game['popular_order']; ?></span><?php endif; ?>
                        <span class="badge"><?= e(strtoupper($gameSource)); ?></span>
                        <span class="badge"><?= e($gameType); ?></span>
                    </div>
                </div>

                <div class="card-body">
                    <h2 class="game-name"><?= e($game['game_name']); ?></h2>

                    <div class="meta">
                        <span>Provider: <?= e($game['provider_code']); ?></span>
                        <span>Kode: <?= e($game['game_code']); ?></span>
                        <span>Kategori: <?= e($typeLabels[$gameType] ?? $gameType); ?></span>
                        <span>ID: <?= $gameId; ?></span>
                    </div>

                    <div class="actions">
                        <form class="toggle-form" method="post">
                            <input type="hidden" name="csrf_token" value="<?= e($csrfToken); ?>">
                            <input type="hidden" name="action" value="toggle">
                            <input type="hidden" name="return_url" value="<?= e($returnUrl); ?>">
                            <input type="hidden" name="source" value="<?= e($gameSource); ?>">
                            <input type="hidden" name="game_id" value="<?= $gameId; ?>">
                            <input type="hidden" name="new_popular" value="<?= $isPopular ? '0' : '1'; ?>">
                            <input type="hidden" name="popular_order" value="<?= $isPopular ? (int) $game['popular_order'] : 999; ?>">

                            <button class="btn <?= $isPopular ? 'btn-red' : 'btn-green'; ?>" type="submit">
                                <?= $isPopular ? 'Batalkan Populer' : 'Jadikan Populer'; ?>
                            </button>
                        </form>

                        <?php if ($isPopular): ?>
                            <form class="order-form" method="post">
                                <input type="hidden" name="csrf_token" value="<?= e($csrfToken); ?>">
                                <input type="hidden" name="action" value="save_order">
                                <input type="hidden" name="return_url" value="<?= e($returnUrl); ?>">
                                <input type="hidden" name="source" value="<?= e($gameSource); ?>">
                                <input type="hidden" name="game_id" value="<?= $gameId; ?>">

                                <input
                                    class="order-input"
                                    type="number"
                                    name="popular_order"
                                    min="1"
                                    max="99999"
                                    value="<?= max(1, (int) $game['popular_order']); ?>"
                                    aria-label="Urutan populer"
                                    required
                                >

                                <button class="btn btn-blue" type="submit">Simpan Urutan</button>
                            </form>
                        <?php endif; ?>
                    </div>
                </div>
            </article>
        <?php endforeach; ?>
    </div>

    <?php if ($totalPages > 1): ?>
        <nav class="pagination" aria-label="Navigasi halaman">
            <?php if ($page > 1): ?>
                <a href="<?= e(pageUrl($self, $returnParams, $page - 1)); ?>">‹</a>
            <?php endif; ?>

            <?php
            $startPage = max(1, $page - 2);
            $endPage = min($totalPages, $page + 2);
            ?>

            <?php if ($startPage > 1): ?>
                <a href="<?= e(pageUrl($self, $returnParams, 1)); ?>">1</a>
                <?php if ($startPage > 2): ?><span>…</span><?php endif; ?>
            <?php endif; ?>

            <?php for ($i = $startPage; $i <= $endPage; $i++): ?>
                <a class="<?= $i === $page ? 'active' : ''; ?>" href="<?= e(pageUrl($self, $returnParams, $i)); ?>"><?= $i; ?></a>
            <?php endfor; ?>

            <?php if ($endPage < $totalPages): ?>
                <?php if ($endPage < $totalPages - 1): ?><span>…</span><?php endif; ?>
                <a href="<?= e(pageUrl($self, $returnParams, $totalPages)); ?>"><?= $totalPages; ?></a>
            <?php endif; ?>

            <?php if ($page < $totalPages): ?>
                <a href="<?= e(pageUrl($self, $returnParams, $page + 1)); ?>">›</a>
            <?php endif; ?>
        </nav>
    <?php endif; ?>

    <div class="warning">
        Halaman ini bersifat sementara. Setelah selesai memilih game populer, ganti nama file atau hapus dari public_html. Ganti juga password pada variabel <strong>$temporaryPassword</strong> di bagian paling atas.
    </div>
</div>

<script>
(function () {
    'use strict';

    var selectAll = document.getElementById('selectAll');
    var boxes = document.querySelectorAll('.game-select');
    var bulkForm = document.getElementById('bulkForm');

    if (selectAll) {
        selectAll.addEventListener('change', function () {
            boxes.forEach(function (box) {
                box.checked = selectAll.checked;
            });
        });
    }

    if (bulkForm) {
        bulkForm.addEventListener('submit', function (event) {
            var selected = document.querySelectorAll('.game-select:checked');

            if (selected.length === 0) {
                event.preventDefault();
                alert('Pilih minimal satu game.');
                return;
            }

            if (!window.confirm('Perbarui ' + selected.length + ' game terpilih?')) {
                event.preventDefault();
            }
        });
    }
}());
</script>
</body>
</html>