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

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

$event_id = $_POST['event_id'] ?? null;
$target_heat = $_POST['target_heat'] ?? null;
$source_heat = $_POST['source_heat'] ?? null;
$promotion_count = $_POST['promotion_count'] ?? 3; // Default to top 3
$category = $_POST['category'] ?? null;

if (!$event_id || !$target_heat) {
    echo json_encode(['status' => 'error', 'message' => 'Missing required parameters: event_id and target_heat.']);
    exit;
}

try {
    $pdo->beginTransaction();

    // If no source heat specified, find heats that can promote to the target heat
    if (!$source_heat) {
        // Get heats that have flow configuration pointing to target heat
        $flow_stmt = $pdo->prepare("
            SELECT DISTINCT h.heat_number, h.heat_name
            FROM heats h 
            WHERE h.event_id = ? 
            AND h.flow_target_heat = ?
            AND h.flow_type IN ('promotion', 'qualifying')
            ORDER BY h.heat_number
        ");
        $flow_stmt->execute([$event_id, $target_heat]);
        $source_heats = $flow_stmt->fetchAll(PDO::FETCH_ASSOC);
        
        if (empty($source_heats)) {
            throw new Exception('No source heats configured to promote to Heat ' . $target_heat);
        }
    } else {
        $source_heats = [['heat_number' => $source_heat]];
    }

    $total_promoted = 0;
    $promotion_details = [];

    foreach ($source_heats as $heat_info) {
        $current_source_heat = $heat_info['heat_number'];
        
        // Get heat configuration for promotion rules
        $heat_config_stmt = $pdo->prepare("
            SELECT flow_participants_per_category, flow_type 
            FROM heats 
            WHERE event_id = ? AND heat_number = ?
        ");
        $heat_config_stmt->execute([$event_id, $current_source_heat]);
        $heat_config = $heat_config_stmt->fetch(PDO::FETCH_ASSOC);
        
        $participants_per_category = $heat_config['flow_participants_per_category'] ?? $promotion_count;
        
        // Get categories in the source heat
        $categories_stmt = $pdo->prepare("
            SELECT DISTINCT category 
            FROM event_participants 
            WHERE event_id = ? AND heat_number = ? AND category IS NOT NULL
            ORDER BY category
        ");
        $categories_stmt->execute([$event_id, $current_source_heat]);
        $categories = $categories_stmt->fetchAll(PDO::FETCH_COLUMN);
        
        if (empty($categories)) {
            $promotion_details[] = "Heat {$current_source_heat}: No participants with categories found";
            continue;
        }

        $heat_promoted = 0;
        
        foreach ($categories as $cat) {
            // Skip if specific category filter is set and doesn't match
            if ($category && $category !== $cat) {
                continue;
            }
            
            // Get top performers for this category in this heat
            // This is a simplified version - you may need to adjust based on your scoring system
            $top_performers_stmt = $pdo->prepare("
                SELECT ep.id, ep.participant_id, ep.bib_number, ep.category,
                       p.name as participant_name,
                       COALESCE(AVG(s.score), 0) as avg_score,
                       COUNT(s.score) as score_count
                FROM event_participants ep
                LEFT JOIN participants p ON ep.participant_id = p.id
                LEFT JOIN scores s ON ep.id = s.event_participant_id
                WHERE ep.event_id = ? AND ep.heat_number = ? AND ep.category = ?
                GROUP BY ep.id
                HAVING score_count > 0
                ORDER BY avg_score DESC
                LIMIT ?
            ");
            $top_performers_stmt->execute([$event_id, $current_source_heat, $cat, $participants_per_category]);
            $top_performers = $top_performers_stmt->fetchAll(PDO::FETCH_ASSOC);
            
            foreach ($top_performers as $performer) {
                // Check if participant already exists in target heat
                $exists_stmt = $pdo->prepare("
                    SELECT COUNT(*) FROM event_participants 
                    WHERE event_id = ? AND participant_id = ? AND heat_number = ?
                ");
                $exists_stmt->execute([$event_id, $performer['participant_id'], $target_heat]);
                
                if ($exists_stmt->fetchColumn() == 0) {
                    // Promote by creating new entry in target heat
                    $promote_stmt = $pdo->prepare("
                        INSERT INTO event_participants (event_id, participant_id, heat_number, bib_number, category_id, category) 
                        SELECT event_id, participant_id, ?, bib_number, category_id, category
                        FROM event_participants 
                        WHERE id = ?
                    ");
                    $promote_stmt->execute([$target_heat, $performer['id']]);
                    $heat_promoted++;
                    $total_promoted++;
                }
            }
            
            $promotion_details[] = "Category {$cat}: Promoted " . count($top_performers) . " participants from Heat {$current_source_heat}";
        }
    }
    
    $pdo->commit();
    
    if ($total_promoted > 0) {
        $message = "Successfully promoted {$total_promoted} participants to Heat {$target_heat}.";
        if (!empty($promotion_details)) {
            $message .= "\n\nDetails:\n" . implode("\n", $promotion_details);
        }
        
        echo json_encode([
            'status' => 'success', 
            'message' => $message,
            'promoted_count' => $total_promoted,
            'details' => $promotion_details
        ]);
    } else {
        echo json_encode([
            'status' => 'warning', 
            'message' => 'No participants were promoted. This could be because:\n- No qualifying scores found\n- Participants already exist in target heat\n- No promotion rules configured',
            'promoted_count' => 0
        ]);
    }

} catch (Exception $e) {
    $pdo->rollBack();
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
?>
