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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $event_id = intval($_POST['event_id'] ?? 0);
    $heat_number = intval($_POST['heat_number'] ?? 0);
    $participant_ids = $_POST['participant_ids'] ?? [];

    $assigned = 0;
    foreach ($participant_ids as $participant_id) {
        $participant_id = intval($participant_id);

        // Prevent duplicate BIB in same heat/event
        $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]);
            $assigned++;
        }
    }
    echo json_encode(['status' => 'success','message' => "$assigned participant(s) assigned to heat $heat_number."]);
    exit;
}
http_response_code(400);
echo json_encode(['status' => 'error', 'message' => 'Invalid request']);