<?php
// API endpoint for generating heat cards HTML
header('Content-Type: application/json');
error_reporting(E_ALL);
ini_set('display_errors', 1);

include '../includes/auth.php';
include '../includes/db.php';

$response = ['success' => false, 'data' => '', 'message' => ''];

try {
    $event_id = $_GET['event_id'] ?? null;
    
    if (!$event_id) {
        throw new Exception('Event ID is required');
    }
    
    // Load event data
    $event_stmt = $pdo->prepare("
        SELECT e.*, sf.name as format_name, sf.sport as discipline, sf.mode as format_mode,
               sfj.scale_min, sfj.scale_max, sfj.scale_type, sfj.precision_decimal
        FROM events e
        LEFT JOIN scoring_formats sf ON e.scoring_format = sf.format_id
        LEFT JOIN scoring_format_judges sfj ON sf.format_id = sfj.format_id
        WHERE e.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']);
    
    // 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'];
    }
    
    // Load heat settings
    $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, flow_position_range, is_active, active_run, status,
               format_name, discipline, difficulty_level, course_length, time_limit,
               weather_dependent, format_description, scoring_method, required_figures,
               judges_required, scale_min, scale_max, precision_decimal
        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['required_figures'] = json_decode($row['required_figures'] ?: '[]', true);
        $row['participant_count'] = $heat_participant_counts[$row['heat_number']] ?? 0;
        $heat_settings[$row['heat_number']] = $row;
    }
    
    // Build heat order (same logic as original)
    $heat_order = [];
    $processed_for_order = [];
    
    // First, add all starting heats
    for ($h = 1; $h <= $heats_total; $h++) {
        $setting = $heat_settings[$h] ?? [];
        $has_incoming = false;
        
        foreach ($heat_settings as $other_setting) {
            if (!empty($other_setting['flow_source_heat'])) {
                $source_heats = array_map('trim', explode(',', $other_setting['flow_source_heat']));
                if (in_array((string)$h, $source_heats, true)) {
                    $has_incoming = true;
                    break;
                }
            }
        }
        
        if (($setting['flow_type'] ?? 'none') === 'none' && !$has_incoming) {
            $heat_order[] = $h;
            $processed_for_order[] = $h;
        }
    }
    
    // Then add heats with flow connections
    $remaining_iterations = $heats_total;
    while (count($processed_for_order) < $heats_total && $remaining_iterations > 0) {
        for ($h = 1; $h <= $heats_total; $h++) {
            if (in_array($h, $processed_for_order)) continue;
            
            $setting = $heat_settings[$h] ?? [];
            if (!empty($setting['flow_source_heat'])) {
                $source_heats = array_map('trim', explode(',', $setting['flow_source_heat']));
                $all_sources_processed = true;
                foreach ($source_heats as $source_h) {
                    if (!in_array((int)$source_h, $processed_for_order)) {
                        $all_sources_processed = false;
                        break;
                    }
                }
                if ($all_sources_processed) {
                    $heat_order[] = $h;
                    $processed_for_order[] = $h;
                }
            }
        }
        $remaining_iterations--;
    }
    
    // Add remaining heats
    for ($h = 1; $h <= $heats_total; $h++) {
        if (!in_array($h, $processed_for_order)) {
            $heat_order[] = $h;
        }
    }
    
    // Generate HTML for all heat cards
    ob_start();
    
    foreach ($heat_order as $h) {
        $setting = $heat_settings[$h] ?? [
            'heat_name' => '', 
            'scoring_type' => 'Points',
            'runs_count' => 1,
            'runs_scoring_method' => 'best_from_all',
            'time_start' => '',
            'estimate_time_per_participant' => 0,
            'categories' => [],
            'flow_type' => 'none',
            'flow_source_heat' => null,
            'flow_participants_per_category' => 0,
            'flow_position_range' => null,
            'is_active' => 0,
            'active_run' => 1,
            'status' => 'pending',
            'format_name' => $event_data['format_name'] ?? '',
            'discipline' => $event_data['discipline'] ?? '',
            'difficulty_level' => '',
            'course_length' => 0,
            'time_limit' => 0,
            'weather_dependent' => 0,
            'format_description' => '',
            'scoring_method' => 'standard',
            'required_figures' => [],
            'judges_required' => 5,
            'scale_min' => $event_data['scale_min'] ?? 0,
            'scale_max' => $event_data['scale_max'] ?? 100,
            'precision_decimal' => $event_data['precision_decimal'] ?? 0
        ];
        
        $total_participants = $heat_participant_counts[$h] ?? 0;
        $participants_with_scores = 0;
        $approved_participants = 0;
        
        if ($total_participants > 0) {
            $progress_stmt = $pdo->prepare("
                SELECT 
                    COUNT(DISTINCT ep.participant_id) as total_participants,
                    COUNT(DISTINCT CASE WHEN s.id IS NOT NULL THEN ep.participant_id END) as participants_with_scores,
                    COUNT(DISTINCT CASE WHEN s.is_approved = 1 THEN ep.participant_id END) as approved_participants
                FROM event_participants ep
                LEFT JOIN runs r ON r.event_participant_id = ep.id
                LEFT JOIN scores s ON s.run_id = r.id
                WHERE ep.event_id = ? AND ep.heat_number = ?
            ");
            $progress_stmt->execute([$event_id, $h]);
            $progress_data = $progress_stmt->fetch(PDO::FETCH_ASSOC);
            
            $participants_with_scores = $progress_data['participants_with_scores'] ?? 0;
            $approved_participants = $progress_data['approved_participants'] ?? 0;
        }
        
        $progress_percentage = $total_participants > 0 ? round(($approved_participants / $total_participants) * 100, 1) : 0;
        $scoring_percentage = $total_participants > 0 ? round(($participants_with_scores / $total_participants) * 100, 1) : 0;
        $progress_variant = $progress_percentage >= 100 ? 'success' : ($progress_percentage >= 50 ? 'warning' : 'primary');
        ?>
        
        <div class="col-md-4 col-lg-3 mb-3">
            <div class="card h-100 shadow-sm  <?= $setting['status'] === 'active' ? 'border-2 border-success' : '' ?> <?= $setting['status'] === 'finished' ? 'border-2 border-info' : '' ?> <?= $setting['status'] === 'cancelled' ? 'border-2 border-danger' : '' ?> <?= $setting['status'] === 'rescheduled' ? 'border-2 border-warning' : '' ?>" style="overflow: hidden;">
                <!-- Header Section -->
                <div class="card-header <?= $setting['status'] === 'active' ? 'bg-success text-white' : ($setting['status'] === 'finished' ? 'bg-info text-white' : ($setting['status'] === 'cancelled' ? 'bg-danger text-white' : ($setting['status'] === 'rescheduled' ? 'bg-warning text-dark' : 'bg-light'))) ?> border-0 p-3">
                    <div class="d-flex justify-content-between align-items-start">
                        <div class="flex-grow-1">
                            <h5 class="mb-1 fw-bold">
                                <i class="fas fa-fire me-2 <?= $setting['status'] === 'active' ? 'text-warning' : 'text-muted' ?>"></i>
                                Heat <?= $h ?>
                            </h5>
                            <p class="mb-0 fw-bold <?= $setting['status'] === 'active' ? 'text-white-100' : 'text-muted' ?>">
                                <?= !empty($setting['heat_name']) ? htmlspecialchars($setting['heat_name']) : 'Unnamed Heat' ?>
                            </p>
                        </div>
                        <!-- Quick Stats -->
                    <div class="row g-2 me-3">
                        <div class="col-6">
                            <div class="text-center p-2 bg-light bg-opacity-25 rounded d-flex flex-row align-items-center justify-content-center gap-2" title="Athletes">
                                <i class="fas fa-users text-primary mb-1"></i>
                                <div class="fw-bold"><?= $total_participants ?></div>
                                
                            </div>
                        </div>
                        <div class="col-6">
                            <div class="text-center p-2 bg-light bg-opacity-25 rounded d-flex flex-row align-items-center justify-content-center gap-2" title="Runs">
                                <i class="fas fa-redo text-info mb-1"></i>
                                <div class="fw-bold"><?= $setting['runs_count'] ?></div>
                               
                            </div>
                        </div>
                    </div>
                        <div class="d-flex flex-column gap-1 align-items-end">
                            <?php if ($setting['status'] === 'active'): ?>
                                <span class="badge bg-warning text-dark">
                                    <i class="fas fa-bolt me-1"></i>ACTIVE
                                </span>
                            <?php elseif ($setting['status'] === 'finished'): ?>
                                <span class="badge bg-info">
                                    <i class="fas fa-check-circle me-1"></i>FINISHED
                                </span>
                            <?php elseif ($setting['status'] === 'cancelled'): ?>
                                <span class="badge bg-danger">
                                    <i class="fas fa-ban me-1"></i>CANCELLED
                                </span>
                            <?php elseif ($setting['status'] === 'rescheduled'): ?>
                                <span class="badge bg-warning text-dark">
                                    <i class="fas fa-clock me-1"></i>RESCHEDULED
                                </span>
                            <?php else: ?>
                                <span class="badge bg-secondary">
                                    <i class="fas fa-pause me-1"></i>PENDING
                                </span>
                            <?php endif; ?>
                            <?php if ($setting['flow_type'] !== 'none'): ?>
                                <span class="badge bg-primary">
                                    <i class="fas fa-arrow-up me-1"></i>FLOW
                                </span>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                
                <div class="card-body p-3 pb-0">
                    
                    
                    <?php if ($setting['status'] === 'active'): ?>
                        <!-- Active Run Control -->
                        <div class="alert alert-success mb-3 py-2">
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <small class="fw-bold"><i class="fas fa-play-circle me-1"></i>Current Run</small>
                                <span class="badge bg-success"><?= $setting['active_run'] ?>/<?= $setting['runs_count'] ?></span>
                            </div>
                            <div class="d-flex gap-1">
                                <button type="button" class="btn btn-sm btn-outline-success flex-grow-1" 
                                        onclick="changeActiveRun(<?= $h ?>, -1)"
                                        <?= $setting['active_run'] <= 1 ? 'disabled' : '' ?>
                                        title="Previous Run">
                                    <i class="fas fa-chevron-left"></i> Prev
                                </button>
                                <button type="button" class="btn btn-sm btn-outline-success flex-grow-1" 
                                        onclick="changeActiveRun(<?= $h ?>, 1)"
                                        <?= $setting['active_run'] >= $setting['runs_count'] ? 'disabled' : '' ?>
                                        title="Next Run">
                                    Next <i class="fas fa-chevron-right"></i>
                                </button>
                            </div>
                        </div>
                    <?php endif; ?>
                    
                    <?php if ($total_participants > 0): ?>
                        <!-- Time Display -->
                        <?php if (!empty($setting['time_start'])): ?>
                            <?php
                            $time_per_participant = $setting['estimate_time_per_participant'] ?? 0;
                            $duration_minutes = 0;
                            $planned_end_time = '';
                            
                            if ($time_per_participant > 0 && $total_participants > 0) {
                                $total_seconds = $time_per_participant * $total_participants;
                                $duration_minutes = ceil($total_seconds / 60);
                                
                                $start_time_obj = new DateTime($setting['time_start']);
                                $planned_end_time_obj = clone $start_time_obj;
                                $planned_end_time_obj->modify("+{$duration_minutes} minutes");
                                $planned_end_time = $planned_end_time_obj->format('H:i');
                            }
                            ?>
                            <div class="border-bottom pb-2">
                                <small class="fw-bold text-primary d-block mb-2">
                                    <i class="fas fa-clock me-1"></i>Schedule
                                </small>
                                <div class="small d-flex flex-row gap-2 w-100 justify-content-between">
                                    <div class="d-flex justify-content-between mb-1 gap-2">
                                        <span class="text-muted">Start</span>
                                        <span class="fw-bold"><?= $setting['time_start'] ?></span>
                                    </div>
                                    <?php if ($planned_end_time): ?>
                                        <div class="d-flex justify-content-between mb-1  gap-2"">
                                            <span class="text-muted">End</span>
                                            <span class="fw-bold"><?= $planned_end_time ?></span>
                                        </div>
                                        <div class="d-flex justify-content-between  gap-2"">
                                            <span class="text-muted">Duration</span>
                                            <span class="fw-bold"><?= $duration_minutes ?>min</span>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        <?php endif; ?>
                        <!-- Progress Section -->
                        <div class="mt-3">
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <small class="fw-bold text-secondary">
                                    <i class="fas fa-chart-line me-1"></i>Scoring Progress
                                </small>
                                <span class="badge bg-<?= $progress_variant ?>"><?= $progress_percentage ?>%</span>
                            </div>
                            <div class="progress mb-2" style="height: 10px;">
                                <div class="progress-bar bg-<?= $progress_variant ?>" 
                                     role="progressbar" 
                                     style="width: <?= $progress_percentage ?>%" 
                                     aria-valuenow="<?= $progress_percentage ?>" 
                                     aria-valuemin="0" 
                                     aria-valuemax="100">
                                </div>
                            </div>
                            <div class="d-flex justify-content-between small text-muted">
                                <span><i class="fas fa-check-circle me-1"></i><?= $approved_participants ?> approved</span>
                                <span><i class="fas fa-pen me-1"></i><?= $participants_with_scores ?> scored</span>
                            </div>
                        </div>
                        
                        
                    <?php endif; ?>
                </div>
                
                <!-- Action Buttons -->
                <div class="card-footer bg-white border-0 p-3">
                    <div class="d-grid gap-2">
                        <?php if ($setting['status'] === 'pending'): ?>
                            <!-- Pending: Can Activate, Cancel, or Reschedule -->
                            <button type="button" class="btn btn-success btn-sm" onclick="activateHeat(<?= $h ?>)">
                                <i class="fas fa-play me-1"></i>Activate Heat
                            </button>
                            <div class="btn-group" role="group">
                                <button type="button" class="btn btn-outline-danger btn-sm" onclick="cancelHeat(<?= $h ?>)">
                                    <i class="fas fa-ban me-1"></i>Cancel
                                </button>
                                <button type="button" class="btn btn-outline-warning btn-sm" onclick="rescheduleHeat(<?= $h ?>)">
                                    <i class="fas fa-clock me-1"></i>Reschedule
                                </button>
                            </div>
                        <?php elseif ($setting['status'] === 'active'): ?>
                            <!-- Active: Can Finish, Set Pending, Cancel, or Reschedule -->
                            <div class="btn-group" role="group">
                                <button type="button" class="btn btn-primary btn-sm" onclick="closeHeat(<?= $h ?>)">
                                    <i class="fas fa-check me-1"></i>Finish
                                </button>
                                <button type="button" class="btn btn-secondary btn-sm" onclick="setPendingHeat(<?= $h ?>)">
                                    <i class="fas fa-pause me-1"></i>Pending
                                </button>
                            </div>
                            <div class="btn-group" role="group">
                                <button type="button" class="btn btn-outline-danger btn-sm" onclick="cancelHeat(<?= $h ?>)">
                                    <i class="fas fa-ban me-1"></i>Cancel
                                </button>
                                <button type="button" class="btn btn-outline-warning btn-sm" onclick="rescheduleHeat(<?= $h ?>)">
                                    <i class="fas fa-clock me-1"></i>Reschedule
                                </button>
                            </div>
                        <?php elseif ($setting['status'] === 'finished'): ?>
                            <!-- Finished: Can Reactivate or Set Pending -->
                            <div class="btn-group" role="group">
                                <button type="button" class="btn btn-success btn-sm" onclick="activateHeat(<?= $h ?>)">
                                    <i class="fas fa-redo me-1"></i>Reactivate
                                </button>
                                <button type="button" class="btn btn-secondary btn-sm" onclick="setPendingHeat(<?= $h ?>)">
                                    <i class="fas fa-pause me-1"></i>Set Pending
                                </button>
                            </div>
                        <?php elseif ($setting['status'] === 'cancelled'): ?>
                            <!-- Cancelled: Can Activate, Reschedule, or Set Pending -->
                            <button type="button" class="btn btn-success btn-sm" onclick="activateHeat(<?= $h ?>)">
                                <i class="fas fa-play me-1"></i>Activate Heat
                            </button>
                            <div class="btn-group" role="group">
                                <button type="button" class="btn btn-outline-warning btn-sm" onclick="rescheduleHeat(<?= $h ?>)">
                                    <i class="fas fa-clock me-1"></i>Reschedule
                                </button>
                                <button type="button" class="btn btn-outline-secondary btn-sm" onclick="setPendingHeat(<?= $h ?>)">
                                    <i class="fas fa-pause me-1"></i>Set Pending
                                </button>
                            </div>
                        <?php elseif ($setting['status'] === 'rescheduled'): ?>
                            <!-- Rescheduled: Can Activate, Reschedule, or Set Pending -->
                            <button type="button" class="btn btn-success btn-sm" onclick="activateHeat(<?= $h ?>)">
                                <i class="fas fa-play me-1"></i>Activate Heat
                            </button>
                            <div class="btn-group" role="group">
                                <button type="button" class="btn btn-outline-danger btn-sm" onclick="cancelHeat(<?= $h ?>)">
                                    <i class="fas fa-ban me-1"></i>Cancel
                                </button>
                                <button type="button" class="btn btn-outline-secondary btn-sm" onclick="setPendingHeat(<?= $h ?>)">
                                    <i class="fas fa-pause me-1"></i>Set Pending
                                </button>
                            </div>
                        <?php endif; ?>
                        <div class="btn-group" role="group">
                            <button type="button" class="btn btn-outline-primary btn-sm" onclick="openHeatModal(<?= $h ?>)">
                                <i class="fas fa-cog me-1"></i>Config
                            </button>
                            <button type="button" class="btn btn-outline-info btn-sm" onclick="showHeatResults(<?= $h ?>)">
                                <i class="fas fa-trophy me-1"></i>Results
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <?php
    }
    
    $html = ob_get_clean();
    
    $response['success'] = true;
    $response['data'] = $html;
    $response['heat_count'] = count($heat_order);
    $response['timestamp'] = date('Y-m-d H:i:s');
    
} catch (Exception $e) {
    $response['message'] = $e->getMessage();
}

echo json_encode($response);
