<?php
header('Content-Type: application/json');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');

require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/api.php';

$id = (int)($_GET['id'] ?? 1001);
$match = get_fixture($id);

if (!$match) {
    http_response_code(404);
    echo json_encode(['error' => 'Match not found']);
    exit;
}

$local = $match['localteam'] ?? $match['localTeam'] ?? [];
$visitor = $match['visitorteam'] ?? $match['visitorTeam'] ?? [];
$local_score = get_score_string($match, $local['id'] ?? 0);
$visitor_score = get_score_string($match, $visitor['id'] ?? 0);
$status_info = format_status($match['status'] ?? '');

$response = [
    'success' => true,
    'id' => $match['id'],
    'name' => $match['name'] ?? '',
    'type' => format_match_type($match['type'] ?? 'T20'),
    'status' => $status_info['label'],
    'status_class' => $status_info['class'],
    'note' => $match['note'] ?? '',
    'local_team' => [
        'id' => $local['id'] ?? 0,
        'name' => $local['name'] ?? 'Team A',
        'code' => $local['code'] ?? 'T1',
        'score' => $local_score
    ],
    'visitor_team' => [
        'id' => $visitor['id'] ?? 0,
        'name' => $visitor['name'] ?? 'Team B',
        'code' => $visitor['code'] ?? 'T2',
        'score' => $visitor_score
    ],
    'crr' => $match['crr'] ?? '0.00',
    'rrr' => $match['rrr'] ?? '0.00',
    'target' => $match['target'] ?? 0,
    'runs_needed' => $match['runs_needed'] ?? 0,
    'balls_remaining' => $match['balls_remaining'] ?? 0,
    'recent_balls' => $match['recent_balls'] ?? [],
    'partnership' => $match['partnership'] ?? null,
    'win_probability' => $match['win_probability'] ?? null,
    'odds' => $match['odds'] ?? null,
    'sessions' => $match['sessions'] ?? [],
    'batting' => $match['batting'] ?? [],
    'bowling' => $match['bowling'] ?? [],
    'fow' => $match['fow'] ?? [],
    'timestamp' => time()
];

echo json_encode($response, JSON_PRETTY_PRINT);
