<?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;
$ep_ids = $_POST['event_participant_ids'] ?? [];
$action_type = $_POST['action_type'] ?? 'move'; // 'move' or 'copy'

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

try {
    $pdo->beginTransaction();

    // Validate that all event_participant IDs belong to the specified event
    $placeholders = implode(',', array_fill(0, count($ep_ids), '?'));
    $validate_stmt = $pdo->prepare("
        SELECT COUNT(*) 
        FROM event_participants 
        WHERE id IN ($placeholders) AND event_id = ?
    ");
    $validate_stmt->execute(array_merge($ep_ids, [$event_id]));
    
    if ($validate_stmt->fetchColumn() != count($ep_ids)) {
        throw new Exception('Some participants do not belong to this event.');
    }

    if ($action_type === 'move') {
        // Move: Update heat numbers for selected participants
        $update_stmt = $pdo->prepare("
            UPDATE event_participants 
            SET heat_number = ? 
            WHERE id IN ($placeholders) AND event_id = ?
        ");
        $update_stmt->execute(array_merge([$target_heat], $ep_ids, [$event_id]));
        $affected_rows = $update_stmt->rowCount();
        $message = "Successfully moved {$affected_rows} participants to Heat {$target_heat}.";
        
    } else { // 'copy'
        // Copy: Create new records for the target heat
        $select_stmt = $pdo->prepare("
            SELECT participant_id, bib_number, category_id, category
            FROM event_participants 
            WHERE id IN ($placeholders) AND event_id = ?
        ");
        $select_stmt->execute(array_merge($ep_ids, [$event_id]));
        $participants_data = $select_stmt->fetchAll(PDO::FETCH_ASSOC);
        
        $insert_stmt = $pdo->prepare("
            INSERT INTO event_participants (event_id, participant_id, heat_number, bib_number, category_id, category) 
            VALUES (?, ?, ?, ?, ?, ?)
        ");
        
        $copied_count = 0;
        foreach ($participants_data as $participant) {
            // 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, $participant['participant_id'], $target_heat]);
            
            if ($exists_stmt->fetchColumn() == 0) {
                $insert_stmt->execute([
                    $event_id,
                    $participant['participant_id'],
                    $target_heat,
                    $participant['bib_number'],
                    $participant['category_id'],
                    $participant['category']
                ]);
                $copied_count++;
            }
        }
        
        $message = "Successfully copied {$copied_count} participants to Heat {$target_heat}.";
        if ($copied_count < count($participants_data)) {
            $message .= " " . (count($participants_data) - $copied_count) . " participants were already in the target heat.";
        }
    }
    
    $pdo->commit();
    
    echo json_encode([
        'status' => 'success', 
        'message' => $message
    ]);

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