<?php
require_once __DIR__ . '/../config/pagination.php';

if (!function_exists('legacy_game_history_response_success')) {
    function legacy_game_history_response_success(array $response, string $type): bool
    {
        $statusRaw = $response['status'] ?? null;
        $statusText = strtolower(trim((string)$statusRaw));
        $status = is_numeric($statusRaw) ? (int)$statusRaw : null;

        if ($status === 1 || $status === 200 || $statusText === 'success') {
            return true;
        }

        return $status === 0 && (
            legacy_game_history_response_rows($response, $type) !== []
            || isset($response[$type])
            || isset($response['data'])
            || isset($response['game_log'])
            || isset($response['total_count'])
        );
    }
}

if (!function_exists('legacy_game_history_response_rows')) {
    function legacy_game_history_response_rows(array $response, string $type): array
    {
        $candidates = [
            $response[$type] ?? null,
            $response['data'] ?? null,
            $response['game_log'] ?? null,
            $response['history'] ?? null,
            $response['histories'] ?? null,
            $response['logs'] ?? null,
            $response['rows'] ?? null,
            $response['records'] ?? null,
            $response['result'] ?? null,
            $response['results'] ?? null,
            $response['list'] ?? null,
            $response['items'] ?? null,
            $response['data'][$type] ?? null,
            $response['data']['data'] ?? null,
            $response['data']['game_log'] ?? null,
            $response['data']['history'] ?? null,
            $response['data']['histories'] ?? null,
            $response['data']['logs'] ?? null,
            $response['data']['rows'] ?? null,
            $response['data']['records'] ?? null,
            $response['data']['result'] ?? null,
            $response['data']['results'] ?? null,
            $response['data']['list'] ?? null,
            $response['data']['items'] ?? null,
        ];

        foreach ($candidates as $candidate) {
            $rows = legacy_game_history_collect_rows($candidate);
            if ($rows !== []) {
                return $rows;
            }
        }

        return [];
    }
}

if (!function_exists('legacy_game_history_collect_rows')) {
    function legacy_game_history_collect_rows($candidate, int $depth = 0): array
    {
        if (!is_array($candidate) || $depth > 5) {
            return [];
        }

        if (legacy_game_history_looks_like_row($candidate)) {
            return [$candidate];
        }

        $rows = [];
        foreach ($candidate as $item) {
            if (!is_array($item)) {
                continue;
            }

            $nestedRows = legacy_game_history_collect_rows($item, $depth + 1);
            if ($nestedRows !== []) {
                $rows = array_merge($rows, $nestedRows);
            }
        }

        return $rows;
    }
}

if (!function_exists('legacy_game_history_looks_like_row')) {
    function legacy_game_history_looks_like_row(array $row): bool
    {
        $rowKeys = [
            'history_id', 'historyId', 'id', 'round_id', 'roundId', 'session',
            'txn', 'transaction', 'txn_id', 'transaction_id', 'transactionId', 'trx_id', 'trxId',
            'provider_code', 'providerCode', 'provider', 'provider_name',
            'game_code', 'gameCode', 'game', 'game_name', 'gameName',
            'bet_money', 'betMoney', 'bet', 'turnover', 'bet_amount', 'betAmount',
            'win_money', 'winMoney', 'win', 'payout', 'win_amount', 'winAmount',
            'created_at', 'createdAt', 'created', 'date', 'datetime', 'time',
            'bet_time', 'betTime', 'end_time', 'endTime', 'match_time', 'matchTime',
            'start_time', 'startTime',
        ];

        foreach ($rowKeys as $key) {
            if (array_key_exists($key, $row)) {
                return true;
            }
        }

        return false;
    }
}

if (!function_exists('legacy_game_history_scalar_value')) {
    function legacy_game_history_scalar_value($value, $default = '')
    {
        if ($value === null || is_array($value) || is_object($value)) {
            return $default;
        }

        if (is_bool($value)) {
            return $value ? '1' : '0';
        }

        return $value;
    }
}

if (!function_exists('legacy_game_history_pick')) {
    function legacy_game_history_pick(array $row, array $keys, $default = '')
    {
        foreach ($keys as $key) {
            if (!array_key_exists($key, $row)) {
                continue;
            }

            $value = legacy_game_history_scalar_value($row[$key], null);
            if ($value !== null && (string)$value !== '') {
                return $value;
            }
        }

        return $default;
    }
}

if (!function_exists('legacy_game_history_number')) {
    function legacy_game_history_number($value): float
    {
        $value = legacy_game_history_scalar_value($value, 0);
        if (is_numeric($value)) {
            return (float)$value;
        }

        $clean = str_replace(',', '', trim((string)$value));
        return is_numeric($clean) ? (float)$clean : 0.0;
    }
}

if (!function_exists('legacy_game_history_response_message')) {
    function legacy_game_history_response_message(array $response, string $fallback): string
    {
        return trim((string)($response['error'] ?? $response['msg'] ?? $response['message'] ?? $fallback)) ?: $fallback;
    }
}

if (!function_exists('legacy_game_history_is_rate_limit_response')) {
    function legacy_game_history_is_rate_limit_response($response): bool
    {
        if (!is_array($response)) {
            return false;
        }

        $message = strtolower(legacy_game_history_response_message($response, ''));
        return strpos($message, 'rate') !== false && strpos($message, 'limit') !== false;
    }
}

if (!function_exists('legacy_game_history_fetch_primary_history')) {
    function legacy_game_history_fetch_primary_history($provider, string $userCode, string $type, string $start, string $end, int $page, int $perPage)
    {
        $attempts = 4;
        $response = null;

        for ($attempt = 0; $attempt < $attempts; $attempt++) {
            if ($attempt > 0) {
                usleep(1000000 * $attempt);
            }

            $response = $provider->getGameLog($userCode, $type, $start, $end, $page, $perPage);
            if (!legacy_game_history_is_rate_limit_response($response)) {
                return $response;
            }
        }

        return $response;
    }
}

if (!function_exists('legacy_game_history_normalize_row')) {
    function legacy_game_history_normalize_row(array $row, string $fallbackUserCode, string $fallbackExtUser, float $agentBalance, string $fallbackType = ''): array
    {
        foreach (['txn', 'transaction'] as $nestedKey) {
            if (isset($row[$nestedKey]) && is_array($row[$nestedKey])) {
                $row = array_merge($row[$nestedKey], $row);
            }
        }

        $historyId = legacy_game_history_pick($row, ['history_id', 'historyId', 'id', 'round_id', 'roundId', 'session', 'txn_id', 'transaction_id', 'transactionId', 'trx_id', 'trxId'], '');
        $txnId = legacy_game_history_pick($row, ['txn_id', 'transaction_id', 'transactionId', 'trx_id', 'trxId', 'session', 'history_id', 'historyId', 'id'], $historyId);
        $createdAt = legacy_game_history_pick($row, ['created_at', 'createdAt', 'created', 'date', 'datetime', 'time', 'bet_time', 'betTime', 'settle_time', 'settleTime', 'end_time', 'endTime', 'match_time', 'matchTime', 'start_time', 'startTime'], '');

        return [
            'history_id' => (string)$historyId,
            'user_code' => (string)legacy_game_history_pick($row, ['user_code', 'userCode', 'intUser', 'username', 'user', 'member', 'member_code', 'memberCode'], $fallbackUserCode),
            'user' => $fallbackExtUser,
            'user_member' => $fallbackExtUser,
            'provider_code' => (string)legacy_game_history_pick($row, ['provider_code', 'providerCode', 'provider', 'provider_name', 'providerName'], ''),
            'game_code' => (string)legacy_game_history_pick($row, ['game_code', 'gameCode', 'game', 'game_name', 'gameName'], ''),
            'type' => (string)legacy_game_history_pick($row, ['type', 'game_type', 'gameType', 'provider_type', 'providerType', 'category'], $fallbackType),
            'bet_money' => legacy_game_history_number(legacy_game_history_pick($row, ['bet_money', 'betMoney', 'bet', 'turnover', 'bet_amount', 'betAmount', 'valid_bet', 'validBet', 'amount'], 0)),
            'win_money' => legacy_game_history_number(legacy_game_history_pick($row, ['win_money', 'winMoney', 'win', 'payout', 'win_amount', 'winAmount', 'settle_amount', 'settleAmount'], 0)),
            'txn_id' => (string)$txnId,
            'txn_type' => (string)legacy_game_history_pick($row, ['txn_type', 'txnType', 'transaction_type', 'transactionType', 'status', 'action'], ''),
            'user_start_balance' => legacy_game_history_number(legacy_game_history_pick($row, ['user_start_balance', 'userStartBalance', 'before_balance', 'beforeBalance', 'balance_before', 'balanceBefore', 'user_before_balance', 'userBeforeBalance'], 0)),
            'user_end_balance' => legacy_game_history_number(legacy_game_history_pick($row, ['user_end_balance', 'userEndBalance', 'after_balance', 'afterBalance', 'balance_after', 'balanceAfter', 'user_after_balance', 'userAfterBalance', 'balance'], 0)),
            'agent_start_balance' => legacy_game_history_number(legacy_game_history_pick($row, ['agent_start_balance', 'agentStartBalance', 'agent_before_balance', 'agentBeforeBalance'], $agentBalance)),
            'agent_end_balance' => legacy_game_history_number(legacy_game_history_pick($row, ['agent_end_balance', 'agentEndBalance', 'agent_after_balance', 'agentAfterBalance'], $agentBalance)),
            'created_at' => (string)$createdAt,
        ];
    }
}

if (!function_exists('legacy_game_history_in_date_range')) {
    function legacy_game_history_in_date_range(string $createdAt, string $start, string $end): bool
    {
        $time = strtotime($createdAt);
        if ($time === false) {
            return true;
        }

        return $time >= strtotime($start) && $time <= strtotime($end);
    }
}

if (!function_exists('legacy_game_history_user_scope_condition')) {
    function legacy_game_history_user_scope_condition(mysqli $db, string $column, array $agent): string
    {
        $agentLevel = strtolower(trim((string)($agent['agent_level'] ?? '')));
        $agentRefsSql = agent_sql_values($db, agent_identity_values($agent));

        if (in_array($agentLevel, ['admin', 'superadmin', 'super_admin'], true)) {
            return '1=1';
        }

        if ($agentLevel === 'head_agent') {
            return "(
                $column IN ($agentRefsSql)
                OR $column IN (
                    SELECT a.agent_code
                    FROM tb_agent a
                    WHERE a.agent_upline IN ($agentRefsSql)
                )
                OR $column IN (
                    SELECT a.agent_name
                    FROM tb_agent a
                    WHERE a.agent_upline IN ($agentRefsSql)
                )
            )";
        }

        return "$column IN ($agentRefsSql)";
    }
}

if (!isset($data_admin['agent_level'], $data_admin['agent_name'])) {
    header('Location: ./');
    exit();
}

$agentLevel = strtolower(trim((string)$data_admin['agent_level']));
$isAdmin = in_array($agentLevel, ['admin', 'superadmin', 'super_admin'], true);
$isHeadAgent = $agentLevel === 'head_agent';
$allowedUsers = [];
$allUsersOptionValue = '__all__';
$selectedUser = trim((string)($_GET['user_code'] ?? ''));
$userSearch = trim((string)($_GET['user_search'] ?? ''));
$historyUserLimit = legacy_page_limit('history_user_limit', 200, [50, 100, 200, 500, 1000]);
$currentGameHistoryUserScopeSql = legacy_game_history_user_scope_condition($call, 'agent_code', (array)$data_admin);
$userWhereParts = [];
$userScopeWhereParts = [$currentGameHistoryUserScopeSql];

$userWhereParts[] = $currentGameHistoryUserScopeSql;

if ($userSearch !== '') {
    $userSearchSql = legacy_escape_like($call, $userSearch);
    $userWhereParts[] = "(
        extUser LIKE '%$userSearchSql%' ESCAPE '\\\\'
        OR intUser LIKE '%$userSearchSql%' ESCAPE '\\\\'
    )";
}

$historyUserTotalRow = legacy_fetch_stats(
    $call,
    "SELECT COUNT(*) AS total_member
     FROM tb_user
     WHERE " . implode(' AND ', $userScopeWhereParts)
);
$historyUserTotal = (int)($historyUserTotalRow['total_member'] ?? 0);
$userWhereSql = implode(' AND ', $userWhereParts);
$historyUserMatchRow = legacy_fetch_stats(
    $call,
    "SELECT COUNT(*) AS total_member
     FROM tb_user
     WHERE $userWhereSql"
);
$historyUserMatchTotal = (int)($historyUserMatchRow['total_member'] ?? 0);
$userQueryLimit = ($isAdmin || $isHeadAgent) ? $historyUserLimit : 200;
$userQuery = "SELECT intUser, extUser FROM tb_user WHERE $userWhereSql ORDER BY created DESC LIMIT $userQueryLimit";
$userResult = mysqli_query($call, $userQuery);
if ($userResult) {
    while ($row = mysqli_fetch_assoc($userResult)) {
        $allowedUsers[$row['intUser']] = $row['extUser'];
    }
}

$selectedUserInScope = false;
if ($selectedUser !== '' && $selectedUser !== $allUsersOptionValue) {
    if (isset($allowedUsers[$selectedUser])) {
        $selectedUserInScope = true;
    } else {
        $selectedUserSql = mysqli_real_escape_string($call, $selectedUser);
        $selectedWhere = "intUser = '$selectedUserSql' AND $currentGameHistoryUserScopeSql";
        $selectedQuery = mysqli_query($call, "SELECT intUser, extUser FROM tb_user WHERE $selectedWhere LIMIT 1");
        if ($selectedQuery && mysqli_num_rows($selectedQuery) > 0) {
            $selectedRow = mysqli_fetch_assoc($selectedQuery) ?: [];
            $allowedUsers[(string)$selectedRow['intUser']] = (string)$selectedRow['extUser'];
            $selectedUserInScope = true;
        }
    }
}

$defaultStart = date('Y-m-d 00:00:00', strtotime('-1 day'));
$defaultEnd = date('Y-m-d 23:59:59');

if (!$isAdmin && $selectedUser === '' && count($allowedUsers) === 1) {
    $selectedUser = array_key_first($allowedUsers);
    $selectedUserInScope = true;
}
$agentBalanceLocal = (float)($data_admin['agent_balance'] ?? 0);

$gameTypes = ['slot', 'fishing', 'arcade', 'table', 'lottery', 'sports'];
$selectedGameType = strtolower(trim((string)($_GET['game_type'] ?? 'all')));
if ($selectedGameType === '' || $selectedGameType === 'all') {
    $requestedGameTypes = $gameTypes;
    $selectedGameType = 'all';
} elseif (in_array($selectedGameType, $gameTypes, true)) {
    $requestedGameTypes = [$selectedGameType];
} else {
    $requestedGameTypes = $gameTypes;
    $selectedGameType = 'all';
}
$start = trim((string)($_GET['start'] ?? $defaultStart));
$end = trim((string)($_GET['end'] ?? $defaultEnd));
$logPage = (int)($_GET['log_page'] ?? 0);
$perPage = (int)($_GET['per_page'] ?? 1000);
if ($logPage < 0) {
    $logPage = 0;
}
if ($perPage <= 0 || $perPage > 1000) {
    $perPage = 1000;
}

$apiResponse = null;
$logRows = [];
$apiError = '';
$apiWarnings = [];
$secondaryRowsCount = 0;
$isAllUsersHistory = $isAdmin && $selectedUser === $allUsersOptionValue;

if ($selectedUser !== '' || $isAllUsersHistory) {
    $hasAccess = $selectedUserInScope;
    $historyUsers = [];

    if ($isAllUsersHistory) {
        $hasAccess = true;
        $historyUsers = $allowedUsers;
    } elseif ($selectedUser !== '' && $selectedUser !== $allUsersOptionValue) {
        $historyUsers = [$selectedUser => ($allowedUsers[$selectedUser] ?? $selectedUser)];
    }

    if (!$hasAccess) {
        $apiError = 'User tidak tersedia untuk akun ini.';
    } elseif ($historyUsers === []) {
        $apiError = 'Tidak ada user yang tersedia untuk akun ini.';
    } else {
        $totalCount = 0;
        $successCount = 0;

        foreach ($historyUsers as $historyUserCode => $historyExtUser) {
            $requestIndex = 0;
            foreach ($requestedGameTypes as $type) {
                if ($requestIndex > 0) {
                    usleep(800000);
                }
                $requestIndex++;

                $response = legacy_game_history_fetch_primary_history($GS, (string)$historyUserCode, $type, $start, $end, $logPage, $perPage);
                if (!is_array($response) || !isset($response['status'])) {
                    $apiWarnings[] = 'Tidak ada response dari API untuk ' . strtoupper($type) . '.';
                    continue;
                }
                if (!legacy_game_history_response_success($response, $type)) {
                    $apiWarnings[] = legacy_game_history_response_message($response, 'Gagal mengambil data.') . ' (' . strtoupper($type) . ').';
                    continue;
                }
                $rows = legacy_game_history_response_rows($response, $type);
                if (!empty($rows)) {
                    foreach ($rows as $row) {
                        $normalized = legacy_game_history_normalize_row(
                            $row,
                            (string)$historyUserCode,
                            (string)$historyExtUser,
                            $agentBalanceLocal,
                            $type
                        );

                        if (!legacy_game_history_in_date_range((string)$normalized['created_at'], $start, $end)) {
                            continue;
                        }

                        $logRows[] = $normalized;
                    }
                }
                $totalCount += (int)($response['total_count'] ?? 0);
                $successCount++;
            }
        }

        // Secondary provider game history
        if ($apiError === '') {
            $secondaryHistoryUserCode = count($historyUsers) === 1 ? (string)array_key_first($historyUsers) : '';
            $secondaryResponse = $ZH->getGameHistory($secondaryHistoryUserCode, $perPage);
            if (is_array($secondaryResponse) && isset($secondaryResponse['status'])) {
                if ((int)$secondaryResponse['status'] === 200) {
                    foreach (legacy_game_history_response_rows($secondaryResponse, 'data') as $secondaryRow) {
                        $secondaryUser = (string)legacy_game_history_pick($secondaryRow, ['user_code', 'userCode', 'intUser', 'username', 'user'], '');
                        $secondaryCreated = (string)legacy_game_history_pick($secondaryRow, ['end_time', 'endTime', 'match_time', 'matchTime', 'start_time', 'startTime', 'created_at', 'createdAt'], '');
                        if ($secondaryUser === '' && $secondaryHistoryUserCode !== '') {
                            $secondaryUser = $secondaryHistoryUserCode;
                        }
                        if ($secondaryUser === '' || !isset($historyUsers[$secondaryUser])) {
                            continue;
                        }
                        if (!legacy_game_history_in_date_range($secondaryCreated, $start, $end)) {
                            continue;
                        }
                        $logRows[] = legacy_game_history_normalize_row($secondaryRow, $secondaryUser, (string)($historyUsers[$secondaryUser] ?? $secondaryUser), $agentBalanceLocal);
                        $secondaryRowsCount++;
                    }
                    $totalCount += $secondaryRowsCount;
                } elseif ((int)$secondaryResponse['status'] !== 404) {
                    $apiWarnings[] = $secondaryResponse['message'] ?? 'Gagal mengambil data provider tambahan.';
                }
            } else {
                $apiWarnings[] = 'Tidak ada response dari API provider tambahan.';
            }
        }

        if ($successCount === 0 && $secondaryRowsCount > 0) {
            $apiResponse = [
                'status' => 1,
                'total_count' => $secondaryRowsCount,
                'page' => $logPage,
                'perPage' => $perPage,
                'user_count' => count($historyUsers)
            ];
        } elseif ($successCount === 0) {
            $apiError = $apiWarnings[0] ?? 'Tidak ada response dari API.';
        } else {
            $apiResponse = [
                'status' => 1,
                'total_count' => $totalCount ?: count($logRows),
                'page' => $logPage,
                'perPage' => $perPage,
                'user_count' => count($historyUsers)
            ];
        }
    }
}

usort($logRows, static function (array $a, array $b): int {
    $left = strtotime((string)($a['created_at'] ?? '')) ?: 0;
    $right = strtotime((string)($b['created_at'] ?? '')) ?: 0;

    return $right <=> $left;
});

$historyTotal = count($logRows);
$historyBetTotal = 0.0;
$historyWinTotal = 0.0;
foreach ($logRows as $historyRow) {
    $historyBetTotal += (float)($historyRow['bet_money'] ?? 0);
    $historyWinTotal += (float)($historyRow['win_money'] ?? 0);
}
?>

<div class="app-page-shell">
    <div class="row g-4">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <h4 class="card-title mb-1">Riwayat Game</h4>
                <p class="text-muted mb-0">Gunakan filter untuk memuat data dari provider.</p>
                <p class="text-muted small mb-0">Kolom saldo agent memakai saldo agent saat ini.</p>
                <p class="text-muted small mb-0">
                    Member tersedia: <?= number_format($historyUserTotal, 0, ',', '.') ?> |
                    Opsi dimuat: <?= number_format(count($allowedUsers), 0, ',', '.') ?>
                    <?php if ($userSearch !== ''): ?>
                        | Hasil pencarian: <?= number_format($historyUserMatchTotal, 0, ',', '.') ?>
                    <?php endif; ?>
                </p>
            </div>
            <div class="card-body">
                <form method="get" id="gameHistoryForm" class="row g-3 align-items-end">
                    <input type="hidden" name="page" value="GameHistory">
                    <div class="col-12 col-md-3">
                        <label class="form-label" for="userSearch">Cari User</label>
                        <input type="text" id="userSearch" name="user_search" class="form-control" value="<?= htmlspecialchars($userSearch, ENT_QUOTES, 'UTF-8') ?>" placeholder="User site / User API">
                    </div>
                    <div class="col-12 col-md-4">
                        <label class="form-label" for="userSelect">Pengguna</label>
                        <select id="userSelect" name="user_code" class="form-control select2" data-placeholder="Pilih User">
                            <option value=""></option>
                            <?php if ($isAdmin): ?>
                                <option value="<?= htmlspecialchars($allUsersOptionValue, ENT_QUOTES, 'UTF-8') ?>"<?= $selectedUser === $allUsersOptionValue ? ' selected' : '' ?>>All User</option>
                            <?php endif; ?>
                            <?php foreach ($allowedUsers as $intUser => $extUser): ?>
                                <option value="<?= htmlspecialchars($intUser, ENT_QUOTES, 'UTF-8') ?>"<?= $selectedUser === $intUser ? ' selected' : '' ?>>
                                    <?= htmlspecialchars($extUser, ENT_QUOTES, 'UTF-8') ?> (<?= htmlspecialchars($intUser, ENT_QUOTES, 'UTF-8') ?>)
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <?php if ($isAdmin || $isHeadAgent): ?>
                    <div class="col-6 col-md-2">
                        <label class="form-label">Batch Member</label>
                        <select name="history_user_limit" class="form-control">
                            <?php foreach ([50, 100, 200, 500, 1000] as $limitOption): ?>
                                <option value="<?= $limitOption ?>"<?= $historyUserLimit === $limitOption ? ' selected' : '' ?>><?= number_format($limitOption, 0, ',', '.') ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <?php endif; ?>
                    <div class="col-6 col-md-2">
                        <label class="form-label">Tipe Game</label>
                        <select name="game_type" class="form-control">
                            <option value="all"<?= $selectedGameType === 'all' ? ' selected' : '' ?>>All</option>
                            <?php foreach ($gameTypes as $typeOption): ?>
                                <option value="<?= htmlspecialchars($typeOption, ENT_QUOTES, 'UTF-8') ?>"<?= $selectedGameType === $typeOption ? ' selected' : '' ?>>
                                    <?= htmlspecialchars(strtoupper($typeOption), ENT_QUOTES, 'UTF-8') ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-6 col-md-3">
                        <label class="form-label">Mulai</label>
                        <input type="text" name="start" class="form-control" value="<?= htmlspecialchars($start, ENT_QUOTES, 'UTF-8') ?>" placeholder="YYYY-MM-DD 00:00:00">
                    </div>
                    <div class="col-6 col-md-3">
                        <label class="form-label">Selesai</label>
                        <input type="text" name="end" class="form-control" value="<?= htmlspecialchars($end, ENT_QUOTES, 'UTF-8') ?>" placeholder="YYYY-MM-DD 23:59:59">
                    </div>
                    <div class="col-6 col-md-2">
                        <label class="form-label">Per Halaman</label>
                        <input type="number" name="per_page" class="form-control" min="1" max="1000" value="<?= htmlspecialchars((string)$perPage, ENT_QUOTES, 'UTF-8') ?>">
                    </div>
                    <div class="col-6 col-md-2">
                        <label class="form-label">Halaman</label>
                        <input type="number" name="log_page" class="form-control" min="0" value="<?= htmlspecialchars((string)$logPage, ENT_QUOTES, 'UTF-8') ?>">
                    </div>
                    <div class="col-12 col-md-2">
                        <button type="submit" class="btn btn-primary w-100">Muat</button>
                    </div>
                </form>

                <?php if ($apiError !== ''): ?>
                    <div class="alert alert-danger mt-3 mb-0"><?= htmlspecialchars($apiError, ENT_QUOTES, 'UTF-8') ?></div>
                <?php elseif ($apiResponse && (int)$apiResponse['status'] === 1): ?>
                    <div class="mt-3 text-muted">
                        Total data: <?= number_format((int)($apiResponse['total_count'] ?? 0), 0, ',', '.') ?> |
                        Halaman: <?= number_format((int)($apiResponse['page'] ?? 0), 0, ',', '.') ?> |
                        Per halaman: <?= number_format((int)($apiResponse['perPage'] ?? 0), 0, ',', '.') ?>
                        <?php if (isset($apiResponse['user_count'])): ?>
                            | Member: <?= number_format((int)$apiResponse['user_count'], 0, ',', '.') ?>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
                <?php if ($apiWarnings !== []): ?>
                    <div class="alert alert-warning mt-3 mb-0">
                        <?= htmlspecialchars(implode(' ', array_values(array_unique($apiWarnings))), ENT_QUOTES, 'UTF-8') ?>
                    </div>
                <?php endif; ?>

                <div class="table-responsive mt-3">
                    <table id="dataTableExample" class="table table-striped table-hover align-middle" data-order-col="13" data-order-dir="desc">
                        <thead class="table-light">
                            <tr>
                                <th>ID Riwayat</th>
                                <th>Pengguna</th>
                                <th>Provider</th>
                                <th>Game</th>
                                <th>Tipe</th>
                                <th>Taruhan</th>
                                <th>Menang</th>
                                <th>ID Transaksi</th>
                                <th>Tipe Transaksi</th>
                                <th>Saldo Awal User</th>
                                <th>Saldo Akhir User</th>
                                <th>Saldo Awal Agent</th>
                                <th>Saldo Akhir Agent</th>
                                <th>Dibuat</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!empty($logRows)): ?>
                                <?php foreach ($logRows as $row): ?>
                                    <?php
                                    $userCode = (string)($row['user_code'] ?? '-');
                                    $displayUser = $allowedUsers[$userCode] ?? (string)($row['user_member'] ?? $row['user'] ?? $userCode);
                                    ?>
                                    <tr>
                                        <td><?= htmlspecialchars((string)($row['history_id'] ?? '-'), ENT_QUOTES, 'UTF-8') ?></td>
                                        <td><?= htmlspecialchars($displayUser, ENT_QUOTES, 'UTF-8') ?></td>
                                        <td><?= htmlspecialchars((string)($row['provider_code'] ?? '-'), ENT_QUOTES, 'UTF-8') ?></td>
                                        <td><?= htmlspecialchars((string)($row['game_code'] ?? '-'), ENT_QUOTES, 'UTF-8') ?></td>
                                        <td><?= strtoupper(htmlspecialchars((string)($row['type'] ?? '-'), ENT_QUOTES, 'UTF-8')) ?></td>
                                        <td class="text-end"><?= number_format((float)($row['bet_money'] ?? 0), 0, ',', '.') ?></td>
                                        <td class="text-end"><?= number_format((float)($row['win_money'] ?? 0), 0, ',', '.') ?></td>
                                        <td class="text-nowrap"><?= htmlspecialchars((string)($row['txn_id'] ?? '-'), ENT_QUOTES, 'UTF-8') ?></td>
                                        <td><?= strtoupper(htmlspecialchars((string)($row['txn_type'] ?? '-'), ENT_QUOTES, 'UTF-8')) ?></td>
                                        <td class="text-end"><?= number_format((float)($row['user_start_balance'] ?? 0), 0, ',', '.') ?></td>
                                        <td class="text-end"><?= number_format((float)($row['user_end_balance'] ?? 0), 0, ',', '.') ?></td>
                                        <td class="text-end"><?= number_format((float)($row['agent_start_balance'] ?? $agentBalanceLocal), 0, ',', '.') ?></td>
                                        <td class="text-end"><?= number_format((float)($row['agent_end_balance'] ?? $agentBalanceLocal), 0, ',', '.') ?></td>
                                        <td class="text-nowrap"><?= htmlspecialchars((string)($row['created_at'] ?? '-'), ENT_QUOTES, 'UTF-8') ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td class="text-center">Tidak ada data.</td>
                                    <td></td>
                                    <td></td>
                                    <td></td>
                                    <td></td>
                                    <td></td>
                                    <td></td>
                                    <td></td>
                                    <td></td>
                                    <td></td>
                                    <td></td>
                                    <td></td>
                                    <td></td>
                                    <td></td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
</div>

<style>
#gameHistoryForm .form-label {
    font-size: 1rem;
}
@media (max-width: 576px) {
    #gameHistoryForm .form-label {
        font-size: 1rem;
    }
}
</style>

<script>
document.addEventListener("DOMContentLoaded", function () {
    var selectId = "#userSelect";

    function ensureSelect2Styles() {
        if (document.querySelector('link[href*="assets/vendors/select2/select2.min.css"]')) {
            return;
        }
        var link = document.createElement("link");
        link.rel = "stylesheet";
        link.href = "assets/vendors/select2/select2.min.css";
        document.head.appendChild(link);
    }

    function activateSelect2() {
        if (!window.jQuery || !window.jQuery.fn || !window.jQuery.fn.select2) {
            return false;
        }
        ensureSelect2Styles();
        var $select = window.jQuery(selectId);
        if ($select.length === 0) {
            return false;
        }
        if ($select.hasClass("select2-hidden-accessible")) {
            return true;
        }
        $select.select2({
            width: "100%",
            minimumResultsForSearch: 0,
            placeholder: $select.data("placeholder") || "Pilih User",
            allowClear: true,
            dropdownParent: $select.closest(".card"),
            ajax: {
                url: "function/game_history_users.php",
                dataType: "json",
                delay: 250,
                data: function (params) {
                    return {
                        q: params.term || "",
                        page: params.page || 1
                    };
                },
                processResults: function (data) {
                    return {
                        results: data.results || [],
                        pagination: {
                            more: !!(data.pagination && data.pagination.more)
                        }
                    };
                },
                cache: true
            }
        });
        return true;
    }

    function loadAndInit() {
        if (activateSelect2()) {
            return;
        }
        var script = document.createElement("script");
        script.src = "assets/vendors/select2/select2.min.js";
        script.onload = function () {
            activateSelect2();
        };
        document.body.appendChild(script);
    }

    loadAndInit();

    // Retry in case scripts load late (mobile/slow network)
    var retries = 0;
    var maxRetries = 10;
    var interval = setInterval(function () {
        retries++;
        if (activateSelect2() || retries >= maxRetries) {
            clearInterval(interval);
        }
    }, 300);
});
</script>
