<?php
/**
 * Heat Bracket Data API
 * Returns raw heat data in JSON format for external bracket renderers
 */

header('Content-Type: application/json; charset=utf-8');
require_once __DIR__ . '/../includes/db.php';

try {
    $event_id = isset($_GET['event_id']) ? intval($_GET['event_id']) : null;

    if (!$event_id) {
        echo json_encode([
            'success' => false,
            'error' => 'Event ID is required'
        ]);
        exit;
    }

    // Get event details
    $event_stmt = $pdo->prepare("SELECT name FROM events WHERE id = ?");
    $event_stmt->execute([$event_id]);
    $event = $event_stmt->fetch(PDO::FETCH_ASSOC);

    // Debug: log what we got
    error_log("Event ID: $event_id, Result: " . json_encode($event));

    if (!$event) {
        echo json_encode([
            'success' => false,
            'error' => 'Event not found',
            'debug_event_id' => $event_id,
            'debug_result' => $event
        ]);
        exit;
    }

    // Get heat settings with flow information
    $heats_stmt = $pdo->prepare("
        SELECT 
            heat_number,
            heat_name,
            runs_count,
            runs_scoring_method,
            categories,
            is_active,
            flow_source_heat,
            flow_participants_per_category
        FROM event_heat_settings 
        WHERE event_id = ? 
        ORDER BY heat_number
    ");
    $heats_stmt->execute([$event_id]);
    $heats = $heats_stmt->fetchAll(PDO::FETCH_ASSOC);

    // Build heat hierarchy to determine levels
    $heat_levels = [];
    $max_level = 1;
    
    foreach ($heats as &$heat) {
        $heat_num = $heat['heat_number'];
        
        if ($heat['flow_source_heat']) {
            // This heat has a source, so it's at least level 2
            $source_level = $heat_levels[$heat['flow_source_heat']] ?? 1;
            $heat_levels[$heat_num] = $source_level + 1;
            $max_level = max($max_level, $heat_levels[$heat_num]);
        } else {
            // No source = first round
            $heat_levels[$heat_num] = 1;
        }
        
        $heat['level'] = $heat_levels[$heat_num];
        $heat['heat_number'] = intval($heat['heat_number']);
        $heat['runs_count'] = intval($heat['runs_count']);
        $heat['is_active'] = intval($heat['is_active']);
        $heat['categories'] = json_decode($heat['categories'] ?? '[]', true);
        
        // Get participants for this heat
        $participants_stmt = $pdo->prepare("
            SELECT 
                p.id as participant_id,
                p.first_name,
                p.last_name,
                p.bib,
                ep.heat_number,
                (
                    SELECT MAX(s.score_value)
                    FROM event_participants ep2
                    INNER JOIN runs r ON r.event_participant_id = ep2.id
                    INNER JOIN scores s ON s.run_id = r.id
                    WHERE ep2.participant_id = p.id
                    AND ep2.event_id = ?
                    AND ep2.heat_number = ?
                    AND s.is_approved = 1
                ) as best_score
            FROM participants p
            INNER JOIN event_participants ep ON p.id = ep.participant_id
            WHERE ep.event_id = ?
            AND ep.heat_number = ?
            ORDER BY best_score DESC
        ");
        $participants_stmt->execute([$event_id, $heat_num, $event_id, $heat_num]);
        $participants = $participants_stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Format participant data
        $heat['participants'] = array_map(function($p) {
            return [
                'id' => intval($p['participant_id']),
                'name' => trim($p['first_name'] . ' ' . $p['last_name']),
                'bib' => intval($p['bib']),
                'best_score' => $p['best_score'] ? floatval($p['best_score']) : null
            ];
        }, $participants);
        
        $heat['participant_count'] = count($participants);
    }

    // Build connections array for flow visualization
    $connections = [];
    foreach ($heats as $heat) {
        if ($heat['flow_source_heat']) {
            $connections[] = [
                'from' => intval($heat['flow_source_heat']),
                'to' => intval($heat['heat_number']),
                'participants' => intval($heat['flow_participants_per_category'] ?? 0)
            ];
        }
    }

    echo json_encode([
        'success' => true,
        'event' => [
            'id' => $event_id,
            'name' => $event['name']
        ],
        'heats' => $heats,
        'connections' => $connections,
        'max_level' => $max_level,
        'total_heats' => count($heats)
    ], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);

} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'error' => 'Database error: ' . $e->getMessage()
    ]);
}
