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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $event_id = $_POST['event_id'] ?? null;
    $bib_assignments = $_POST['bib_assign'] ?? [];

    if (!$event_id || empty($bib_assignments)) {
        die('Invalid submission.');
    }

    try {
        $pdo->beginTransaction();
        
        $updated_count = 0;
        $conflicts = [];
        
        foreach ($bib_assignments as $participant_id => $bib_number) {
            // Skip empty values
            if (empty($bib_number) || !is_numeric($bib_number)) {
                // Clear BIB number if empty
                $stmt = $pdo->prepare("UPDATE event_participants SET bib_number = NULL WHERE event_id = ? AND participant_id = ?");
                $stmt->execute([$event_id, $participant_id]);
                continue;
            }

            // Check for conflicts with other participants in the same event
            $stmt = $pdo->prepare("
                SELECT p.first_name, p.last_name, ep.participant_id
                FROM event_participants ep 
                JOIN participants p ON ep.participant_id = p.id 
                WHERE ep.event_id = ? AND ep.bib_number = ? AND ep.participant_id != ?
                LIMIT 1
            ");
            $stmt->execute([$event_id, $bib_number, $participant_id]);
            $conflict = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($conflict) {
                $conflicts[] = "BIB $bib_number is already assigned to {$conflict['first_name']} {$conflict['last_name']} (different participant)";
                continue;
            }

            // Update the BIB number for ALL heats of this participant in this event
            $stmt = $pdo->prepare("UPDATE event_participants SET bib_number = ? WHERE event_id = ? AND participant_id = ?");
            $stmt->execute([$bib_number, $event_id, $participant_id]);
            
            if ($stmt->rowCount() > 0) {
                $updated_count++;
            }
        }
        
        $pdo->commit();
        
        // Prepare success message
        $message = "Successfully updated $updated_count BIB assignments.";
        if (!empty($conflicts)) {
            $message .= " However, there were conflicts: " . implode(', ', $conflicts);
        }
        
        // Redirect with success message
        header("Location: bib_distribute.php?event_id=" . $event_id . "&success=" . urlencode($message));
        exit;
        
    } catch (Exception $e) {
        $pdo->rollBack();
        header("Location: bib_distribute.php?event_id=" . $event_id . "&error=" . urlencode("Database error: " . $e->getMessage()));
        exit;
    }
}
?>
