<?php
declare(strict_types=1);

require_once __DIR__ . '/bootstrap.php';
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/special_odds_engine.php';

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

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    http_response_code(405);
    echo json_encode(['ok' => false, 'error' => 'method'], 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;
}

$now = time();

function mocker_special_odds_public_map_row(array $r, int $now, bool $isHistory): array
{
    $kick = (int) ($r['kickoff_at'] ?? 0);
    $status = (string) ($r['status'] ?? '');
    $maxP = isset($r['max_participants']) ? max(0, (int) $r['max_participants']) : 0;
    $pc = isset($r['participant_count']) ? (int) $r['participant_count'] : 0;
    $timeOk = $status === 'open' && $kick > $now;
    $full = $maxP > 0 && $pc >= $maxP;
    $bettingOpen = $timeOk && !$full && $status === 'open';

    $oo = isset($r['odds_offered']) && (float) $r['odds_offered'] >= 1.0 ? (float) $r['odds_offered'] : (float) $r['odds_home'];
    $pool = isset($r['pool_total']) ? (int) $r['pool_total'] : 0;

    return [
        'id' => (int) $r['id'],
        'externalEventId' => (string) $r['external_event_id'],
        'homeName' => (string) $r['home_name'],
        'awayName' => (string) $r['away_name'],
        'logoHomeUrl' => $r['logo_home_url'] !== null && $r['logo_home_url'] !== '' ? (string) $r['logo_home_url'] : null,
        'logoAwayUrl' => $r['logo_away_url'] !== null && $r['logo_away_url'] !== '' ? (string) $r['logo_away_url'] : null,
        'kickoffAt' => $kick,
        'predictionText' => isset($r['prediction_text']) ? (string) $r['prediction_text'] : '',
        'oddsOffered' => $oo,
        'poolTotal' => $pool,
        'oddsHome' => (float) $r['odds_home'],
        'oddsDraw' => (float) $r['odds_draw'],
        'oddsAway' => (float) $r['odds_away'],
        'maxParticipants' => $maxP,
        'participantCount' => $pc,
        'bettingFull' => $full,
        'matchStatus' => $status,
        'bettingOpen' => $bettingOpen,
        'result' => $r['result'] !== null ? (string) $r['result'] : null,
        'homeGoals' => $r['home_goals'] !== null ? (int) $r['home_goals'] : null,
        'awayGoals' => $r['away_goals'] !== null ? (int) $r['away_goals'] : null,
        'isHistory' => $isHistory,
    ];
}

$stOpen = $pdo->query(
    'SELECT m.id, m.external_event_id, m.home_name, m.away_name, m.logo_home_url, m.logo_away_url, m.kickoff_at,
            m.odds_home, m.odds_draw, m.odds_away, m.prediction_text, m.admin_pick, m.odds_offered, m.max_participants,
            m.status, m.result, m.home_goals, m.away_goals,
            (SELECT COUNT(*) FROM special_odds_bets b WHERE b.match_id = m.id AND b.status = \'pending\') AS participant_count,
            (SELECT COALESCE(SUM(stake), 0) FROM special_odds_bets b WHERE b.match_id = m.id AND b.status = \'pending\') AS pool_total
     FROM special_odds_matches m
     WHERE m.is_active = 1 AND m.status = \'open\'
     ORDER BY m.kickoff_at ASC, m.id ASC
     LIMIT 100'
);
$rowsOpen = $stOpen ? $stOpen->fetchAll(PDO::FETCH_ASSOC) : [];
$out = [];
foreach ($rowsOpen as $r) {
    $out[] = mocker_special_odds_public_map_row($r, $now, false);
}

$stHist = $pdo->query(
    'SELECT m.id, m.external_event_id, m.home_name, m.away_name, m.logo_home_url, m.logo_away_url, m.kickoff_at,
            m.odds_home, m.odds_draw, m.odds_away, m.prediction_text, m.admin_pick, m.odds_offered, m.max_participants,
            m.status, m.result, m.home_goals, m.away_goals, m.updated_at,
            (SELECT COUNT(*) FROM special_odds_bets b WHERE b.match_id = m.id) AS participant_count,
            (SELECT COALESCE(SUM(stake), 0) FROM special_odds_bets b WHERE b.match_id = m.id) AS pool_total
     FROM special_odds_matches m
     WHERE m.is_active = 1 AND m.status IN (\'settled\',\'cancelled\')
     ORDER BY m.updated_at DESC, m.id DESC
     LIMIT 100'
);
$rowsHist = $stHist ? $stHist->fetchAll(PDO::FETCH_ASSOC) : [];
$hist = [];
foreach ($rowsHist as $r) {
    $hist[] = mocker_special_odds_public_map_row($r, $now, true);
}

echo json_encode(
    [
        'ok' => true,
        'stakeMin' => SPECIAL_ODDS_MIN_STAKE,
        'stakeMax' => SPECIAL_ODDS_MAX_STAKE,
        'matches' => $out,
        'history' => $hist,
        'serverTime' => $now,
    ],
    JSON_UNESCAPED_UNICODE
);
