<?php
declare(strict_types=1);

require_once __DIR__ . '/bootstrap.php';
require_once __DIR__ . '/admin_auth_lib.php';
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/external_players_sync_lib.php';

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    http_response_code(405);
    echo json_encode(['ok' => false, 'error' => 'method'], JSON_UNESCAPED_UNICODE);
    exit;
}

mocker_admin_require_any_permission(['members', 'ip-clashes']);

if (!mocker_external_players_enabled()) {
    echo json_encode(
        [
            'ok' => true,
            'externalEnabled' => false,
            'syncComplete' => true,
            'syncedCount' => 0,
        ],
        JSON_UNESCAPED_UNICODE
    );
    exit;
}

try {
    $pdo = mocker_db();
} catch (Throwable $e) {
    http_response_code(503);
    echo json_encode(['ok' => false, 'error' => 'db'], JSON_UNESCAPED_UNICODE);
    exit;
}

if (isset($_GET['reset']) && (string) $_GET['reset'] === '1') {
    mocker_external_players_sync_reset_progress($pdo);
    $status = mocker_external_players_sync_status($pdo, true);
    echo json_encode(['ok' => true, 'reset' => true] + $status, JSON_UNESCAPED_UNICODE);
    exit;
}

if (isset($_GET['status']) && (string) $_GET['status'] === '1') {
    $status = mocker_external_players_sync_status($pdo, true);
    echo json_encode(['ok' => true] + $status, JSON_UNESCAPED_UNICODE);
    exit;
}

$page = max(1, (int) ($_GET['page'] ?? 1));
$filters = [
    'id' => (string) ($_GET['id'] ?? ''),
    'username' => (string) ($_GET['username'] ?? ''),
    'telegram_username' => (string) ($_GET['telegram_username'] ?? ''),
    'ip' => (string) ($_GET['ip'] ?? ''),
];

try {
    if (function_exists('set_time_limit')) {
        @set_time_limit(120);
    }
    $result = mocker_external_players_sync_page($pdo, $page, $filters);
    $status = mocker_external_players_sync_status($pdo, false);
    $syncComplete = $result['sync_complete'] ?? $status['syncComplete'];
    echo json_encode(
        [
            'ok' => true,
            'page' => $page,
            'pagination' => $result['pagination'],
            'page_stats' => $result['page_stats'],
            'synced_total' => $result['synced_total'],
            'syncComplete' => $syncComplete,
            'remoteTotal' => max((int) ($result['remote_total'] ?? 0), (int) $status['remoteTotal']),
            'resumePage' => $status['resumePage'],
            'missingCount' => $status['missingCount'],
        ],
        JSON_UNESCAPED_UNICODE
    );
} catch (Throwable $e) {
    error_log('admin_members_sync failed: ' . $e->getMessage());
    $partial = 0;
    try {
        $partial = mocker_external_players_synced_count($pdo);
    } catch (Throwable $ignored) {
    }
    $status = mocker_external_players_sync_status($pdo, true);
    http_response_code(502);
    echo json_encode(
        [
            'ok' => false,
            'error' => 'sync_failed',
            'message' => $e->getMessage(),
            'synced_total' => $partial,
            'syncComplete' => $status['syncComplete'],
            'remoteTotal' => $status['remoteTotal'],
            'resumePage' => $status['resumePage'],
            'lastSyncedPage' => $status['lastSyncedPage'],
        ],
        JSON_UNESCAPED_UNICODE
    );
}
