<?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 '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;
            
        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
    ];
}
?>