<?php
// =============================================================================
// /api/sports/sync.php — admin "Pull now" + settings save.
// POST action=run             — fire a sync, return counts
// POST action=set_provider    — { provider: 'free'|'paid', paid_sportsdb_key: '…' }
// GET  ?action=status         — last log entry + cache info
// =============================================================================
require_once __DIR__ . '/../_common.php';
require_csrf_unless_get();

list($action, $body) = read_action();

if ($action === 'status' || ($action === '' && $_SERVER['REQUEST_METHOD'] === 'GET')) {
    $last = db_one('SELECT * FROM sports_sync_log ORDER BY id DESC LIMIT 1');
    $provider_setting = db_one('SELECT value FROM webview_settings WHERE key=?', ['sports_provider']);
    $key_setting      = db_one('SELECT value FROM webview_settings WHERE key=?', ['paid_sportsdb_key']);
    json_response([
        'last'              => $last,
        'sports_provider'   => $provider_setting ? (string)$provider_setting['value'] : 'free',
        'paid_key_set'      => !empty($key_setting['value']),
        'league_count'      => (int)db_one('SELECT COUNT(*) c FROM sports_leagues')['c'],
        'event_count'       => (int)db_one('SELECT COUNT(*) c FROM sports_events')['c'],
    ]);
}

require_method('POST');

if ($action === 'set_provider') {
    $provider = (string)($body['provider'] ?? 'free');
    if (!in_array($provider, ['free', 'paid', 'manual'], true)) json_error('invalid provider', 400);
    require_once __DIR__ . '/../../includes/sports/sync.php';
    wv_setting_set('sports_provider', $provider);
    if (isset($body['paid_sportsdb_key'])) {
        wv_setting_set('paid_sportsdb_key', (string)$body['paid_sportsdb_key']);
    }
    json_response(['ok' => true]);
}

if ($action === 'run') {
    require_once __DIR__ . '/../../includes/sports/sync.php';
    $r = sports_sync_once();
    json_response($r);
}

json_error('unknown action', 400);
