<?php
declare(strict_types=1);

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

header('Content-Type: application/json; charset=utf-8');

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

mocker_require_csrf_post();
mocker_admin_require_login();
mocker_admin_require_permission('site');

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

$dataFile = dirname(__DIR__) . '/data/gamdom-turnuva.json';
if (!is_readable($dataFile)) {
    http_response_code(404);
    echo json_encode(['ok' => false, 'error' => 'gamdom-turnuva.json bulunamadı'], JSON_UNESCAPED_UNICODE);
    exit;
}

$raw = (string) file_get_contents($dataFile);
if (str_starts_with($raw, "\xEF\xBB\xBF")) {
    $raw = substr($raw, 3);
}
$cfg = json_decode($raw, true);
if (!is_array($cfg)) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => 'Geçersiz yapılandırma dosyası'], JSON_UNESCAPED_UNICODE);
    exit;
}

$api = isset($cfg['api']) && is_array($cfg['api']) ? $cfg['api'] : [];
if (isset($input['apiUrl']) && trim((string) $input['apiUrl']) !== '') {
    $api['url'] = trim((string) $input['apiUrl']);
}
if (isset($input['apiKey'])) {
    $api['apiKey'] = trim((string) $input['apiKey']);
}
if (isset($input['clientId']) && trim((string) $input['clientId']) !== '') {
    $api['clientId'] = trim((string) $input['clientId']);
}
$cfg['api'] = $api;

if (empty($api['enabled'])) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'Harici API kapalı. Önce API\'yi etkinleştirin.'], JSON_UNESCAPED_UNICODE);
    exit;
}

$live = gamdom_build_live_payload($cfg, $periodId);
if (!$live['ok']) {
    http_response_code(502);
    echo json_encode(['ok' => false, 'error' => $live['error'] ?? 'Senkron başarısız'], JSON_UNESCAPED_UNICODE);
    exit;
}

$payload = $live['payload'];
$activePeriodId = $payload['activePeriodId'] ?? $periodId;
if ($activePeriodId === '') {
    $activePeriodId = 'default';
}

if (!isset($cfg['periodsData']) || !is_array($cfg['periodsData'])) {
    $cfg['periodsData'] = [];
}
$cfg['periodsData'][$activePeriodId] = ['entries' => $payload['entries'] ?? []];

if (!empty($payload['periods']) && is_array($payload['periods'])) {
    $cfg['periods'] = $payload['periods'];
}
$cfg['activePeriodId'] = $activePeriodId;
if (!empty($payload['title'])) {
    $cfg['title'] = $payload['title'];
}
if (!empty($payload['prizePool'])) {
    $cfg['prizePool'] = $payload['prizePool'];
}
if (!empty($payload['endAt'])) {
    $cfg['endAt'] = $payload['endAt'];
}

$encoded = json_encode($cfg, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
if ($encoded === false) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => 'JSON encode hatası'], JSON_UNESCAPED_UNICODE);
    exit;
}

if (file_put_contents($dataFile, $encoded . "\n") === false) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => 'Dosya yazılamadı'], JSON_UNESCAPED_UNICODE);
    exit;
}

echo json_encode([
    'ok' => true,
    'periodId' => $activePeriodId,
    'count' => count($payload['entries'] ?? []),
    'title' => $payload['title'] ?? '',
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
