<?php
// TV Overlay API - Real-time data for overlays
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

error_reporting(E_ALL);
ini_set('display_errors', 1);

try {
    require_once '../includes/db.php';
    
    if (!isset($pdo)) {
        throw new Exception('Database connection not established');
    }
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Database connection failed: ' . $e->getMessage()]);
    exit;
}

$action = $_GET['action'] ?? '';
$event_id = (int)($_GET['event_id'] ?? 0);

switch ($action) {
    case 'participants':
        getParticipants($pdo, $event_id);
        break;
    
    case 'ranking_configs':
        getRankingConfigs($pdo, $event_id);
        break;
    
    case 'start_list':
        getStartList($pdo, $event_id);
        break;
    
    case 'rankings':
        getRankings($pdo, $event_id);
        break;
    
    case 'participant_detail':
        $participant_id = (int)($_GET['participant_id'] ?? 0);
        getParticipantDetail($pdo, $event_id, $participant_id);
        break;
    
    case 'live_scores':
        getLiveScores($pdo, $event_id);
        break;
    
    case 'judge_scores':
        $participant_id = (int)($_GET['participant_id'] ?? 0);
        getJudgeScores($pdo, $event_id, $participant_id);
        break;
    
    case 'start_list':
        getStartList($pdo, $event_id);
        break;
    
    case 'event_info':
        getEventInfo($pdo, $event_id);
        break;
    
    default:
        http_response_code(400);
        echo json_encode(['error' => 'Invalid action']);
        break;
}

function getRankingConfigs($pdo, $event_id) {
    try {
        // Get all summary table configurations for this event
        $query = "
            SELECT 
                id,
                name,
                category,
                heat_number,
                configuration
            FROM result_configurations 
            WHERE event_id = ? 
            ORDER BY name ASC
        ";
        
        $stmt = $pdo->prepare($query);
        $stmt->execute([$event_id]);
        $configs = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        echo json_encode(['status' => 'success', 'data' => $configs]);
        
    } catch (Exception $e) {
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    }
}

function getStartList($pdo, $event_id) {
    try {
        $heat_number = isset($_GET['heat_number']) ? (int)$_GET['heat_number'] : null;
        
        // Build the URL for start_list_api.php
        $start_list_url = "http://localhost/v2/api/start_list_api.php?event_id={$event_id}&format=json";
        if ($heat_number) {
            $start_list_url .= "&heat_number={$heat_number}";
        }
        
        // Use cURL for reliable HTTP requests
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $start_list_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        
        $start_list_json = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curl_error = curl_error($ch);
        curl_close($ch);
        
        if ($start_list_json === false || !empty($curl_error)) {
            echo json_encode(['status' => 'error', 'message' => 'cURL error: ' . $curl_error, 'url' => $start_list_url]);
            return;
        }
        
        if ($http_code !== 200) {
            echo json_encode(['status' => 'error', 'message' => "HTTP error: {$http_code}", 'url' => $start_list_url]);
            return;
        }
        
        $start_list_data = json_decode($start_list_json, true);
        
        if (!$start_list_data) {
            echo json_encode(['status' => 'error', 'message' => 'Invalid JSON response', 'response' => $start_list_json]);
            return;
        }
        
        // Return the start list data directly
        echo json_encode($start_list_data);
        
    } catch (Exception $e) {
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    }
}

function getParticipants($pdo, $event_id) {
    try {
        // Use the existing start_list_api.php with cURL
        $start_list_url = "http://localhost/v2/api/start_list_api.php?event_id={$event_id}&format=json";
        
        // Use cURL for reliable HTTP requests
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $start_list_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        
        $start_list_json = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        $start_list_data = json_decode($start_list_json, true);
        
        if (!$start_list_data || $http_code !== 200 || !isset($start_list_data['status']) || $start_list_data['status'] !== 'success') {
            // Fallback to direct database query if API fails
            $query = "
                SELECT 
                    ep.id as participant_id,
                    p.first_name,
                    p.last_name,
                    CONCAT(p.first_name, ' ', p.last_name) as name,
                    p.country,
                    ep.bib_number,
                    ep.category,
                    ep.heat_number,
                    0 as best_score
                FROM event_participants ep
                JOIN participants p ON ep.participant_id = p.id
                WHERE ep.event_id = ?
                ORDER BY ep.heat_number, ep.bib_number
            ";
            
            $stmt = $pdo->prepare($query);
            $stmt->execute([$event_id]);
            $participants = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            echo json_encode(['status' => 'success', 'data' => $participants]);
            return;
        }
        
        // Transform start list data for TV overlay use
        $participants = [];
        foreach ($start_list_data['data'] as $heat_data) {
            if (isset($heat_data['participants'])) {
                foreach ($heat_data['participants'] as $participant) {
                    $participants[] = [
                        'participant_id' => $participant['id'] ?? 0,
                        'first_name' => $participant['first_name'] ?? '',
                        'last_name' => $participant['last_name'] ?? '',
                        'name' => trim(($participant['first_name'] ?? '') . ' ' . ($participant['last_name'] ?? '')),
                        'country' => $participant['country'] ?? '',
                        'bib_number' => $participant['bib_number'] ?? 0,
                        'category' => $participant['category'] ?? '',
                        'heat_number' => $participant['heat_number'] ?? 0,
                        'best_score' => 0 // Will be populated by rankings API
                    ];
                }
            }
        }
        
        echo json_encode(['status' => 'success', 'data' => $participants]);
    } catch (Exception $e) {
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    }
}

function getRankings($pdo, $event_id) {
    try {
        $limit = (int)($_GET['limit'] ?? 10);
        $config_id = (int)($_GET['config_id'] ?? 0);
        $category = $_GET['category'] ?? 'all';
        
        // If config_id is provided, use it for consistent results with reports
        if ($config_id > 0) {
            $summary_url = "http://localhost/v2/api/summary_table_api.php?config_id={$config_id}&format=json";
        } else {
            // Fallback to basic event_id approach, but we should find a default config
            // Try to find a default summary configuration for this event
            $config_stmt = $pdo->prepare("
                SELECT id, name 
                FROM result_configurations 
                WHERE event_id = ? 
                ORDER BY id DESC 
                LIMIT 1
            ");
            $config_stmt->execute([$event_id]);
            $config = $config_stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($config) {
                $config_id = $config['id'];
                $summary_url = "http://localhost/v2/api/summary_table_api.php?config_id={$config_id}&format=json";
            } else {
                // Last resort: use basic event_id approach
                $summary_url = "http://localhost/v2/api/summary_table_api.php?event_id={$event_id}&category={$category}&format=json&sort=OverallAverage&sort_direction=desc";
            }
        }
        
        // Use cURL for reliable HTTP requests
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $summary_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        
        $summary_json = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curl_error = curl_error($ch);
        curl_close($ch);
        
        if ($summary_json === false || !empty($curl_error)) {
            echo json_encode(['status' => 'error', 'message' => 'cURL error: ' . $curl_error, 'url' => $summary_url]);
            return;
        }
        
        if ($http_code !== 200) {
            echo json_encode(['status' => 'error', 'message' => "HTTP error: {$http_code}", 'url' => $summary_url]);
            return;
        }
        
        $summary_data = json_decode($summary_json, true);
        
        if (!$summary_data || !isset($summary_data['status']) || $summary_data['status'] !== 'success') {
            // Fallback to simplified query if API fails
            $query = "
                SELECT 
                    ep.id as participant_id,
                    p.first_name,
                    p.last_name,
                    CONCAT(p.first_name, ' ', p.last_name) as name,
                    p.country,
                    ep.bib_number,
                    ep.category,
                    ep.heat_number,
                    0 as best_score,
                    0 as completed_runs
                FROM event_participants ep
                JOIN participants p ON ep.participant_id = p.id
                WHERE ep.event_id = ?
                ORDER BY ep.bib_number ASC
                LIMIT " . (int)$limit . "
            ";
            
            $stmt = $pdo->prepare($query);
            $stmt->execute([$event_id]);
            $rankings = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            echo json_encode(['status' => 'success', 'data' => $rankings]);
            return;
        }
        
        // Transform summary data for TV overlay rankings
        $rankings = [];
        $rank = 1;
        
        if (isset($summary_data['data']['participants'])) {
            foreach ($summary_data['data']['participants'] as $participant) {
                if ($rank > $limit) break;
                
                $rankings[] = [
                    'rank' => $rank,
                    'participant_id' => $participant['participant_id'] ?? 0,
                    'first_name' => $participant['first_name'] ?? '',
                    'last_name' => $participant['last_name'] ?? '',
                    'name' => $participant['participant_name'] ?? trim(($participant['first_name'] ?? '') . ' ' . ($participant['last_name'] ?? '')),
                    'country' => $participant['country'] ?? '',
                    'bib_number' => $participant['bib'] ?? 0,
                    'category' => $participant['category'] ?? '',
                    'heat_number' => $participant['heat_number'] ?? 0,
                    'best_score' => $participant['OverallAverage'] ?? 0,
                    'completed_runs' => $participant['completed_runs'] ?? 0
                ];
                $rank++;
            }
        }
        
        echo json_encode(['status' => 'success', 'data' => $rankings]);
    } catch (Exception $e) {
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    }
}

function getParticipantDetail($pdo, $event_id, $participant_id) {
    // Get participant basic info from proper StyleScore v2 structure
    $query = "
        SELECT 
            ep.id as participant_id,
            p.first_name,
            p.last_name,
            CONCAT(p.first_name, ' ', p.last_name) as name,
            ep.country,
            ep.bib_number,
            ep.category,
            e.name as event_name,
            e.discipline
        FROM event_participants ep
        JOIN participants p ON ep.participant_id = p.id
        JOIN events e ON ep.event_id = e.id
        WHERE ep.event_id = ? AND ep.id = ?
    ";
    
    $stmt = $pdo->prepare($query);
    $stmt->execute([$event_id, $participant_id]);
    $participant = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$participant) {
        http_response_code(404);
        echo json_encode(['error' => 'Participant not found']);
        return;
    }
    
    // Get scores
    $score_query = "
        SELECT 
            s.run_number,
            s.total_score,
            s.timestamp,
            s.score_status
        FROM scores s
        WHERE s.event_id = ? AND s.participant_id = ?
        ORDER BY s.run_number DESC
    ";
    
    $stmt = $pdo->prepare($score_query);
    $stmt->execute([$event_id, $participant_id]);
    $scores_results = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $scores = [];
    $best_score = 0;
    $current_score = 0;
    $current_score_time = '';
    
    foreach ($scores_results as $score_row) {
        $score = (float)$score_row['total_score'];
        $scores[] = [
            'run' => (int)$score_row['run_number'],
            'score' => $score,
            'timestamp' => $score_row['timestamp'],
            'status' => $score_row['score_status']
        ];
        
        if ($score > $best_score) {
            $best_score = $score;
        }
        
        if ($score_row['run_number'] == 1 || 
            ($score_row['timestamp'] && $score_row['timestamp'] > $current_score_time)) {
            $current_score = $score;
            $current_score_time = $score_row['timestamp'];
        }
    }
    
    // Get current rank
    $rank_query = "
        SELECT COUNT(*) + 1 as rank_position
        FROM (
            SELECT p2.participant_id, COALESCE(MAX(s2.total_score), 0) as best
            FROM participants p2
            LEFT JOIN scores s2 ON p2.participant_id = s2.participant_id
            WHERE p2.event_id = ?
            GROUP BY p2.participant_id
            HAVING best > ?
        ) ranked
    ";
    
    $stmt = $pdo->prepare($rank_query);
    $stmt->execute([$event_id, $best_score]);
    $rank_row = $stmt->fetch(PDO::FETCH_ASSOC);
    $current_rank = (int)$rank_row['rank_position'];
    
    $response = [
        'participant' => [
            'id' => $participant['participant_id'],
            'name' => trim($participant['first_name'] . ' ' . $participant['last_name']),
            'country' => $participant['country'],
            'bib' => '#' . $participant['bib_number'],
            'category' => $participant['category'],
            'event' => $participant['event_name'],
            'discipline' => $participant['discipline']
        ],
        'scores' => [
            'current' => $current_score,
            'best' => $best_score,
            'runs' => $scores
        ],
        'rank' => [
            'position' => $current_rank,
            'ordinal' => getOrdinal($current_rank)
        ]
    ];
    
    echo json_encode($response);
}

function getLiveScores($pdo, $event_id) {
    try {
        $limit = (int)($_GET['limit'] ?? 5);
        
        // Get the most recent scores from StyleScore system
        $query = "
            SELECT 
                p.first_name,
                p.last_name,
                CONCAT(p.first_name, ' ', p.last_name) as name,
                ep.bib_number,
                r.run_number,
                s.score_value,
                s.status,
                COALESCE(s.updated_at, s.created_at) as timestamp,
                u.username as judge_name,
                ecp.control_point_name
            FROM scores s
            JOIN runs r ON s.run_id = r.id
            JOIN event_participants ep ON r.event_participant_id = ep.id
            JOIN participants p ON ep.participant_id = p.id
            LEFT JOIN users u ON u.judge_id = s.judge_id OR u.id = s.judge_id
            LEFT JOIN judge_assignments ja ON ja.judge_id = s.judge_id AND ja.event_id = ep.event_id
            LEFT JOIN event_control_points ecp ON ecp.id = ja.control_point_id
            WHERE ep.event_id = ?
            AND s.status = 'OK'
            AND s.score_value IS NOT NULL
            ORDER BY COALESCE(s.updated_at, s.created_at) DESC
            LIMIT ?
        ";
        
        $stmt = $pdo->prepare($query);
        $stmt->execute([$event_id, $limit]);
        $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        $live_scores = [];
        foreach ($results as $row) {
            $live_scores[] = [
                'participant_name' => trim($row['first_name'] . ' ' . $row['last_name']),
                'bib' => '#' . $row['bib_number'],
                'run' => (int)$row['run_number'],
                'score' => (float)$row['score_value'],
                'judge' => $row['judge_name'] ?? 'Unknown Judge',
                'control_point' => $row['control_point_name'] ?? 'Main',
                'timestamp' => $row['timestamp'],
                'status' => $row['status']
            ];
        }
        
        echo json_encode(['live_scores' => $live_scores]);
        
    } catch (Exception $e) {
        // Return demo data if query fails
        $demo_scores = [
            ['participant_name' => 'Yuki Tanaka', 'bib' => '#3', 'run' => 2, 'score' => 92.25, 'judge' => 'Judge A', 'control_point' => 'Main', 'timestamp' => date('Y-m-d H:i:s'), 'status' => 'OK'],
            ['participant_name' => 'Sarah Johnson', 'bib' => '#2', 'run' => 2, 'score' => 89.75, 'judge' => 'Judge B', 'control_point' => 'Main', 'timestamp' => date('Y-m-d H:i:s', strtotime('-1 minute')), 'status' => 'OK'],
            ['participant_name' => 'John Smith', 'bib' => '#1', 'run' => 1, 'score' => 85.50, 'judge' => 'Judge C', 'control_point' => 'Main', 'timestamp' => date('Y-m-d H:i:s', strtotime('-2 minutes')), 'status' => 'OK']
        ];
        echo json_encode(['live_scores' => $demo_scores]);
    }
}

function getJudgeScores($pdo, $event_id, $participant_id) {
    try {
        $run_number = (int)($_GET['run_number'] ?? 1);
        
        // Get real judge scores from StyleScore system
        $query = "
            SELECT 
                s.judge_id,
                COALESCE(u1.username, u2.username, CONCAT('Judge ', s.judge_id)) as judge_name,
                s.score_value,
                s.status,
                COALESCE(s.updated_at, s.created_at) as timestamp,
                ecp.control_point_name,
                s.figures_json
            FROM scores s
            JOIN runs r ON s.run_id = r.id
            JOIN event_participants ep ON r.event_participant_id = ep.id
            LEFT JOIN users u1 ON u1.judge_id = s.judge_id
            LEFT JOIN users u2 ON u2.id = s.judge_id
            LEFT JOIN judge_assignments ja ON ja.judge_id = s.judge_id AND ja.event_id = ep.event_id
            LEFT JOIN event_control_points ecp ON ecp.id = ja.control_point_id
            WHERE ep.event_id = ? 
            AND ep.id = ? 
            AND r.run_number = ?
            ORDER BY s.judge_id, COALESCE(s.updated_at, s.created_at) DESC
        ";
        
        $stmt = $pdo->prepare($query);
        $stmt->execute([$event_id, $participant_id, $run_number]);
        $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        $judge_scores = [];
        foreach ($results as $row) {
            $figures = [];
            if ($row['figures_json']) {
                $decoded = json_decode($row['figures_json'], true);
                if (is_array($decoded)) {
                    $figures = $decoded;
                }
            }
            
            $judge_scores[] = [
                'judge_id' => $row['judge_id'],
                'judge_name' => $row['judge_name'],
                'score' => (float)$row['score_value'],
                'status' => $row['status'],
                'control_point' => $row['control_point_name'] ?? 'Main',
                'timestamp' => $row['timestamp'],
                'figures' => $figures
            ];
        }
        
        echo json_encode(['judge_scores' => $judge_scores]);
        
    } catch (Exception $e) {
        // Return demo data if query fails
        $demo_scores = [
            ['judge_id' => 1, 'judge_name' => 'Judge A', 'score' => 92.5, 'status' => 'OK', 'control_point' => 'Main', 'timestamp' => date('Y-m-d H:i:s'), 'figures' => []],
            ['judge_id' => 2, 'judge_name' => 'Judge B', 'score' => 91.0, 'status' => 'OK', 'control_point' => 'Main', 'timestamp' => date('Y-m-d H:i:s'), 'figures' => []],
            ['judge_id' => 3, 'judge_name' => 'Judge C', 'score' => 93.0, 'status' => 'OK', 'control_point' => 'Main', 'timestamp' => date('Y-m-d H:i:s'), 'figures' => []]
        ];
        echo json_encode(['judge_scores' => $demo_scores]);
    }
}

function getEventInfo($pdo, $event_id) {
    try {
        // Use StyleScore v2 column names
        $query = "
            SELECT 
                e.id as event_id,
                e.name as event_name,
                e.discipline,
                e.date as event_date,
                e.location,
                e.status as event_status,
                COUNT(ep.id) as participant_count
            FROM events e
            LEFT JOIN event_participants ep ON e.id = ep.event_id
            WHERE e.id = ?
            GROUP BY e.id
        ";
        
        $stmt = $pdo->prepare($query);
        $stmt->execute([$event_id]);
        $event = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$event) {
            // Try alternative table structure
            $query = "
                SELECT 
                    e.id as event_id,
                    e.name as event_name,
                    e.discipline,
                    e.date as event_date,
                    e.location,
                    e.status as event_status,
                    COUNT(p.id) as participant_count
                FROM events e
                LEFT JOIN participants p ON e.id = p.event_id
                WHERE e.id = ?
                GROUP BY e.id
            ";
            
            $stmt = $pdo->prepare($query);
            $stmt->execute([$event_id]);
            $event = $stmt->fetch(PDO::FETCH_ASSOC);
        }
        
        if (!$event) {
            http_response_code(404);
            echo json_encode(['error' => 'Event not found']);
            return;
        }
        
        echo json_encode(['event' => $event]);
        
    } catch (Exception $e) {
        // Return demo data if query fails
        $demo_event = [
            'event_id' => $event_id,
            'event_name' => 'Demo Freestyle Event',
            'discipline' => 'freestyle',
            'event_date' => date('Y-m-d'),
            'location' => 'Demo Location',
            'event_status' => 'active',
            'participant_count' => 3
        ];
        echo json_encode(['event' => $demo_event]);
    }
}

function getOrdinal($number) {
    $ends = ['th','st','nd','rd','th','th','th','th','th','th'];
    if ((($number % 100) >= 11) && (($number % 100) <= 13)) {
        return $number . 'th';
    } else {
        return $number . $ends[$number % 10];
    }
}
?>
