<?php
declare(strict_types=1);

require_once __DIR__ . '/bootstrap.php';
require_once __DIR__ . '/gamdom_turnuva_lib.php';

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate');

$dataFile = dirname(__DIR__) . '/data/gamdom-turnuva.json';
$read = static function (string $path): array {
    if (!is_readable($path)) {
        return [];
    }
    $raw = (string) file_get_contents($path);
    if (str_starts_with($raw, "\xEF\xBB\xBF")) {
        $raw = substr($raw, 3);
    }
    $j = json_decode($raw, true);
    return is_array($j) ? $j : [];
};

$cfg = $read($dataFile);
$enabled = !empty($cfg['enabled']);

if (!$enabled) {
    echo json_encode(['ok' => true, 'enabled' => false], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

$periodId = isset($_GET['period']) ? trim((string) $_GET['period']) : '';
if ($periodId !== '' && !preg_match('/^\d{4}-\d{2}$/', $periodId)) {
    $periodId = '';
}

$api = isset($cfg['api']) && is_array($cfg['api']) ? $cfg['api'] : [];
$apiError = null;
if (!empty($api['enabled']) && trim((string) ($api['url'] ?? '')) !== '') {
    $live = gamdom_build_live_payload($cfg, $periodId);
    if ($live['ok']) {
        echo json_encode($live['payload'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        exit;
    }
    $apiError = $live['error'] ?? 'API kullanılamadı';
}

$activePeriodId = isset($cfg['activePeriodId']) ? trim((string) $cfg['activePeriodId']) : 'default';
if ($periodId === '') {
    $periodId = $activePeriodId !== '' ? $activePeriodId : 'default';
}

$periods = [];
if (isset($cfg['periods']) && is_array($cfg['periods'])) {
    foreach ($cfg['periods'] as $p) {
        if (!is_array($p)) {
            continue;
        }
        $id = isset($p['id']) ? trim((string) $p['id']) : '';
        $label = isset($p['label']) ? trim((string) $p['label']) : '';
        if ($id === '') {
            continue;
        }
        $periods[] = ['id' => $id, 'label' => $label !== '' ? $label : gamdom_month_label_tr($id)];
    }
}

$periodsData = isset($cfg['periodsData']) && is_array($cfg['periodsData']) ? $cfg['periodsData'] : [];
$bucket = isset($periodsData[$periodId]) && is_array($periodsData[$periodId]) ? $periodsData[$periodId] : [];
$rawEntries = isset($bucket['entries']) && is_array($bucket['entries']) ? $bucket['entries'] : [];

$entries = [];
foreach ($rawEntries as $row) {
    if (!is_array($row)) {
        continue;
    }
    $hidden = !empty($row['hidden']);
    $username = $hidden ? 'Hidden user' : trim((string) ($row['username'] ?? ''));
    if ($username === '' && !$hidden) {
        $username = '—';
    }
    $wager = isset($row['wager']) ? (float) $row['wager'] : 0.0;
    $wagerDisplay = trim((string) ($row['wagerDisplay'] ?? ''));
    if ($wagerDisplay === '' && $wager > 0) {
        $wagerDisplay = number_format($wager, 2, '.', ',') . '$';
    }
    $entries[] = [
        'rank' => isset($row['rank']) ? max(1, (int) $row['rank']) : 0,
        'username' => $username,
        'hidden' => $hidden,
        'wager' => $wager,
        'wagerDisplay' => $wagerDisplay,
        'reward' => trim((string) ($row['reward'] ?? '')),
    ];
}

usort($entries, static function (array $a, array $b): int {
    $wa = (float) ($a['wager'] ?? 0);
    $wb = (float) ($b['wager'] ?? 0);
    if ($wa !== $wb) {
        return $wb <=> $wa;
    }
    return ($a['rank'] ?? 0) <=> ($b['rank'] ?? 0);
});

foreach ($entries as $i => &$e) {
    $e['rank'] = $i + 1;
}
unset($e);
$entries = array_slice($entries, 0, 50);

$endAt = $cfg['endAt'] ?? null;
if ($endAt !== null && $endAt !== '') {
    $endAt = (int) $endAt;
    if ($endAt < 0) {
        $endAt = null;
    }
} else {
    $endAt = null;
}

$out = [
    'ok' => true,
    'enabled' => true,
    'source' => 'static',
    'title' => trim((string) ($cfg['title'] ?? 'Gamdom Çevrim Etkinliği')),
    'prizePool' => trim((string) ($cfg['prizePool'] ?? '')),
    'logoUrl' => trim((string) ($cfg['logoUrl'] ?? '')),
    'ctaLabel' => trim((string) ($cfg['ctaLabel'] ?? '')),
    'ctaUrl' => trim((string) ($cfg['ctaUrl'] ?? '')),
    'rulesUrl' => trim((string) ($cfg['rulesUrl'] ?? '')),
    'rulesText' => trim((string) ($cfg['rulesText'] ?? '')),
    'rulesTitle' => trim((string) ($cfg['rulesTitle'] ?? '')) ?: 'Kurallar ve Şartlar',
    'endAt' => $endAt,
    'activePeriodId' => $periodId,
    'periods' => $periods,
    'entries' => $entries,
];

if ($apiError !== null) {
    $out['warning'] = 'api_fallback';
    $out['apiError'] = $apiError;
}

echo json_encode($out, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
