<?php
// filepath: c:\stylescore2025\htdocs\v2\admin\heat_flow_api.php
/*
API: GET /v2/admin/heat_flow_api.php
Auth:
- Requires an authenticated session (includes/auth.php). Use credentials/cookies when calling.

Description:
- Returns event heat flow chains, live progress, BIB info, and per-heat summary results
  (via api/summary_table_api.php). Useful for monitoring and automated flow decisions.

Query parameters:
- event_id (required, int): Event ID to inspect.

Response (application/json):
{
  "event": { "id": 1, "name": "Event Name", "heats_total": 3, "date": "2025-08-01" },
  "flow_chains": [
    [
      {
        "heat_number": 1,
        "heat_name": "Qualifiers",
        "flow_type": "none",
        "flow_source_heat": null,
        "is_active": true,
        "active_run": 1,
        "categories": ["All Categories"],
        "participant_count": 24,
        "time_start": "09:00:00",
        "estimate_time_per_participant": 90,
        "scoring_type": "Points",
        "runs_count": 2,
        "runs_scoring_method": "best_from_all",
        "bib_on_start": 12,
        "bib_latest_on_run": 18,
        "current_participant": { "bib_number": 12, "sort_order": 120, "name": "A. Rider", "category": "Pro" },
        "next_participant": { "bib_number": 15, "sort_order": 150, "name": "B. Rider", "category": "Pro" },
        "progress": {
          "total_participants": 24,
          "completed_participants": 10,
          "completion_percentage": 41.7,
          "participants_with_scores": 9,
          "scoring_completion_percentage": 37.5
        },
        "participants_summary": {
          "total": 24,
          "has_participants": true,
          "first_bib": 1,
          "last_bib": 99
        },
        "summary_results": {
          "by_category": { "all": { "success": true, "participant_count": 24, "table_head": "...", "table_body": "..." } },
          "combined_rankings_by_category": { "all": [ { "rank": 1, "bib_number": 7, "participant_name": "C. Rider", "primary_score": 92.5 } ] },
          "top_3_by_category": { "all": [ { "rank": 1, "bib_number": 7, "participant_name": "C. Rider" } ] },
          "statistics": { "total_participants": 24, "categories_processed": 1, "categories": ["all"], "has_results": true },
          "has_results": true,
          "total_with_scores": 24,
          "categories_with_results": ["all"],
          "categories_with_rankings": ["all"],
          "participant_count_by_category": { "all": 24 }
        }
      }
    ]
  ],
  "statistics": {
    "total_heats": 3,
    "flow_chains": 1,
    "auto_flow_heats": 0,
    "starting_heats": 1,
    "total_participants": 60,
    "active_heats": 1,
    "completed_participants": 10,
    "heats_with_active_participants": 1,
    "overall_completion_percentage": 16.7,
    "heats_with_results": 1,
    "total_participants_with_scores": 24,
    "scoring_completion_percentage": 40.0,
    "overall_highest_score": 98.0,
    "categories_with_results": ["all"],
    "categories_with_results_count": 1
  },
  "timestamp": 1723286400
}

Usage examples (Windows-friendly):

1) curl.exe (session cookie required)
- First, log in via your app to get PHPSESSID in your browser, then reuse it:
  curl.exe "http://localhost/v2/admin/heat_flow_api.php?event_id=123" ^
    -H "Cookie: PHPSESSID=YOUR_SESSION_ID"

2) PowerShell (with cookies)
  $sess = New-Object Microsoft.PowerShell.Commands.WebRequestSession
  $sess.Cookies.Add((New-Object System.Net.Cookie("PHPSESSID","YOUR_SESSION_ID","/","localhost")))
  Invoke-RestMethod -Uri "http://localhost/v2/admin/heat_flow_api.php?event_id=123" -WebSession $sess

3) Browser JavaScript (fetch with credentials)
  fetch('/v2/admin/heat_flow_api.php?event_id=123', { credentials: 'include' })
    .then(r => r.json())
    .then(data => console.log('Flow:', data))
    .catch(console.error);

4) PHP (cURL with cookie)
  <?php
  $ch = curl_init('http://localhost/v2/admin/heat_flow_api.php?event_id=123');
  curl_setopt_array($ch, [
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_HTTPHEADER => ['Cookie: PHPSESSID=YOUR_SESSION_ID']
  ]);
  $json = curl_exec($ch);
  curl_close($ch);
  $data = json_decode($json, true);
  print_r($data);
  ?>

Notes:
- Replace YOUR_SESSION_ID with a valid session cookie value.
- Ensure summary_table_api.php is reachable at /v2/api/summary_table_api.php since this endpoint calls it internally.
*/
include '../includes/auth.php';
include '../includes/db.php';

header('Content-Type: application/json');

// Function to call summary table API for a specific heat and category
function getSummaryTableResults($event_id, $heat_number, $category, $scoring_type = 'Points') {
    $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'];
    $base_path = '/v2';
    $api_url = "{$protocol}://{$host}{$base_path}/api/summary_table_api.php";
    
    $params = [
        'event_id' => $event_id,
        'category' => $category,
        'gender' => 'all',
        'sort' => 'HighestAverage',
        'heat_run_filter' => json_encode([$heat_number => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]),
        'show_runs' => 'true',
        'show_judges' => 'false',
        'show_control_points' => 'false',
        'show_heat_best' => 'true',
        'show_heat_average' => 'true',
        'show_overall_best' => 'false',
        'show_highest_average' => 'false'
    ];
    
    $query_string = http_build_query($params);
    $full_url = $api_url . '?' . $query_string;
    
    // Use cURL to make the API call
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $full_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Heat Flow Internal API Call');
    
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curl_error = curl_error($ch);
    curl_close($ch);
    
    if ($http_code !== 200 || !$response || !empty($curl_error)) {
        return [
            'success' => false,
            'error' => "HTTP {$http_code}: {$curl_error}",
            'participant_count' => 0,
            'table_head' => '',
            'table_body' => '',
            'rankings' => []
        ];
    }
    
    $data = json_decode($response, true);
    if (!$data) {
        return [
            'success' => false,
            'error' => 'Failed to parse JSON response: ' . json_last_error_msg(),
            'participant_count' => 0,
            'table_head' => '',
            'table_body' => '',
            'rankings' => []
        ];
    }
    
    // Extract rankings from table HTML if successful
    $rankings = [];
    if ($data['success'] && !empty($data['table_body'])) {
        $rankings = parseTableHTMLToRankings($data['table_body'], $scoring_type);
    }
    
    return [
        'success' => $data['success'] ?? false,
        'participant_count' => $data['participant_count'] ?? 0,
        'table_head' => $data['table_head'] ?? '',
        'table_body' => $data['table_body'] ?? '',
        'rankings' => $rankings,
        'statistics' => [
            'total_participants' => $data['participant_count'] ?? 0,
            'categories_processed' => $data['categories_processed'] ?? [$category],
            'is_grouped' => $data['is_grouped'] ?? false
        ],
        'api_url' => $full_url,
        'debug_info' => $data['debug_info'] ?? []
    ];
}

// Function to parse HTML table into structured rankings
function parseTableHTMLToRankings($table_html, $scoring_type = 'Points') {
    $rankings = [];
    
    if (empty($table_html)) {
        return $rankings;
    }
    
    $dom = new DOMDocument();
    libxml_use_internal_errors(true);
    @$dom->loadHTML('<table>' . $table_html . '</table>');
    libxml_clear_errors();
    
    $rows = $dom->getElementsByTagName('tr');
    
    foreach ($rows as $row) {
        $cells = $row->getElementsByTagName('td');
        
        // Skip group header rows and rows with insufficient data
        if ($cells->length < 6) {
            continue;
        }
        
        // Check if this is a group header row
        $first_cell = $cells->item(0);
        if ($first_cell && $first_cell->getAttribute('colspan') > 1) {
            continue; // Skip group headers
        }
        
        $rank = trim($cells->item(0)->textContent);
        $bib = trim($cells->item(1)->textContent);
        $participant = trim($cells->item(2)->textContent);
        $category = trim($cells->item(3)->textContent);
        $club = trim($cells->item(4)->textContent);
        $gender = trim($cells->item(5)->textContent);
        
        // Extract scores from remaining columns
        $scores = [];
        $heat_best = null;
        $heat_average = null;
        
        for ($i = 6; $i < $cells->length; $i++) {
            $cell_text = trim($cells->item($i)->textContent);
            if ($cell_text !== '-' && $cell_text !== '' && is_numeric($cell_text)) {
                $score_value = floatval($cell_text);
                $scores[] = $score_value;
                
                // Assume last two numeric columns are heat best and heat average
                if ($i == $cells->length - 2) {
                    $heat_best = $score_value;
                }
                if ($i == $cells->length - 1) {
                    $heat_average = $score_value;
                }
            }
        }
        
        if (!empty($scores) && !empty($bib) && !empty($participant)) {
            $rankings[] = [
                'rank' => intval($rank) ?: count($rankings) + 1,
                'bib_number' => intval($bib),
                'participant_name' => $participant,
                'category' => $category,
                'club' => $club,
                'gender' => $gender,
                'heat_best' => $heat_best ?? max($scores),
                'heat_average' => $heat_average ?? (array_sum($scores) / count($scores)),
                'scores' => $scores,
                'highest_score' => max($scores),
                'primary_score' => $heat_average ?? max($scores)
            ];
        }
    }
    
    return $rankings;
}

// Function to get summary results for a heat across all its categories
function getHeatSummaryResults($pdo, $event_id, $heat_number, $heat_categories, $event_categories, $scoring_type = 'Points') {
    $category_results = [];
    $combined_rankings_by_category = [];
    $top_3_by_category = [];
    $total_participants = 0;
    
    // Determine which categories to process
    $categories_to_process = [];
    if (empty($heat_categories)) {
        $categories_to_process = ['all'];
    } else {
        // Convert category IDs to category names
        foreach ($event_categories as $cat) {
            if (in_array($cat['id'], $heat_categories)) {
                $categories_to_process[] = $cat['category_name'];
            }
        }
    }
    
    foreach ($categories_to_process as $category) {
        $result = getSummaryTableResults($event_id, $heat_number, $category, $scoring_type);
        
        $category_results[$category] = $result;
        $total_participants += $result['participant_count'];
        
        // Process rankings for this category
        $category_rankings = $result['rankings'];
        
        // Sort rankings for this category
        if ($scoring_type === 'Time') {
            usort($category_rankings, function($a, $b) {
                return ($a['primary_score'] ?? PHP_INT_MAX) <=> ($b['primary_score'] ?? PHP_INT_MAX);
            });
        } else {
            usort($category_rankings, function($a, $b) {
                return ($b['primary_score'] ?? 0) <=> ($a['primary_score'] ?? 0);
            });
        }
        
        // Update ranks after sorting and add source category
        foreach ($category_rankings as $index => &$ranking) {
            $ranking['category_rank'] = $index + 1;
            $ranking['source_category'] = $category;
        }
        
        // Store rankings by category (limit to top 20 for performance)
        $combined_rankings_by_category[$category] = array_slice($category_rankings, 0, 20);
        
        // Store top 3 for this category
        $top_3_by_category[$category] = array_slice($category_rankings, 0, 4);
    }
    
    return [
        'by_category' => $category_results,
        'combined_rankings_by_category' => $combined_rankings_by_category,
        'top_3_by_category' => $top_3_by_category,
        'statistics' => [
            'total_participants' => $total_participants,
            'categories_processed' => count($categories_to_process),
            'categories' => $categories_to_process,
            'has_results' => !empty($combined_rankings_by_category),
            'categories_with_rankings' => array_keys(array_filter($combined_rankings_by_category, function($rankings) {
                return !empty($rankings);
            })),
            'participant_count_by_category' => array_map(function($cat_result) {
                return $cat_result['participant_count'];
            }, $category_results)
        ]
    ];
}

try {
    $event_id = $_GET['event_id'] ?? '';
    
    if (!$event_id) {
        throw new Exception('Event ID is required');
    }
    
    // Load event data
    $event_stmt = $pdo->prepare("SELECT * FROM events WHERE id = ?");
    $event_stmt->execute([$event_id]);
    $event_data = $event_stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$event_data) {
        throw new Exception('Event not found');
    }
    
    $heats_total = intval($event_data['heats_total']);
    
    if ($heats_total == 0) {
        echo json_encode([
            'flow_chains' => [],
            'statistics' => [
                'total_heats' => 0,
                'flow_chains' => 0,
                'auto_flow_heats' => 0,
                'starting_heats' => 0,
                'total_participants' => 0,
                'active_heats' => 0
            ]
        ]);
        exit;
    }
    
    // Load event categories
    $categories_stmt = $pdo->prepare("
        SELECT id, category_name 
        FROM event_categories 
        WHERE event_id = ? AND is_main_category = 1 
        ORDER BY category_name
    ");
    $categories_stmt->execute([$event_id]);
    $event_categories = $categories_stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Get participant counts per heat
    $participant_counts_stmt = $pdo->prepare("
        SELECT heat_number, COUNT(*) as participant_count 
        FROM event_participants 
        WHERE event_id = ? 
        GROUP BY heat_number
    ");
    $participant_counts_stmt->execute([$event_id]);
    $heat_participant_counts = [];
    foreach ($participant_counts_stmt->fetchAll(PDO::FETCH_ASSOC) as $count_row) {
        $heat_participant_counts[$count_row['heat_number']] = $count_row['participant_count'];
    }
    
    // Get participants data for each heat with sort order
    $participants_stmt = $pdo->prepare("
        SELECT 
            ep.heat_number,
            ep.bib_number,
            ep.sort_order,
            p.first_name,
            p.last_name,
            p.name,
            ep.category
        FROM event_participants ep
        LEFT JOIN participants p ON ep.participant_id = p.id
        WHERE ep.event_id = ?
        ORDER BY ep.heat_number, ep.sort_order, ep.bib_number
    ");
    $participants_stmt->execute([$event_id]);
    $heat_participants = [];
    foreach ($participants_stmt->fetchAll(PDO::FETCH_ASSOC) as $participant) {
        $heat_num = $participant['heat_number'];
        if (!isset($heat_participants[$heat_num])) {
            $heat_participants[$heat_num] = [];
        }
        
        // Format participant name
        $display_name = '';
        if ($participant['first_name'] || $participant['last_name']) {
            $display_name = trim($participant['first_name'] . ' ' . $participant['last_name']);
        } else {
            $display_name = $participant['name'] ?? 'Unknown';
        }
        
        $heat_participants[$heat_num][] = [
            'bib_number' => $participant['bib_number'],
            'sort_order' => $participant['sort_order'],
            'name' => $display_name,
            'category' => $participant['category']
        ];
    }
    
    // Load heat settings with BIB information
    $settings_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, bib_on_start, bib_latest_on_run
        FROM event_heat_settings 
        WHERE event_id = ?
        ORDER BY heat_number
    ");
    $settings_stmt->execute([$event_id]);
    $heat_settings = [];
    foreach ($settings_stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
        $row['categories'] = json_decode($row['categories'] ?: '[]', true);
        $row['participant_count'] = $heat_participant_counts[$row['heat_number']] ?? 0;
        
        // Add BIB information and next participant
        $heat_num = $row['heat_number'];
        $participants_in_heat = $heat_participants[$heat_num] ?? [];
        
        // Current BIB information
        $row['bib_on_start'] = $row['bib_on_start'] ? intval($row['bib_on_start']) : null;
        $row['bib_latest_on_run'] = $row['bib_latest_on_run'] ? intval($row['bib_latest_on_run']) : null;
        
        // Find current participant on start
        $current_participant = null;
        $next_participant = null;
        
        if ($row['bib_on_start']) {
            foreach ($participants_in_heat as $participant) {
                if ($participant['bib_number'] == $row['bib_on_start']) {
                    $current_participant = $participant;
                    break;
                }
            }
        }
        
        // Find next participant based on sort_order
        if (!empty($participants_in_heat)) {
            if ($row['bib_on_start']) {
                // Find next participant after current one
                $current_sort_order = null;
                foreach ($participants_in_heat as $participant) {
                    if ($participant['bib_number'] == $row['bib_on_start']) {
                        $current_sort_order = $participant['sort_order'];
                        break;
                    }
                }
                
                if ($current_sort_order !== null) {
                    // Find participant with next sort order
                    $min_next_sort = null;
                    foreach ($participants_in_heat as $participant) {
                        if ($participant['sort_order'] > $current_sort_order) {
                            if ($min_next_sort === null || $participant['sort_order'] < $min_next_sort) {
                                $min_next_sort = $participant['sort_order'];
                                $next_participant = $participant;
                            }
                        }
                    }
                }
            } else {
                // No current participant, get first by sort order
                $min_sort = null;
                foreach ($participants_in_heat as $participant) {
                    if ($min_sort === null || $participant['sort_order'] < $min_sort) {
                        $min_sort = $participant['sort_order'];
                        $next_participant = $participant;
                    }
                }
            }
        }
        
        // Add participant information to heat settings
        $row['current_participant'] = $current_participant;
        $row['next_participant'] = $next_participant;
        $row['participants_list'] = $participants_in_heat;
        
        // Calculate progress information
        $total_participants = count($participants_in_heat);
        $completed_participants = 0;
        
        if ($row['bib_latest_on_run'] && $total_participants > 0) {
            // Count participants up to and including the latest run
            foreach ($participants_in_heat as $participant) {
                if ($participant['bib_number'] <= $row['bib_latest_on_run']) {
                    $completed_participants++;
                } else {
                    break; // Assuming BIB numbers are in order
                }
            }
        }
        
        $row['progress'] = [
            'total_participants' => $total_participants,
            'completed_participants' => $completed_participants,
            'completion_percentage' => $total_participants > 0 ? round(($completed_participants / $total_participants) * 100, 1) : 0
        ];
        
        $heat_settings[$row['heat_number']] = $row;
    }
    
    // Build flow chains with enhanced information
    $processed_heats = [];
    $flow_chains = [];
    
    for ($h = 1; $h <= $heats_total; $h++) {
        if (in_array($h, $processed_heats)) continue;
        
        $current_chain = [];
        $heat_to_process = $h;
        
        while ($heat_to_process && !in_array($heat_to_process, $processed_heats)) {
            $setting = $heat_settings[$heat_to_process] ?? [];
            
            // Get category names for display
            $heat_categories = $setting['categories'] ?? [];
            $category_names = [];
            if (empty($heat_categories)) {
                $category_names = ['All Categories'];
            } else {
                foreach ($event_categories as $cat) {
                    if (in_array($cat['id'], $heat_categories)) {
                        $category_names[] = $cat['category_name'];
                    }
                }
            }
            
            // Get summary results for this heat
            $summary_results = getHeatSummaryResults(
                $pdo,
                $event_id, 
                $heat_to_process, 
                $heat_categories,
                $event_categories,
                $setting['scoring_type'] ?? 'Points'
            );
            
            // Calculate enhanced progress with scoring data
            $progress_info = $setting['progress'] ?? [
                'total_participants' => 0,
                'completed_participants' => 0,
                'completion_percentage' => 0
            ];
            
            // Add scoring completion information
            if ($summary_results['statistics']['has_results']) {
                $progress_info['participants_with_scores'] = $summary_results['statistics']['total_participants'];
                $progress_info['scoring_completion_percentage'] = $progress_info['total_participants'] > 0 
                    ? round(($summary_results['statistics']['total_participants'] / $progress_info['total_participants']) * 100, 1)
                    : 0;
            } else {
                $progress_info['participants_with_scores'] = 0;
                $progress_info['scoring_completion_percentage'] = 0;
            }
            
            $current_chain[] = [
                'heat_number' => $heat_to_process,
                'heat_name' => $setting['heat_name'] ?? '',
                'flow_type' => $setting['flow_type'] ?? 'none',
                'flow_participants_per_category' => $setting['flow_participants_per_category'] ?? 0,
                'flow_source_heat' => $setting['flow_source_heat'] ?? null,
                'is_active' => (bool)($setting['is_active'] ?? false),
                'active_run' => $setting['active_run'] ?? 1,
                'categories' => $category_names,
                'participant_count' => $heat_participant_counts[$heat_to_process] ?? 0,
                'time_start' => $setting['time_start'] ?? '',
                'estimate_time_per_participant' => $setting['estimate_time_per_participant'] ?? 0,
                'scoring_type' => $setting['scoring_type'] ?? 'Points',
                'runs_count' => $setting['runs_count'] ?? 1,
                'runs_scoring_method' => $setting['runs_scoring_method'] ?? 'best_from_all',
                
                // Enhanced BIB and participant information
                'bib_on_start' => $setting['bib_on_start'] ?? null,
                'bib_latest_on_run' => $setting['bib_latest_on_run'] ?? null,
                'current_participant' => $setting['current_participant'] ?? null,
                'next_participant' => $setting['next_participant'] ?? null,
                'progress' => $progress_info,
                'participants_summary' => [
                    'total' => count($setting['participants_list'] ?? []),
                    'has_participants' => !empty($setting['participants_list'] ?? []),
                    'first_bib' => !empty($setting['participants_list'] ?? []) ? $setting['participants_list'][0]['bib_number'] : null,
                    'last_bib' => !empty($setting['participants_list'] ?? []) ? end($setting['participants_list'])['bib_number'] : null
                ],
                
                // NEW: Complete summary results grouped by categories
                'summary_results' => [
                    'by_category' => $summary_results['by_category'],
                    'combined_rankings_by_category' => $summary_results['combined_rankings_by_category'],
                    'top_3_by_category' => $summary_results['top_3_by_category'],
                    'statistics' => $summary_results['statistics'],
                    'has_results' => $summary_results['statistics']['has_results'],
                    'total_with_scores' => $summary_results['statistics']['total_participants'],
                    'categories_with_results' => array_keys(array_filter($summary_results['by_category'], function($cat_result) {
                        return $cat_result['success'] && $cat_result['participant_count'] > 0;
                    })),
                    'categories_with_rankings' => $summary_results['statistics']['categories_with_rankings'],
                    'participant_count_by_category' => $summary_results['statistics']['participant_count_by_category']
                ]
            ];
            
            $processed_heats[] = $heat_to_process;
            
            // Find next heat that flows from this one
            $next_heat = null;
            for ($next = $heat_to_process + 1; $next <= $heats_total; $next++) {
                $next_setting = $heat_settings[$next] ?? [];
                if (($next_setting['flow_source_heat'] ?? null) == $heat_to_process) {
                    $next_heat = $next;
                    break;
                }
            }
            
            $heat_to_process = $next_heat;
        }
        
        if (!empty($current_chain)) {
            $flow_chains[] = $current_chain;
        }
    }
    
    // Calculate enhanced statistics including summary data from all heats
    $total_participants = array_sum($heat_participant_counts);
    $auto_flow_count = 0;
    $active_heat_count = 0;
    $starting_heat_count = 0;
    $total_completed = 0;
    $heats_with_active_participants = 0;
    $total_participants_with_scores = 0;
    $heats_with_results = 0;
    $overall_highest_score = 0;
    $categories_with_results = [];
    
    foreach ($heat_settings as $h_num => $setting) {
        if (($setting['flow_type'] ?? 'none') !== 'none') {
            $auto_flow_count++;
        }
        
        if ($setting['is_active'] ?? false) {
            $active_heat_count++;
        }
        
        if (($setting['flow_type'] ?? 'none') === 'none') {
            // Check if any other heat flows from this one
            $has_outgoing = false;
            foreach ($heat_settings as $other_setting) {
                if (($other_setting['flow_source_heat'] ?? null) == $h_num) {
                    $has_outgoing = true;
                    break;
                }
            }
            if (!$has_outgoing) {
                $starting_heat_count++;
            }
        }
        
        // Count completed participants
        if (isset($setting['progress'])) {
            $total_completed += $setting['progress']['completed_participants'];
        }
        
        // Count heats with active participants (BIB on start)
        if ($setting['bib_on_start']) {
            $heats_with_active_participants++;
        }
    }
    
    // Collect summary statistics from flow chains
    foreach ($flow_chains as $chain) {
        foreach ($chain as $heat_info) {
            if ($heat_info['summary_results']['has_results']) {
                $heats_with_results++;
                $total_participants_with_scores += $heat_info['summary_results']['total_with_scores'];
                
                // Track categories with results
                $categories_with_results = array_merge(
                    $categories_with_results, 
                    $heat_info['summary_results']['categories_with_results']
                );
                
                // Find highest score across all categories and heats
                foreach ($heat_info['summary_results']['combined_rankings_by_category'] as $category => $rankings) {
                    foreach ($rankings as $ranking) {
                        if ($ranking['highest_score'] > $overall_highest_score) {
                            $overall_highest_score = $ranking['highest_score'];
                        }
                    }
                }
            }
        }
    }
    
    $categories_with_results = array_unique($categories_with_results);
    
    $response = [
        'event' => [
            'id' => $event_data['id'],
            'name' => $event_data['name'],
            'heats_total' => $heats_total,
            'date' => $event_data['date']
        ],
        'flow_chains' => $flow_chains,
        'statistics' => [
            // Basic heat statistics
            'total_heats' => $heats_total,
            'flow_chains' => count($flow_chains),
            'auto_flow_heats' => $auto_flow_count,
            'starting_heats' => $starting_heat_count,
            'total_participants' => $total_participants,
            'active_heats' => $active_heat_count,
            'completed_participants' => $total_completed,
            'heats_with_active_participants' => $heats_with_active_participants,
            'overall_completion_percentage' => $total_participants > 0 ? round(($total_completed / $total_participants) * 100, 1) : 0,
            
            // NEW: Scoring and results statistics
            'heats_with_results' => $heats_with_results,
            'total_participants_with_scores' => $total_participants_with_scores,
            'scoring_completion_percentage' => $total_participants > 0 ? round(($total_participants_with_scores / $total_participants) * 100, 1) : 0,
            'overall_highest_score' => $overall_highest_score,
            'categories_with_results' => $categories_with_results,
            'categories_with_results_count' => count($categories_with_results)
        ],
        'timestamp' => time()
    ];
    
    echo json_encode($response);
    
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode(['error' => $e->getMessage()]);
}
?>