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

header('Content-Type: application/json');
header('X-Content-Type-Options: nosniff');

function game_history_users_fail(int $httpCode, string $message): void
{
    http_response_code($httpCode);
    echo json_encode([
        'results' => [],
        'message' => $message,
    ], JSON_UNESCAPED_SLASHES);
    exit;
}

function game_history_users_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 (empty($_SESSION['admin'])) {
    game_history_users_fail(403, 'FORBIDDEN');
}

$sessionAgentIdentity = (string)($_SESSION['admin']['agent_name'] ?? ($_SESSION['admin']['agent_code'] ?? ''));
$agent = agent_find_by_identifier($call, $sessionAgentIdentity) ?? (array)$_SESSION['admin'];

if (trim((string)($agent['agent_name'] ?? $agent['agent_code'] ?? '')) === '') {
    game_history_users_fail(403, 'FORBIDDEN');
}

$term = trim((string)($_GET['q'] ?? ($_GET['term'] ?? '')));
$page = max(1, (int)($_GET['page'] ?? 1));
$limit = 25;
$offset = ($page - 1) * $limit;
$fetchLimit = $limit + 1;

$whereParts = [
    game_history_users_scope_condition($call, 'u.agent_code', (array)$agent),
];

$orderSql = 'u.created DESC';
if ($term !== '') {
    $termLikeSql = legacy_escape_like($call, $term);
    $termSql = mysqli_real_escape_string($call, $term);
    $whereParts[] = "(
        u.extUser LIKE '%$termLikeSql%' ESCAPE '\\\\'
        OR u.intUser LIKE '%$termLikeSql%' ESCAPE '\\\\'
        OR u.agent_code LIKE '%$termLikeSql%' ESCAPE '\\\\'
    )";
    $orderSql = "CASE
        WHEN u.extUser = '$termSql' OR u.intUser = '$termSql' THEN 0
        WHEN u.extUser LIKE '$termLikeSql%' ESCAPE '\\\\' OR u.intUser LIKE '$termLikeSql%' ESCAPE '\\\\' THEN 1
        ELSE 2
    END, u.created DESC";
}

$whereSql = implode(' AND ', $whereParts);
$query = mysqli_query(
    $call,
    "SELECT u.intUser, u.extUser
     FROM tb_user u
     WHERE $whereSql
     ORDER BY $orderSql
     LIMIT $offset, $fetchLimit"
);

if (!$query) {
    game_history_users_fail(500, 'QUERY FAILED');
}

$results = [];
while ($row = mysqli_fetch_assoc($query)) {
    $intUser = (string)($row['intUser'] ?? '');
    $extUser = (string)($row['extUser'] ?? '');
    if ($intUser === '') {
        continue;
    }

    $results[] = [
        'id' => $intUser,
        'text' => $extUser !== '' ? "$extUser ($intUser)" : $intUser,
    ];
}

$hasMore = count($results) > $limit;
if ($hasMore) {
    array_pop($results);
}

echo json_encode([
    'results' => $results,
    'pagination' => [
        'more' => $hasMore,
    ],
], JSON_UNESCAPED_SLASHES);
