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

$event_id = $_POST['event_id'] ?? null;
$series_id = $_POST['bib_series_id'] ?? null;
$ep_ids = $_POST['participant_ids'] ?? [];
$start_number = $_POST['start_number'] ?? null;
$overwrite_existing = $_POST['overwrite_existing'] ?? 0;

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

// Fetch BIB series
$stmt = $pdo->prepare("SELECT * FROM bib_series WHERE id = ? AND event_id = ?");
$stmt->execute([$series_id, $event_id]);
$series = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$series) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid BIB series.']);
    exit;
}

// Build list of available BIBs
$missing = array_filter(array_map('trim', explode(',', $series['missing_numbers'] ?? '')), 'is_numeric');
$additional = array_filter(array_map('trim', explode(',', $series['additional_numbers'] ?? '')), 'is_numeric');

$range = range($series['start_number'], $series['end_number']);
$all_bibs = array_unique(array_merge($range, $additional));
$available_bibs = array_values(array_diff($all_bibs, $missing));

// Filter out used BIBs (unless overwriting)
if (!$overwrite_existing) {
    $stmt = $pdo->prepare("SELECT DISTINCT bib_number FROM event_participants WHERE event_id = ? AND bib_number IS NOT NULL AND bib_number != ''");
    $stmt->execute([$event_id]);
    $used_bibs = $stmt->fetchAll(PDO::FETCH_COLUMN);
    $available_bibs = array_values(array_diff($available_bibs, $used_bibs));
}

// Apply custom start number if provided
if ($start_number && is_numeric($start_number)) {
    $available_bibs = array_filter($available_bibs, function($bib) use ($start_number) {
        return $bib >= $start_number;
    });
    $available_bibs = array_values($available_bibs);
}

if (count($available_bibs) < count($ep_ids)) {
    echo json_encode(['status' => 'error', 'message' => 'Not enough BIB numbers available.']);
    exit;
}

// Get participant IDs ordered by sort_order
$placeholders = implode(',', array_fill(0, count($ep_ids), '?'));
$where_clause = $overwrite_existing ? "" : "AND (bib_number IS NULL OR bib_number = '')";
$query = "SELECT id, participant_id FROM event_participants WHERE id IN ($placeholders) AND event_id = ? $where_clause ORDER BY sort_order ASC";
$stmt = $pdo->prepare($query);
$stmt->execute(array_merge($ep_ids, [$event_id]));
$participants_to_assign = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Assign BIBs
$stmt_update = $pdo->prepare("UPDATE event_participants SET bib_number = ? WHERE id = ?");

foreach ($participants_to_assign as $i => $participant) {
    if (isset($available_bibs[$i])) {
        $bib = $available_bibs[$i];
        $stmt_update->execute([$bib, $participant['id']]);
    }
}

echo json_encode(['status' => 'success', 'message' => 'BIBs assigned successfully.']);
?>