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

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

try {
    $db = getDB();

    switch ($method) {
        case 'GET':
            // Get timing records
            $studentId = $_GET['studentId'] ?? '';
            $distance = $_GET['distance'] ?? '';

            $sql = "SELECT t.*, s.full_name as student_name FROM timing_records t
                    LEFT JOIN students s ON t.student_id = s.id WHERE 1=1";
            $params = [];

            if ($studentId) {
                $sql .= " AND t.student_id = ?";
                $params[] = $studentId;
            }
            if ($distance && $distance !== 'All') {
                $sql .= " AND t.distance = ?";
                $params[] = $distance;
            }

            $sql .= " ORDER BY t.record_date DESC, t.created_at DESC";
            $stmt = $db->prepare($sql);
            $stmt->execute($params);
            sendJson($stmt->fetchAll());
            break;

        case 'POST':
            // Save timing record
            $parts = explode(':', $input['time'] ?? '00:00');
            $mins = (int)$parts[0];
            $secs = isset($parts[1]) ? (float)$parts[1] : 0;
            $totalSeconds = $mins * 60 + $secs;

            $stmt = $db->prepare("INSERT INTO timing_records
                (student_id, distance, time_seconds, time_display, record_date, notes, recorded_by)
                VALUES (?, ?, ?, ?, ?, ?, ?)");
            $stmt->execute([
                $input['studentId'] ?? 0,
                $input['distance'] ?? '500m',
                $totalSeconds,
                $input['time'] ?? '00:00.00',
                $input['date'] ?? date('Y-m-d'),
                $input['notes'] ?? '',
                $input['recordedBy'] ?? 0
            ]);
            sendJson(['success' => true, 'id' => $db->lastInsertId()]);
            break;

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