<?php
/**
 * Heat Bracket View API
 * Generates the bracket grid HTML for display across different interfaces
 */

header('Content-Type: application/json');
include '../includes/db.php';

// Get parameters
$event_id = isset($_GET['event_id']) ? intval($_GET['event_id']) : 0;
$compact_mode = isset($_GET['compact']) && $_GET['compact'] == '1';

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

try {
    // Fetch heat settings
    $heat_stmt = $pdo->prepare("
        SELECT heat_number, heat_name, scoring_type, runs_count, runs_scoring_method, 
               time_start, estimate_time_per_participant, categories, 
               flow_type, flow_source_heat, flow_participants_per_category,
               is_active, active_run
        FROM event_heat_settings 
        WHERE event_id = ? 
        ORDER BY heat_number ASC
    ");
    $heat_stmt->execute([$event_id]);
    $heat_settings_array = $heat_stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $heat_settings = [];
    foreach ($heat_settings_array as $setting) {
        $heat_num = $setting['heat_number'];
        // categories is already a JSON column in MariaDB
        if (isset($setting['categories']) && is_string($setting['categories'])) {
            $setting['categories'] = json_decode($setting['categories'], true) ?: [];
        }
        $heat_settings[$heat_num] = $setting;
    }
    
    // Fetch participants for each heat
    $participant_stmt = $pdo->prepare("
        SELECT ep.heat_number, ep.bib_number, p.id as participant_id, 
               p.first_name, p.last_name, p.country
        FROM event_participants ep
        JOIN participants p ON ep.participant_id = p.id
        WHERE ep.event_id = ?
        ORDER BY ep.heat_number, ep.sort_order, ep.bib_number
    ");
    $participant_stmt->execute([$event_id]);
    $all_participants = $participant_stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $heat_participants = [];
    $participants_by_id = [];
    foreach ($all_participants as $participant) {
        $heat_num = $participant['heat_number'];
        $participant_id = $participant['participant_id'];
        
        if (!isset($heat_participants[$heat_num])) {
            $heat_participants[$heat_num] = [];
        }
        $heat_participants[$heat_num][] = $participant_id;
        
        // Store participant details by ID
        if (!isset($participants_by_id[$participant_id])) {
            $participants_by_id[$participant_id] = [
                'first_name' => $participant['first_name'],
                'last_name' => $participant['last_name'],
                'country' => $participant['country'],
                'bib_number' => $participant['bib_number'],
                'run_scores' => [],
                'best_score' => null,
                'average_score' => null
            ];
        }
    }
    
    // Fetch scores for all participants in this event
    $scores_stmt = $pdo->prepare("
        SELECT ep.participant_id, r.run_number, s.score_value
        FROM event_participants ep
        JOIN runs r ON r.event_participant_id = ep.id
        JOIN scores s ON s.run_id = r.id
        WHERE ep.event_id = ? AND s.is_approved = 1
        ORDER BY ep.participant_id, r.run_number
    ");
    $scores_stmt->execute([$event_id]);
    $all_scores = $scores_stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Process scores for each participant
    foreach ($all_scores as $score_row) {
        $participant_id = $score_row['participant_id'];
        $run_number = $score_row['run_number'];
        $score_value = floatval($score_row['score_value']);
        
        if (isset($participants_by_id[$participant_id])) {
            // Store run score
            if (!isset($participants_by_id[$participant_id]['run_scores'][$run_number])) {
                $participants_by_id[$participant_id]['run_scores'][$run_number] = $score_value;
            } else {
                // If multiple scores exist for same run, keep the highest (or average them)
                $existing = $participants_by_id[$participant_id]['run_scores'][$run_number];
                $participants_by_id[$participant_id]['run_scores'][$run_number] = max($existing, $score_value);
            }
        }
    }
    
    // Calculate best and average scores for each participant
    foreach ($participants_by_id as $participant_id => &$participant) {
        if (!empty($participant['run_scores'])) {
            $scores = array_values($participant['run_scores']);
            $participant['best_score'] = max($scores);
            $participant['average_score'] = array_sum($scores) / count($scores);
        }
    }
    unset($participant); // Break reference
    
    // Build bracket levels
    $bracket_levels = [];
    $processed_heats = [];
    
    // Find starting heats (no source heat)
    $starting_heats = [];
    foreach ($heat_settings as $heat) {
        $source_heats = [];
        if (!empty($heat['flow_source_heat'])) {
            $decoded = json_decode($heat['flow_source_heat'], true);
            $source_heats = is_array($decoded) ? $decoded : [$heat['flow_source_heat']];
        }
        if (empty($source_heats)) {
            $starting_heats[] = $heat;
        }
    }
    
    // Build levels
    $bracket_levels[0] = $starting_heats;
    $current_level = 0;
    
    while (!empty($bracket_levels[$current_level])) {
        $next_level = [];
        foreach ($bracket_levels[$current_level] as $heat) {
            $processed_heats[] = $heat['heat_number'];
        }
        
        // Find heats that flow from current level
        foreach ($heat_settings as $potential_next) {
            if (in_array($potential_next['heat_number'], $processed_heats)) continue;
            
            $source_heats = [];
            if (!empty($potential_next['flow_source_heat'])) {
                $decoded = json_decode($potential_next['flow_source_heat'], true);
                $source_heats = is_array($decoded) ? $decoded : [$potential_next['flow_source_heat']];
            }
            
            // Check if any source heat is in current level
            $has_source_in_level = false;
            foreach ($bracket_levels[$current_level] as $level_heat) {
                if (in_array($level_heat['heat_number'], $source_heats)) {
                    $has_source_in_level = true;
                    break;
                }
            }
            
            if ($has_source_in_level && !in_array($potential_next, $next_level)) {
                $next_level[] = $potential_next;
            }
        }
        
        if (!empty($next_level)) {
            $bracket_levels[++$current_level] = $next_level;
        } else {
            break;
        }
    }
    
    // Build connections data
    $connections = [];
    foreach ($heat_settings as $heat) {
        if (!empty($heat['flow_source_heat'])) {
            $decoded = json_decode($heat['flow_source_heat'], true);
            $source_heats = is_array($decoded) ? $decoded : [$heat['flow_source_heat']];
            foreach ($source_heats as $source) {
                $connections[] = [
                    'from' => (int)$source,
                    'to' => (int)$heat['heat_number']
                ];
            }
        }
    }
    
    // Generate HTML
    ob_start();
    
    if ($compact_mode) {
        // Compact mode for judge overlay
        include 'heat_bracket_compact.php';
    } else {
        // Full mode for admin
        include 'heat_bracket_full.php';
    }
    
    $html = ob_get_clean();
    
    echo json_encode([
        'success' => true,
        'html' => $html,
        'connections' => $connections,
        'bracket_levels' => array_map(function($level) {
            return array_map(function($heat) {
                return $heat['heat_number'];
            }, $level);
        }, $bracket_levels)
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
