<?php
// filepath: c:\stylescore2025\htdocs\v2\admin\heat_management_api.php
include '../includes/auth.php';
include '../includes/db.php';

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

try {
    $event_id = $_POST['event_id'] ?? $_GET['event_id'] ?? '';
    $action = $_POST['action'] ?? $_GET['action'] ?? '';
    
    if (!$event_id) {
        throw new Exception('Event ID is required');
    }
    
    switch ($action) {
        case 'get_data':
            echo json_encode(getHeatManagementData($pdo, $event_id));
            break;
            
        case 'get_heats':
            // Simple endpoint to get just the heats list
            echo json_encode(getHeats($pdo, $event_id));
            break;
            
        case 'update_settings':
            echo json_encode(updateHeatSettings($pdo, $event_id, $_POST));
            break;
            
        case 'update_heat_status':
            $heat_number = $_POST['heat_number'] ?? '';
            $status = $_POST['status'] ?? '';
            echo json_encode(updateHeatStatus($pdo, $event_id, $heat_number, $status));
            break;
            
        case 'get_participants':
            $heat_number = $_GET['heat_number'] ?? '';
            echo json_encode(getHeatParticipants($pdo, $event_id, $heat_number));
            break;
            
        case 'get_queue':
            $heat_number = $_GET['heat_number'] ?? '';
            $mode = $_GET['mode'] ?? 'start_list';
            echo json_encode(getParticipantQueue($pdo, $event_id, $heat_number, $mode));
            break;
            
        case 'update_participant_status':
            echo json_encode(updateParticipantStatus($pdo, $event_id, $_POST));
            break;
            
        case 'deactivate_all':
            echo json_encode(deactivateAllHeats($pdo, $event_id));
            break;
            
        case 'get_judge_status':
            $heat_number = $_GET['heat_number'] ?? '';
            $run_number = $_GET['run_number'] ?? 1;
            echo json_encode(getJudgeStatus($pdo, $event_id, $heat_number, $run_number));
            break;
            
        default:
            throw new Exception('Invalid action');
    }
    
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode(['error' => $e->getMessage()]);
}

function getHeatManagementData($pdo, $event_id) {
    // Get event info
    $event_stmt = $pdo->prepare("SELECT name, heats_total FROM events WHERE id = ?");
    $event_stmt->execute([$event_id]);
    $event = $event_stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$event) {
        throw new Exception('Event not found');
    }
    
    // Get heat settings - handle missing bib_performing column gracefully
    try {
        $heats_stmt = $pdo->prepare("
            SELECT heat_number, heat_name, runs_count, is_active, active_run, 
                   bib_on_start, bib_latest_on_run, bib_performing,
                   time_start, categories, scoring_type
            FROM event_heat_settings 
            WHERE event_id = ? 
            ORDER BY heat_number
        ");
        $heats_stmt->execute([$event_id]);
        $heats = $heats_stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        // Fallback if bib_performing column doesn't exist
        $heats_stmt = $pdo->prepare("
            SELECT heat_number, heat_name, runs_count, is_active, active_run, 
                   bib_on_start, bib_latest_on_run, NULL as bib_performing,
                   time_start, categories, scoring_type
            FROM event_heat_settings 
            WHERE event_id = ? 
            ORDER BY heat_number
        ");
        $heats_stmt->execute([$event_id]);
        $heats = $heats_stmt->fetchAll(PDO::FETCH_ASSOC);
    }
    
    // Get participant counts per heat
    $participant_counts_stmt = $pdo->prepare("
        SELECT heat_number, COUNT(*) as count 
        FROM event_participants 
        WHERE event_id = ? 
        GROUP BY heat_number
    ");
    $participant_counts_stmt->execute([$event_id]);
    $participant_counts = [];
    foreach ($participant_counts_stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
        $participant_counts[$row['heat_number']] = $row['count'];
    }
    
    // Process heats
    foreach ($heats as &$heat) {
        $heat['categories'] = json_decode($heat['categories'] ?: '[]', true);
        $heat['participant_count'] = $participant_counts[$heat['heat_number']] ?? 0;
        $heat['is_active'] = (bool)$heat['is_active'];
    }
    
    // Find current active heat
    $active_heat = null;
    foreach ($heats as $heat) {
        if ($heat['is_active']) {
            $active_heat = $heat;
            break;
        }
    }
    
    return [
        'event' => $event,
        'heats' => $heats,
        'active_heat' => $active_heat,
        'total_heats' => $event['heats_total']
    ];
}

function getHeats($pdo, $event_id) {
    // Simple function to get just the heats list
    try {
        $heats_stmt = $pdo->prepare("
            SELECT heat_number, heat_name, runs_count, is_active, active_run, 
                   time_start, categories, scoring_type
            FROM event_heat_settings 
            WHERE event_id = ? 
            ORDER BY heat_number
        ");
        $heats_stmt->execute([$event_id]);
        $heats = $heats_stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Process heats
        foreach ($heats as &$heat) {
            $heat['categories'] = json_decode($heat['categories'] ?: '[]', true);
            $heat['is_active'] = (bool)$heat['is_active'];
        }
        
        return [
            'success' => true,
            'heats' => $heats
        ];
    } catch (Exception $e) {
        return [
            'success' => false,
            'error' => $e->getMessage()
        ];
    }
}

function updateHeatSettings($pdo, $event_id, $data) {
    $active_heat = $data['active_heat'] ?? null;
    $active_run = intval($data['active_run'] ?? 1);
    $bib_on_start = $data['bib_on_start'] ?? null;
    $bib_latest_on_run = $data['bib_latest_on_run'] ?? null;
    $bib_performing = $data['bib_performing'] ?? null;
    
    // Start transaction
    $pdo->beginTransaction();
    
    try {
        // First, deactivate all heats
        $deactivate_stmt = $pdo->prepare("
            UPDATE event_heat_settings 
            SET is_active = 0 
            WHERE event_id = ?
        ");
        $deactivate_stmt->execute([$event_id]);
        
        if ($active_heat) {
            // Get current settings for the heat - handle missing bib_performing column
            try {
                $current_stmt = $pdo->prepare("
                    SELECT bib_on_start, bib_latest_on_run, bib_performing 
                    FROM event_heat_settings 
                    WHERE event_id = ? AND heat_number = ?
                ");
                $current_stmt->execute([$event_id, $active_heat]);
                $current = $current_stmt->fetch(PDO::FETCH_ASSOC);
            } catch (PDOException $e) {
                // Fallback if bib_performing column doesn't exist
                $current_stmt = $pdo->prepare("
                    SELECT bib_on_start, bib_latest_on_run, NULL as bib_performing 
                    FROM event_heat_settings 
                    WHERE event_id = ? AND heat_number = ?
                ");
                $current_stmt->execute([$event_id, $active_heat]);
                $current = $current_stmt->fetch(PDO::FETCH_ASSOC);
            }
            $current = $current_stmt->fetch(PDO::FETCH_ASSOC);
            
            // Handle BIB on start change
            $new_bib_latest = $bib_latest_on_run;
            if ($bib_on_start && $current && $current['bib_on_start'] && $current['bib_on_start'] != $bib_on_start) {
                // Previous BIB on start becomes latest on run
                $new_bib_latest = $current['bib_on_start'];
            }
            
            // Activate the selected heat and update settings
            try {
                $activate_stmt = $pdo->prepare("
                    UPDATE event_heat_settings 
                    SET is_active = 1, active_run = ?, bib_on_start = ?, bib_latest_on_run = ?, bib_performing = ?
                    WHERE event_id = ? AND heat_number = ?
                ");
                $activate_stmt->execute([
                    $active_run,
                    $bib_on_start ?: null,
                    $new_bib_latest ?: null,
                    $bib_performing ?: null,
                    $event_id,
                    $active_heat
                ]);
            } catch (PDOException $e) {
                // Fallback if bib_performing column doesn't exist
                $activate_stmt = $pdo->prepare("
                    UPDATE event_heat_settings 
                    SET is_active = 1, active_run = ?, bib_on_start = ?, bib_latest_on_run = ?
                    WHERE event_id = ? AND heat_number = ?
                ");
                $activate_stmt->execute([
                    $active_run,
                    $bib_on_start ?: null,
                    $new_bib_latest ?: null,
                    $event_id,
                    $active_heat
                ]);
            }
        }
        
        $pdo->commit();
        
        return [
            'success' => true,
            'message' => $active_heat ? "Heat $active_heat activated with Run $active_run" : 'All heats deactivated',
            'active_heat' => $active_heat,
            'active_run' => $active_run
        ];
        
    } catch (Exception $e) {
        $pdo->rollBack();
        throw $e;
    }
}

function getHeatParticipants($pdo, $event_id, $heat_number) {
    if (!$heat_number) {
        return ['participants' => []];
    }
    
    $participants_stmt = $pdo->prepare("
        SELECT 
            ep.id as event_participant_id,
            ep.bib_number,
            ep.heat_number,
            p.id as participant_id,
            p.name,
            p.first_name,
            p.last_name,
            p.country,
            p.date_of_birth,
            p.bib,
            p.gender,
            p.fis_code,
            p.licence_code,
            p.licence_type,
            p.club,
            p.category as participant_category,
            p.created_at,
            p.imported_at,
            p.updated_at,
            ep.category as event_category
        FROM event_participants ep
        LEFT JOIN participants p ON ep.participant_id = p.id
        WHERE ep.event_id = ? AND ep.heat_number = ?
        ORDER BY ep.sort_order
    ");
    $participants_stmt->execute([$event_id, $heat_number]);
    $participants = $participants_stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Get current heat settings
    $heat_stmt = $pdo->prepare("
        SELECT bib_on_start, bib_latest_on_run 
        FROM event_heat_settings 
        WHERE event_id = ? AND heat_number = ?
    ");
    $heat_stmt->execute([$event_id, $heat_number]);
    $heat_settings = $heat_stmt->fetch(PDO::FETCH_ASSOC);
    
    // Process participants data
    foreach ($participants as &$participant) {
        $bib = $participant['bib_number'];
        
        // Determine status based on heat settings
        if ($heat_settings['bib_on_start'] == $bib) {
            $participant['status'] = 'on_start';
        } elseif ($heat_settings['bib_latest_on_run'] == $bib) {
            $participant['status'] = 'latest_run';
        } else {
            $participant['status'] = 'waiting';
        }
        
        // Use the most appropriate name fields
        if (empty($participant['first_name']) && empty($participant['last_name'])) {
            // Fallback to name field if first/last names are empty
            $nameParts = explode(' ', $participant['name'] ?? '', 2);
            $participant['display_first_name'] = $nameParts[0] ?? '';
            $participant['display_last_name'] = $nameParts[1] ?? '';
        } else {
            $participant['display_first_name'] = $participant['first_name'] ?? '';
            $participant['display_last_name'] = $participant['last_name'] ?? '';
        }
        
        // Use event category if available, otherwise participant category
        $participant['display_category'] = $participant['event_category'] ?? $participant['participant_category'] ?? 'Unknown';
        
        // Format country display
        $participant['display_country'] = $participant['country'] ?? '';
        
        // Calculate age if date of birth is available
        if ($participant['date_of_birth']) {
            $dob = new DateTime($participant['date_of_birth']);
            $now = new DateTime();
            $participant['age'] = $dob->diff($now)->y;
        } else {
            $participant['age'] = null;
        }
        
        // Format license information
        $participant['license_info'] = '';
        if ($participant['licence_code']) {
            $participant['license_info'] = $participant['licence_code'];
            if ($participant['licence_type']) {
                $participant['license_info'] .= ' (' . $participant['licence_type'] . ')';
            }
        }
        
        // Clean up display fields
        $participant['display_club'] = $participant['club'] ?? '';
        $participant['display_fis_code'] = $participant['fis_code'] ?? '';
    }
    
    return [
        'participants' => $participants,
        'heat_settings' => $heat_settings
    ];
}

function deactivateAllHeats($pdo, $event_id) {
    $stmt = $pdo->prepare("
        UPDATE event_heat_settings 
        SET is_active = 0, bib_on_start = NULL 
        WHERE event_id = ?
    ");
    $stmt->execute([$event_id]);
    
    return [
        'success' => true,
        'message' => 'All heats deactivated'
    ];
}

function getParticipantQueue($pdo, $event_id, $heat_number, $mode = 'start_list') {
    if (!$heat_number) {
        return ['queue' => []];
    }
    
    // Get heat settings to determine current and latest participants
    $heat_stmt = $pdo->prepare("
        SELECT bib_on_start, bib_latest_on_run 
        FROM event_heat_settings 
        WHERE event_id = ? AND heat_number = ?
    ");
    $heat_stmt->execute([$event_id, $heat_number]);
    $heat_settings = $heat_stmt->fetch(PDO::FETCH_ASSOC);
    
    // Get participants for this heat
    $participants_stmt = $pdo->prepare("
        SELECT 
            ep.id as event_participant_id,
            ep.bib_number,
            ep.sort_order,
            p.first_name,
            p.last_name,
            p.name,
            p.country,
            p.club,
            ep.category as event_category,
            p.category as participant_category
        FROM event_participants ep
        LEFT JOIN participants p ON ep.participant_id = p.id
        WHERE ep.event_id = ? AND ep.heat_number = ?
        ORDER BY " . ($mode === 'start_list' ? 'ep.sort_order' : 'ep.bib_number') . "
    ");
    $participants_stmt->execute([$event_id, $heat_number]);
    $participants = $participants_stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Process participants and determine queue status
    $queue = [];
    $currentBib = $heat_settings['bib_on_start'] ?? null;
    $latestBib = $heat_settings['bib_latest_on_run'] ?? null;
    
    foreach ($participants as $participant) {
        $bib = $participant['bib_number'];
        
        // Set display names
        if (empty($participant['first_name']) && empty($participant['last_name'])) {
            $nameParts = explode(' ', $participant['name'] ?? '', 2);
            $participant['display_first_name'] = $nameParts[0] ?? '';
            $participant['display_last_name'] = $nameParts[1] ?? '';
        } else {
            $participant['display_first_name'] = $participant['first_name'] ?? '';
            $participant['display_last_name'] = $participant['last_name'] ?? '';
        }
        
        // Set display category
        $participant['display_category'] = $participant['event_category'] ?? $participant['participant_category'] ?? 'Unknown';
        $participant['display_country'] = $participant['country'] ?? '';
        $participant['display_club'] = $participant['club'] ?? '';
        
        // Determine status in queue
        if ($bib == $currentBib) {
            $participant['status'] = 'current';
            $participant['queue_position'] = 0;
        } elseif ($bib == $latestBib) {
            $participant['status'] = 'completed';
            $participant['queue_position'] = -1; // Completed participants go to end
        } else {
            $participant['status'] = 'waiting';
            $participant['queue_position'] = count($queue) + 1;
        }
        
        $queue[] = $participant;
    }
    
    // Sort queue: current first, then waiting in order, completed last
    usort($queue, function($a, $b) {
        if ($a['status'] === 'current') return -1;
        if ($b['status'] === 'current') return 1;
        if ($a['status'] === 'completed' && $b['status'] !== 'completed') return 1;
        if ($b['status'] === 'completed' && $a['status'] !== 'completed') return -1;
        return $a['sort_order'] - $b['sort_order'];
    });
    
    // Reassign queue positions after sorting
    foreach ($queue as $index => &$participant) {
        if ($participant['status'] === 'current') {
            $participant['queue_position'] = 0;
        } elseif ($participant['status'] === 'waiting') {
            $participant['queue_position'] = $index;
        }
    }
    
    // Set next participant status
    if (count($queue) > 1 && $queue[1]['status'] === 'waiting') {
        $queue[1]['status'] = 'next';
    }
    
    return [
        'queue' => $queue,
        'heat_settings' => $heat_settings,
        'mode' => $mode
    ];
}

function updateParticipantStatus($pdo, $event_id, $data) {
    $bib_number = $data['bib_number'] ?? null;
    $status = $data['status'] ?? null;
    
    if (!$bib_number || !$status) {
        throw new Exception('BIB number and status are required');
    }
    
    // Get the heat number for this participant
    $participant_stmt = $pdo->prepare("
        SELECT heat_number 
        FROM event_participants 
        WHERE event_id = ? AND bib_number = ?
        LIMIT 1
    ");
    $participant_stmt->execute([$event_id, $bib_number]);
    $participant = $participant_stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$participant) {
        throw new Exception('Participant not found');
    }
    
    $heat_number = $participant['heat_number'];
    
    // Update heat settings based on status
    switch ($status) {
        case 'started':
            $stmt = $pdo->prepare("
                UPDATE event_heat_settings 
                SET bib_on_start = ? 
                WHERE event_id = ? AND heat_number = ?
            ");
            $stmt->execute([$bib_number, $event_id, $heat_number]);
            $message = "Participant $bib_number marked as started";
            break;
            
        case 'completed':
            $stmt = $pdo->prepare("
                UPDATE event_heat_settings 
                SET bib_latest_on_run = ? 
                WHERE event_id = ? AND heat_number = ?
            ");
            $stmt->execute([$bib_number, $event_id, $heat_number]);
            $message = "Participant $bib_number marked as completed";
            break;
            
        default:
            throw new Exception('Invalid status');
    }
    
    return [
        'success' => true,
        'message' => $message,
        'bib_number' => $bib_number,
        'status' => $status
    ];
}

function updateHeatStatus($pdo, $event_id, $heat_number, $status) {
    if (!$heat_number) {
        return [
            'success' => false,
            'message' => 'Heat number is required'
        ];
    }
    
    $valid_statuses = ['pending', 'active', 'finished', 'cancelled', 'rescheduled'];
    if (!in_array($status, $valid_statuses)) {
        return [
            'success' => false,
            'message' => 'Invalid status. Must be one of: ' . implode(', ', $valid_statuses)
        ];
    }
    
    try {
        // If setting to active, deactivate all other heats first
        if ($status === 'active') {
            $deactivate_stmt = $pdo->prepare("
                UPDATE event_heat_settings 
                SET is_active = 0, status = 'pending'
                WHERE event_id = ? AND heat_number != ?
            ");
            $deactivate_stmt->execute([$event_id, $heat_number]);
            
            // Set this heat as active
            $update_stmt = $pdo->prepare("
                UPDATE event_heat_settings 
                SET is_active = 1, status = ?
                WHERE event_id = ? AND heat_number = ?
            ");
            $update_stmt->execute([$status, $event_id, $heat_number]);
        } else {
            // For non-active statuses, just update status and set is_active to 0
            $update_stmt = $pdo->prepare("
                UPDATE event_heat_settings 
                SET status = ?, is_active = 0
                WHERE event_id = ? AND heat_number = ?
            ");
            $update_stmt->execute([$status, $event_id, $heat_number]);
        }
        
        return [
            'success' => true,
            'message' => "Heat $heat_number status updated to $status",
            'heat_number' => $heat_number,
            'status' => $status
        ];
        
    } catch (Exception $e) {
        return [
            'success' => false,
            'message' => 'Database error: ' . $e->getMessage()
        ];
    }
}

function getJudgeStatus($pdo, $event_id, $heat_number, $run_number) {
    if (!$heat_number) {
        return [
            'success' => false,
            'message' => 'No active heat'
        ];
    }
    
    // Get judges assigned to this event
    $judges_stmt = $pdo->prepare("
        SELECT 
            ej.id,
            ej.judge_id,
            ej.panel_number,
            ej.judge_role,
            u.name as judge_name,
            u.email as judge_email
        FROM event_judges ej
        LEFT JOIN users u ON ej.judge_id = u.id
        WHERE ej.event_id = ?
        ORDER BY ej.panel_number, ej.judge_role
    ");
    $judges_stmt->execute([$event_id]);
    $judges = $judges_stmt->fetchAll(PDO::FETCH_ASSOC);
    
    if (empty($judges)) {
        return [
            'success' => true,
            'judges' => [],
            'heat_number' => $heat_number,
            'run_number' => $run_number,
            'total_participants' => 0,
            'average_progress' => 0
        ];
    }
    
    // Get total participants in this heat
    $participants_stmt = $pdo->prepare("
        SELECT COUNT(*) as total
        FROM event_participants
        WHERE event_id = ? AND heat_number = ?
    ");
    $participants_stmt->execute([$event_id, $heat_number]);
    $total_participants = $participants_stmt->fetchColumn();
    
    // For each judge, get their scoring status
    $judge_status = [];
    foreach ($judges as $judge) {
        // Count scores submitted by this judge for this heat/run
        $scores_stmt = $pdo->prepare("
            SELECT 
                COUNT(*) as scores_count,
                MAX(created_at) as last_score_time
            FROM scoring_results sr
            JOIN event_participants ep ON sr.participant_id = ep.id
            WHERE ep.event_id = ?
                AND ep.heat_number = ?
                AND sr.run_number = ?
                AND sr.judge_id = ?
        ");
        $scores_stmt->execute([$event_id, $heat_number, $run_number, $judge['judge_id']]);
        $score_data = $scores_stmt->fetch(PDO::FETCH_ASSOC);
        
        // Check if judge is online (has activity in last 5 minutes)
        $is_online = false;
        if ($score_data['last_score_time']) {
            $last_activity = strtotime($score_data['last_score_time']);
            $five_minutes_ago = time() - (5 * 60);
            $is_online = $last_activity > $five_minutes_ago;
        }
        
        $judge_status[] = [
            'judge_id' => $judge['judge_id'],
            'judge_name' => $judge['judge_name'] ?: 'Judge #' . $judge['judge_id'],
            'judge_email' => $judge['judge_email'],
            'panel_number' => $judge['panel_number'],
            'judge_role' => $judge['judge_role'],
            'scores_submitted' => (int)$score_data['scores_count'],
            'last_score_time' => $score_data['last_score_time'],
            'is_online' => $is_online,
            'progress_percent' => $total_participants > 0 
                ? round(($score_data['scores_count'] / $total_participants) * 100, 1) 
                : 0
        ];
    }
    
    // Calculate average progress
    $total_progress = array_sum(array_column($judge_status, 'progress_percent'));
    $average_progress = count($judge_status) > 0 ? $total_progress / count($judge_status) : 0;
    
    return [
        'success' => true,
        'judges' => $judge_status,
        'heat_number' => $heat_number,
        'run_number' => $run_number,
        'total_participants' => (int)$total_participants,
        'average_progress' => round($average_progress, 1)
    ];
}
?>