<?php
require_once '../config/database.php';

$method = $_SERVER['REQUEST_METHOD'];
$input = getInput();

try {
    $db = getDB();

    switch ($method) {
        case 'GET':
            // Get all races with rounds and results
            if (isset($_GET['studentId'])) {
                // Get races for specific student
                $studentId = $_GET['studentId'];
                $stmt = $db->prepare("SELECT DISTINCT r.* FROM sprint_races r
                    JOIN sprint_rounds ro ON r.id = ro.race_id
                    JOIN sprint_results res ON ro.id = res.round_id
                    WHERE res.student_id = ? ORDER BY r.race_date DESC");
                $stmt->execute([$studentId]);
                $races = $stmt->fetchAll();
            } else {
                $stmt = $db->query("SELECT * FROM sprint_races ORDER BY race_date DESC, created_at DESC");
                $races = $stmt->fetchAll();
            }

            // Fetch rounds and participants for each race
            foreach ($races as &$race) {
                $roundStmt = $db->prepare("SELECT * FROM sprint_rounds WHERE race_id = ?");
                $roundStmt->execute([$race['id']]);
                $rounds = $roundStmt->fetchAll();

                foreach ($rounds as &$round) {
                    $resultStmt = $db->prepare("SELECT res.*, s.full_name as student_name
                        FROM sprint_results res
                        LEFT JOIN students s ON res.student_id = s.id
                        WHERE res.round_id = ?");
                    $resultStmt->execute([$round['id']]);
                    $round['participants'] = $resultStmt->fetchAll();
                }
                $race['rounds'] = $rounds;
            }

            sendJson($races);
            break;

        case 'POST':
            if (isset($input['action']) && $input['action'] === 'create') {
                // Create new race
                $stmt = $db->prepare("INSERT INTO sprint_races (name, distance, race_date, status, created_by)
                    VALUES (?, ?, ?, 'pending', ?)");
                $stmt->execute([
                    $input['name'] ?? '',
                    $input['distance'] ?? '500m',
                    $input['date'] ?? date('Y-m-d'),
                    $input['createdBy'] ?? 0
                ]);
                $raceId = $db->lastInsertId();

                // Create first round
                $roundStmt = $db->prepare("INSERT INTO sprint_rounds (race_id, round_number) VALUES (?, 1)");
                $roundStmt->execute([$raceId]);
                $roundId = $db->lastInsertId();

                // Add participants
                if (isset($input['participants']) && is_array($input['participants'])) {
                    $resultStmt = $db->prepare("INSERT INTO sprint_results
                        (round_id, student_id, position, time_seconds, time_display, status)
                        VALUES (?, ?, NULL, NULL, NULL, 'pending')");
                    foreach ($input['participants'] as $p) {
                        $resultStmt->execute([$roundId, $p['studentId']]);
                    }
                }

                sendJson(['success' => true, 'raceId' => $raceId]);
            }
            elseif (isset($input['action']) && $input['action'] === 'saveRound') {
                // Save round results (from lap data)
                $roundId = $input['roundId'] ?? 0;

                if (isset($input['results']) && is_array($input['results'])) {
                    $updateStmt = $db->prepare("UPDATE sprint_results
                        SET position = ?, time_seconds = ?, time_display = ?, status = ?
                        WHERE round_id = ? AND student_id = ?");
                    foreach ($input['results'] as $r) {
                        $updateStmt->execute([
                            $r['position'] ?? null,
                            $r['timeSeconds'] ?? null,
                            $r['timeDisplay'] ?? null,
                            $r['status'] ?? 'finished',
                            $roundId,
                            $r['studentId']
                        ]);
                    }
                }

                // Mark round as completed
                $db->prepare("UPDATE sprint_rounds SET completed_at = NOW() WHERE id = ?")
                   ->execute([$roundId]);

                // Mark race as completed
                $db->prepare("UPDATE sprint_races SET status = 'completed' WHERE id = ?")
                   ->execute([$input['raceId'] ?? 0]);

                sendJson(['success' => true]);
            }
            break;

        case 'DELETE':
            $id = $_GET['id'] ?? 0;
            // Delete results first, then rounds, then race
            $db->prepare("DELETE res FROM sprint_results res
                JOIN sprint_rounds ro ON res.round_id = ro.id
                WHERE ro.race_id = ?")->execute([$id]);
            $db->prepare("DELETE FROM sprint_rounds WHERE race_id = ?")->execute([$id]);
            $db->prepare("DELETE FROM sprint_races WHERE id = ?")->execute([$id]);
            sendJson(['success' => true]);
            break;

        default:
            sendJson(['error' => 'Method not allowed'], 405);
    }
} catch (Exception $e) {
    sendJson(['error' => $e->getMessage()], 500);
}
