<?php
declare(strict_types=1);

require_once __DIR__ . '/bootstrap.php';
require_once __DIR__ . '/db.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;
}

$uid = isset($_SESSION['mocker_user_id']) ? (int) $_SESSION['mocker_user_id'] : 0;
if ($uid <= 0) {
    http_response_code(401);
    echo json_encode(['ok' => false, 'error' => 'auth'], 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;
}

$st = $pdo->prepare(
    'SELECT b.id, b.match_id, b.pick, b.stake, b.odds_applied, b.payout_on_win, b.status, b.created_at, b.settled_at,
            m.home_name, m.away_name, m.prediction_text, m.kickoff_at, m.status AS match_status, m.result, m.home_goals, m.away_goals
     FROM special_odds_bets b
     JOIN special_odds_matches m ON m.id = b.match_id
     WHERE b.user_id = :u
     ORDER BY b.created_at DESC, b.id DESC
     LIMIT 100'
);
$st->execute([':u' => $uid]);
$bets = [];
foreach ($st->fetchAll(PDO::FETCH_ASSOC) as $r) {
    $bets[] = [
        'id' => (int) $r['id'],
        'matchId' => (int) $r['match_id'],
        'pick' => (string) $r['pick'],
        'stake' => (int) $r['stake'],
        'oddsApplied' => (float) $r['odds_applied'],
        'payoutOnWin' => (int) $r['payout_on_win'],
        'status' => (string) $r['status'],
        'createdAt' => (int) $r['created_at'],
        'settledAt' => $r['settled_at'] !== null ? (int) $r['settled_at'] : null,
        'homeName' => (string) $r['home_name'],
        'awayName' => (string) $r['away_name'],
        'predictionText' => isset($r['prediction_text']) ? (string) $r['prediction_text'] : '',
        'kickoffAt' => (int) $r['kickoff_at'],
        'matchStatus' => (string) $r['match_status'],
        'matchResult' => $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,
    ];
}

echo json_encode(['ok' => true, 'bets' => $bets], JSON_UNESCAPED_UNICODE);
