<?php
session_start();
include '../includes/auth_admin.php';
include '../includes/db.php';

$data = json_decode(file_get_contents('php://input'), true);
$event_id = $data['event_id'];
$heat_number = $data['heat_number'];
$participant_ids = $data['participant_ids'] ?? [];

$response = ['added' => 0, 'skipped' => 0, 'message' => ''];

foreach ($participant_ids as $participant_id) {
    if (!$participant_id) continue;

    $bib_check = $pdo->prepare("
        SELECT COUNT(*) FROM event_participants ep
        JOIN participants p ON ep.participant_id = p.id
        WHERE ep.event_id = ? AND ep.heat_number = ? AND p.bib = (
            SELECT bib FROM participants WHERE id = ?
        )
    ");
    $bib_check->execute([$event_id, $heat_number, $participant_id]);
    if ($bib_check->fetchColumn() == 0) {
        $stmt = $pdo->prepare("INSERT INTO event_participants (event_id, participant_id, heat_number) VALUES (?, ?, ?)");
        $stmt->execute([$event_id, $participant_id, $heat_number]);
        $response['added']++;
    } else {
        $response['skipped']++;
    }
}
$response['message'] = "✅ {$response['added']} added, 🔒 {$response['skipped']} skipped.";
echo json_encode($response);
?>
