<?php
include '../includes/auth.php';
include '../includes/db.php';
///
// https://sortablejs.github.io/Sortable/
///
// Define selected_event first
$selected_event = $_GET['event_id'] ?? null;

// Fetch event list
$events = $pdo->query("SELECT id, name FROM events")->fetchAll(PDO::FETCH_ASSOC);

// Fetch filters - get categories from event_participants for selected event
$categories = [];
$genders = $pdo->query("SELECT DISTINCT gender FROM participants ORDER BY gender")->fetchAll(PDO::FETCH_COLUMN);
$clubs = $pdo->query("SELECT DISTINCT club FROM participants ORDER BY club")->fetchAll(PDO::FETCH_COLUMN);
$years = $pdo->query("SELECT DISTINCT YEAR(date_of_birth) as year FROM participants ORDER BY year DESC")->fetchAll(PDO::FETCH_COLUMN);

// Get categories specific to the selected event from event_participants
if ($selected_event) {
    $categories_stmt = $pdo->prepare("SELECT DISTINCT category FROM event_participants WHERE event_id = ? AND category IS NOT NULL ORDER BY category");
    $categories_stmt->execute([$selected_event]);
    $categories = $categories_stmt->fetchAll(PDO::FETCH_COLUMN);
}

// Load participants - show those assigned to event but not in any heat
if ($selected_event) {
$stmt = $pdo->prepare("
    SELECT DISTINCT p.id, p.bib, p.first_name, p.last_name, p.club, p.gender, p.date_of_birth,
           COALESCE(ep_cat.category, p.category) as category,
           0 as assignment_count,
           NULL as assigned_heats
    FROM participants p
    INNER JOIN participants_event pe ON p.id = pe.participant_id AND pe.event_id = ?
    LEFT JOIN event_participants ep ON p.id = ep.participant_id AND ep.event_id = ?
    LEFT JOIN event_participants ep_cat ON p.id = ep_cat.participant_id AND ep_cat.event_id = ? AND ep_cat.category IS NOT NULL
    WHERE ep.id IS NULL
    ORDER BY p.bib ASC
");
$stmt->execute([$selected_event, $selected_event, $selected_event]);
    $participants = $stmt->fetchAll(PDO::FETCH_ASSOC);
} else {
    // If no event selected, show all participants with their base category
    $participants = $pdo->query("SELECT id, bib, first_name, last_name, club, category, gender, date_of_birth, 0 as assignment_count, NULL as assigned_heats FROM participants ORDER BY first_name ASC")->fetchAll(PDO::FETCH_ASSOC);
}

// Assign logic
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['assign_participants'])) {
    $event_id = $_POST['event_id'];
    $heat_number = $_POST['heat_number'];
    $participants_to_assign = $_POST['participant_ids'] ?? [];

    foreach ($participants_to_assign 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]);
        }
    }
}

// Delete single
if (isset($_GET['delete_id'])) {
    // Get participant_id and event_id before deleting
    $stmt = $pdo->prepare("SELECT participant_id, event_id FROM event_participants WHERE id = ?");
    $stmt->execute([(int)$_GET['delete_id']]);
    $assignment = $stmt->fetch();
    
    if ($assignment) {
        // Delete from event_participants
        $pdo->prepare("DELETE FROM event_participants WHERE id = ?")->execute([(int)$_GET['delete_id']]);
        
        // Also remove from participants_event
       // $pdo->prepare("DELETE FROM participants_event WHERE participant_id = ? AND event_id = ?")->execute([
       //     $assignment['participant_id'], 
       //     $assignment['event_id']
       // ]);
    }
    
    header("Location: heats_configure.php?event_id=" . (int)$_GET['event_id']);
    exit;
}

// Bulk delete
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['bulk_delete'])) {
    $ids = $_POST['delete_ids'] ?? [];
    if ($ids) {
        // Get all participant_id and event_id pairs before deleting
        $placeholders = implode(',', array_fill(0, count($ids), '?'));
        $stmt = $pdo->prepare("SELECT participant_id, event_id FROM event_participants WHERE id IN ($placeholders)");
        $stmt->execute($ids);
        $assignments = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Delete from event_participants
        $in = implode(',', array_fill(0, count($ids), '?'));
        $pdo->prepare("DELETE FROM event_participants WHERE id IN ($in)")->execute($ids);
        
        // Also remove from participants_event for each assignment
        //foreach ($assignments as $assignment) {
        //    $pdo->prepare("DELETE FROM participants_event WHERE participant_id = ? AND event_id = ?")->execute([
        //        $assignment['participant_id'], 
        //        $assignment['event_id']
        //    ]);
        //}
    }
    header("Location: heats_configure.php?event_id=" . (int)$_GET['event_id']);
    exit;
}

// Auto assign
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['auto_assign'])) {
    $event_id = $_GET['event_id'];
    $heat_number = $_POST['auto_heat'];
    $ids = explode(',', $_POST['filtered_ids']);
    foreach ($ids as $participant_id) {
        $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]);
        }
    }
    header("Location: heats_configure.php?event_id=" . $event_id);
    exit;
}

// Current assignments
$assignments = [];
$selected_event = $_GET['event_id'] ?? null;
$heat_filter = $_GET['heat_filter'] ?? null;
// Current assignments - get bib from event_participants.bib_number
if ($selected_event) {
    $query = "
        SELECT ep.id, ep.heat_number, ep.bib_number as bib, ep.category, 
               p.first_name, p.last_name, p.club, p.gender, p.date_of_birth, p.id as participant_id
        FROM event_participants ep
        JOIN participants p ON ep.participant_id = p.id
        WHERE ep.event_id = ?
    ";
    
    if ($heat_filter) {
        $query .= " AND ep.heat_number = ? ORDER BY ep.sort_order ASC, ep.bib_number ASC";
        $stmt = $pdo->prepare($query);
        $stmt->execute([$selected_event, $heat_filter]);
    } else {
        $query .= " ORDER BY ep.sort_order ASC, ep.bib_number ASC";
        $stmt = $pdo->prepare($query);
        $stmt->execute([$selected_event]);
    }
    $assignments = $stmt->fetchAll(PDO::FETCH_ASSOC);
}



    // Get bib series
    $stmt = $pdo->prepare("SELECT * FROM bib_series WHERE event_id = ? ORDER BY id ASC");
    $stmt->execute([$selected_event]);
    $bib_series = $stmt->fetchAll(PDO::FETCH_ASSOC);

?>
<!DOCTYPE html>
<html>
<head>
    <title>Configure Heats</title>
    <?php include_once '../includes/stylesheets.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>
    

<script>
    function collectFiltered() {
        let visible = Array.from(document.querySelectorAll('#participantSelect option'))
            .filter(opt => opt.style.display !== 'none')
            .map(opt => opt.value);
        document.getElementById('autoFilteredIDs').value = visible.join(',');
    }
    </script>
</head>
<body class="body-bg-aurora-bright">
    <?php include '../menu.php'; ?>
<div class="container-fluid p-2 container-StyleScore">
    <!-- event action menu. -->
    <div class="row mb-2">
        <div class="col-12 d-flex flex-row align-items-center gap-3">
            <?php       
            $use_localStorage = true;
            $show_header = false;
            //$show_public_view = false;
            include 'event_actions_menu.php'; 
            ?>
             <form method="get" class="card border mb-2 load-event-selection">
                <div class="border-0 shadow-none card-body p-2">
                    <div class="row align-items-center">
                        <div class="col-md-2">
                            <label class="form-label small fw-bold mb-0">Event:</label>
                        </div>
                        <div class="col-md-10">
                            <select name="event_id" class="form-select form-select-sm" onchange="this.form.submit()" required>
                                <option value="">-- Choose Event --</option>
                                <?php foreach ($events as $event): ?>
                                    <option value="<?= $event['id'] ?>" <?= $selected_event == $event['id'] ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($event['name']) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                </div>
            </form>
            <h4 class="mb-2">Assign Participants to Heats</h4>
        </div>
    </div>
        
   

      <?php if ($selected_event): ?>
        <?php if ($selected_event): ?>
        <div class="row">    
        <!-- Assignment Form -->
        <div class="col-6 p-4">
            <div class="border-0 shadow-none card-header bg-light py-2">
                <h6 class="mb-0">
                    <i class="fas fa-user-plus me-1 text-success"></i>Assign Participants to Heat
                </h6>
                <small class="text-muted">Select a heat and participants to assign them quickly</small>
            </div>
            <div class="border-0 shadow-none card-body p-2">
                <form method="post" id="ajaxAssignForm" data-event="<?= $selected_event ?>">
                    <input type="hidden" name="event_id" value="<?= $selected_event ?>">
                    <input type="hidden" name="assign_participants" value="1">
                    
                    <div class="row g-2">
                        
                        
                        <!-- Filters Section -->
                        <div class="col-lg-12 w-100">
                            
                            
                            <div class="row g-1 mb-2">
                                <div class="col-md-9">
                                    <label class="form-label small fw-bold me-auto">
                                <i class="fas fa-filter me-1 text-info"></i>Filter Participants
                            </label>
                                    <div class="row g-1 mb-2">
                                        <div class="col-md-4">
                                            <select id="categoryFilter" class="form-select form-select-sm" onchange="filterParticipants()">
                                                <option value="">All Categories</option>
                                                <?php 
                                                // Get categories from participants available for assignment
                                                $available_categories = array_unique(array_filter(array_column($participants, 'category')));
                                                sort($available_categories);
                                                foreach ($available_categories as $c): ?>
                                                    <option value="<?= htmlspecialchars($c) ?>"><?= htmlspecialchars($c) ?></option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                        <div class="col-md-2">
                                            <select id="genderFilter" class="form-select form-select-sm" onchange="filterParticipants()">
                                                <option value="">All Genders</option>
                                                <?php foreach ($genders as $g): ?>
                                                    <option value="<?= htmlspecialchars($g) ?>"><?= htmlspecialchars($g) ?></option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                        <div class="col-md-4">
                                            <select id="clubFilter" class="form-select form-select-sm" onchange="filterParticipants()">
                                                <option value="">All Clubs</option>
                                                <?php foreach ($clubs as $c): ?>
                                                    <option value="<?= htmlspecialchars($c) ?>"><?= htmlspecialchars($c) ?></option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                        <div class="col-md-2">
                                            <select id="yearFilter" class="form-select form-select-sm" onchange="filterParticipants()">
                                                <option value="">All Years</option>
                                                <?php 
                                                // Get years from participants data instead of database query
                                                $participantYears = array_unique(array_filter(array_map(function($p) {
                                                    return $p['date_of_birth'] ? date('Y', strtotime($p['date_of_birth'])) : null;
                                                }, $participants)));
                                                rsort($participantYears);
                                                
                                                foreach ($participantYears as $y): ?>
                                                    <option value="<?= $y ?>"><?= $y ?></option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-3">
                       <label for="heat_number" class="form-label small fw-bold ms-auto" title="Choose the target heat for assignment">
                                    <i class="fas fa-fire me-1 text-primary"></i>Heat Selection
                            </label>
                                    <!-- Heat Selection -->
                                    <div class="col-md-12">
                                        
                                        <?php
                                        // Fetch heats for selected event
                                        $heat_options = [];
                                        if ($selected_event) {
                                            $stmt = $pdo->prepare("SELECT heat_number, heat_name FROM event_heat_settings WHERE event_id = ? ORDER BY heat_number ASC");
                                            $stmt->execute([$selected_event]);
                                            $heat_options = $stmt->fetchAll(PDO::FETCH_ASSOC);
                                        }
                                        ?>
                                        <select name="heat_number" id="heat_number" class="form-select form-select-sm" required>
                                            <option value="">-- Select Heat --</option>
                                            <?php foreach ($heat_options as $heat): ?>
                                                <option value="<?= $heat['heat_number'] ?>">
                                                    Heat <?= $heat['heat_number'] ?><?= $heat['heat_name'] ? ' – ' . htmlspecialchars($heat['heat_name']) : '' ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                        
                                    </div>
                                    <!-- Action Buttons -->
                                    <div class="col-md-12">
                                        
                                        <div class="d-flex gap-1">
                                            <button type="button" class="btn btn-outline-secondary btn-sm" onclick="clearAllFilters()">
                                                <i class="fas fa-undo"></i>
                                            </button>
                                            <button type="button" id="ajaxAssignBtn" class="btn btn-success btn-sm">
                                                <i class="fas fa-user-plus me-1"></i>Assign
                                            </button>
                                        </div>
                                    </div>
                                                
                                 </div>
                            </div>
                            
                            <!-- Participant Selection -->
                            <div class="participant-selection-wrapper">
                                <div class="d-flex justify-content-between align-items-center mb-1">
                                    <label class="form-label small fw-bold mb-0">
                                        <i class="fas fa-users me-1 text-warning"></i>Available Participants
                                        <span id="participantStatusBadge" class="badge bg-info ms-1">0 selected</span>
                                        <small class="text-muted ms-2" style="font-weight: normal;">
                                            <i class="fas fa-hand-pointer text-primary"></i> Drag to Assigned section below
                                        </small>
                                    </label>
                                    <div class="d-flex gap-1">
                                        <div class="btn-group btn-group-sm">
                                            <button type="button" class="btn btn-outline-primary btn-sm" onclick="selectAllVisible()">
                                                <i class="fas fa-check-double"></i>
                                            </button>
                                            <button type="button" class="btn btn-outline-secondary btn-sm" onclick="clearSelection()">
                                                <i class="fas fa-times"></i>
                                            </button>
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- Search Bar -->
                                <div class="mb-2">
                                    <div class="input-group input-group-sm">
                                        <span class="input-group-text">
                                            <i class="fas fa-search"></i>
                                        </span>
                                        <input type="text" id="participantSearch" class="form-control" placeholder="Search by name, bib, or club..." onkeyup="searchParticipants()">
                                        <button class="btn btn-outline-secondary" type="button" onclick="clearSearch()">
                                            <i class="fas fa-times"></i>
                                        </button>
                                    </div>
                                </div>
                                
                                <!-- Hidden select for form submission -->
                                <select name="participant_ids[]" id="participantSelect" multiple style="display: none;">
                                    <?php foreach ($participants as $p): ?>
                                        <option value="<?= $p['id'] ?>" 
                                                data-category="<?= htmlspecialchars($p['category'] ?? '') ?>" 
                                                data-gender="<?= htmlspecialchars($p['gender'] ?? '') ?>" 
                                                data-club="<?= htmlspecialchars($p['club'] ?? '') ?>" 
                                                data-date_of_birth="<?= $p['date_of_birth'] ?? '' ?>"
                                                data-year="<?= $p['date_of_birth'] ? date('Y', strtotime($p['date_of_birth'])) : '' ?>"
                                                data-assigned="<?= $p['assignment_count'] ?>"
                                                data-heats="<?= htmlspecialchars($p['assigned_heats'] ?? '') ?>">
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                
                                <!-- Participant Display Container -->
                                <div class="participant-display-container">
                                    <div class="table-responsive">
                                        <table class="table table-hover table-sm" id="participantsTable">
                                            <thead class="table-light">
                                                <tr>
                                                    <th width="40">
                                                        <input type="checkbox" id="selectAllParticipants" class="form-check-input">
                                                    </th>
                                                    <th width="60">BIB</th>
                                                    <th>Name</th>
                                                    <!-- Club column hidden -->
                                                    <th>Category</th>
                                                    <th width="80">Gender</th>
                                                    <th width="80">Year</th>
                                                    <th width="100">Status</th>
                                                    <th width="80">Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if (empty($participants)): ?>
                                                    <tr>
                                                        <td colspan="8" class="text-center text-muted py-4">
                                                            <i class="fas fa-users fa-3x mb-3 opacity-50"></i>
                                                            <p class="mb-0">No participants available for assignment</p>
                                                            <small class="text-muted">All participants may already be assigned to heats</small>
                                                        </td>
                                                    </tr>
                                                <?php else: ?>
                                                    <?php foreach ($participants as $p): ?>
                                                        <tr class="participant-row" 
                                                            data-id="<?= $p['id'] ?>"
                                                            data-category="<?= htmlspecialchars($p['category'] ?? '') ?>" 
                                                            data-gender="<?= htmlspecialchars($p['gender'] ?? '') ?>" 
                                                            data-club="<?= htmlspecialchars($p['club'] ?? '') ?>" 
                                                            data-date_of_birth="<?= $p['date_of_birth'] ?? '' ?>"
                                                            data-year="<?= $p['date_of_birth'] ? date('Y', strtotime($p['date_of_birth'])) : '' ?>"
                                                            data-assigned="<?= $p['assignment_count'] ?>"
                                                            data-heats="<?= htmlspecialchars($p['assigned_heats'] ?? '') ?>"
                                                            data-search-text="<?= strtolower($p['last_name'] . ' ' . $p['first_name'] . ' ' . $p['bib'] . ' ' . ($p['club'] ?? '')) ?>"
                                                            onclick="toggleTableRowSelection(this)">
                                                            
                                                            <td>
                                                                <input type="checkbox" class="form-check-input participant-checkbox" value="<?= $p['id'] ?>" onclick="event.stopPropagation()">
                                                            </td>
                                                            <td class="css-bib">
                                                            <span class="badge bg-secondary"><?= htmlspecialchars($p['bib']) ?></span>
                                                            </td>
                                                            <td>
                                                                <div class="fw-bold"><?= htmlspecialchars($p['last_name'] . ' ' . $p['first_name']) ?></div>
                                                                <small class="text-muted">ID: <?= $p['id'] ?></small>
                                                            </td>
                                                            <!-- Club column hidden -->
                                                            <td>
                                                                <span class="badge bg-info"><?= htmlspecialchars($p['category'] ?? 'No Category') ?></span>
                                                            </td>
                                                            <td>
                                                                <span class="badge bg-<?= $p['gender'] === 'M' ? 'primary' : 'danger' ?>">
                                                                    <i class="fas fa-<?= $p['gender'] === 'M' ? 'male' : 'female' ?> me-1"></i>
                                                                    <?= htmlspecialchars($p['gender'] ?? '') ?>
                                                                </span>
                                                            </td>
                                                            <td>
                                                                <span class="badge_p">
                                                                    <?= $p['date_of_birth'] ? date('Y', strtotime($p['date_of_birth'])) : '-' ?>
                                                                </span>
                                                            </td>
                                                            <td>
                                                                <?php if ($p['assignment_count'] > 0): ?>
                                                                    <span class="badge bg-warning">
                                                                        <i class="fas fa-fire me-1"></i>
                                                                        Heat <?= $p['assigned_heats'] ?>
                                                                    </span>
                                                                <?php else: ?>
                                                                    <span class="badge bg-success">
                                                                        <i class="fas fa-circle me-1"></i>
                                                                        Available
                                                                    </span>
                                                                <?php endif; ?>
                                                            </td>
                                                            <td>
                                                                <div class="btn-group btn-group-sm">
                                                                    <a href="participant_edit.php?id=<?= $p['id'] ?>" class="btn btn-outline-primary btn-sm" title="Edit Participant">
                                                                        <i class="fas fa-edit"></i>
                                                                    </a>
                                                                </div>
                                                            </td>
                                                        </tr>
                                                    <?php endforeach; ?>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                    
                                    <!-- No Results Message -->
                                    <div id="noParticipantsMessage" class="no-participants-message" style="display: none;">
                                        <div class="text-center py-5">
                                            <i class="fas fa-search fa-3x text-muted mb-3"></i>
                                            <h5 class="text-muted">No participants found</h5>
                                            <p class="text-muted">Try adjusting your search or filter criteria</p>
                                            <button type="button" class="btn btn-outline-primary" onclick="clearAllFiltersAndSearch()">
                                                <i class="fas fa-refresh me-1"></i>Clear All Filters
                                            </button>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="participant-select-footer">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <div class="form-text small">
                                            <span id="participantCount"><?= count($participants) ?></span> participants available • Click to select
                                        </div>
                                        <div class="selection-summary text-end">
                                            <small class="text-muted">
                                                <span id="visibleCount"><?= count($participants) ?></span> visible • <span id="selectedCount">0</span> selected
                                            </small>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                </form>
            </div>
        </div>
                                    
                                  
                            <?php endif; ?>

                            <div class="col-6 p-4">
                                <div class="border-0 shadow-none card-header bg-light py-2 justify-content-between align-items-center">
                                    <h6 class="mb-0">
                                        <i class="fas fa-fire me-1"></i>Heat Assignments (<?= count($assignments) ?> participants)
                                    </h6>
                                  <small class="text-muted">Select a heat and participants to assign them quickly</small>
                                    
                                </div>
                                <div class="border-0 shadow-none card-body p-0">
                                     <label class="form-label small fw-bold">
                                <i class="fas fa-filter me-1 text-info"></i>Filter Participants
                            </label>
                                    <!-- Dynamic Filters -->
                                    <div class="p-2 bg-light border-bottom">
                                        <div class="row g-1">
                                            <div class="col-md-2">
                                                <select id="filterHeat" class="form-select form-select-sm" onchange="filterReorderTable()">
                                                    <option value="">All Heats</option>
                                                    <?php
                                                    if ($selected_event) {
                                                        $stmt = $pdo->prepare("SELECT heat_number, heat_name FROM event_heat_settings WHERE event_id = ? ORDER BY heat_number ASC");
                                                        $stmt->execute([$selected_event]);
                                                        foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $heat) {
                                                            echo '<option value="' . $heat['heat_number'] . '">' . $heat['heat_number'] . ($heat['heat_name'] ? ' – ' . htmlspecialchars($heat['heat_name']) : '') . '</option>';
                                                        }
                                                    }
                                                    ?>
                                                </select>
                                            </div>
                                            <div class="col-md-2">
                                                <select id="filterCategory" class="form-select form-select-sm" onchange="filterReorderTable()">
                                                    <option value="">All Categories</option>
                                                    <option value="No Category">No Category</option>
                                                    <?php 
                                                    // Get categories from current assignments
                                                    $assignment_categories = array_unique(array_filter(array_column($assignments, 'category')));
                                                    sort($assignment_categories);
                                                    foreach ($assignment_categories as $c): ?>
                                                        <option value="<?= htmlspecialchars($c) ?>"><?= htmlspecialchars($c) ?></option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                            <div class="col-md-2">
                                                <select id="filterClub" class="form-select form-select-sm" onchange="filterReorderTable()">
                                                    <option value="">All Clubs</option>
                                                    <?php foreach ($clubs as $c): ?>
                                                        <option value="<?= $c ?>"><?= $c ?></option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                            <div class="col-md-2">
                                                <select id="filterGender" class="form-select form-select-sm" onchange="filterReorderTable()">
                                                    <option value="">All Genders</option>
                                                    <?php foreach ($genders as $g): ?>
                                                        <option value="<?= $g ?>"><?= $g ?></option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                            <div class="col-md-2">
                                                <select id="filterYear" class="form-select form-select-sm" onchange="filterReorderTable()">
                                                    <option value="">All Years</option>
                                                    <optgroup label="Single Years">
                                                        <?php foreach ($years as $y): ?>
                                                            <option value="<?= $y ?>"><?= $y ?></option>
                                                        <?php endforeach; ?>
                                                    </optgroup>
                                                    <optgroup label="Year Ranges">
                                                        <option value="2010-2015">2010-2015</option>
                                                        <option value="2016-2020">2016-2020</option>
                                                        <option value="2021-2025">2021-2025</option>
                                                        <option value="before-2010">Before 2010</option>
                                                        <option value="after-2020">After 2020</option>
                                                    </optgroup>
                                                    <optgroup label="Age Groups">
                                                        <?php
                                                        $currentYear = date('Y');
                                                        $ageGroups = [
                                                            'under-18' => 'Under 18 (' . ($currentYear - 17) . '+)',
                                                            'under-21' => 'Under 21 (' . ($currentYear - 20) . '+)', 
                                                            'under-25' => 'Under 25 (' . ($currentYear - 24) . '+)',
                                                            'over-30' => 'Over 30 (' . ($currentYear - 30) . '-)',
                                                            'over-40' => 'Over 40 (' . ($currentYear - 40) . '-)',
                                                            'over-50' => 'Over 50 (' . ($currentYear - 50) . '-)'
                                                        ];
                                                        foreach ($ageGroups as $value => $label): ?>
                                                            <option value="<?= $value ?>"><?= $label ?></option>
                                                        <?php endforeach; ?>
                                                    </optgroup>
                                                </select>
                                            </div>
                                            <div class="col-md-2 d-flex align-items-end">
                                                <button type="button" class="btn btn-outline-secondary btn-sm w-100" onclick="clearFilters()">
                                                    <i class="fas fa-times me-1"></i>Clear
                                                </button>
                                            </div>
                                        </div>
                                    </div>

                                        <!-- Action Buttons -->
                                    <div class="p-3 border-bottom bg-white">
                                        <div class="d-flex flex-wrap gap-1 align-items-center">
                                            <button type="button" id="reverseSelectedBtn" class="btn btn-outline-secondary btn-sm">
                                                <i class="fas fa-exchange-alt me-1"></i>Reverse Selected
                                            </button>
                                            <button type="button" id="shuffleSelectedBtn" class="btn btn-outline-warning btn-sm">
                                                <i class="fas fa-random me-1"></i>Shuffle Selected
                                            </button>
                                            <button type="button" id="sortByNameBtn" class="btn btn-outline-info btn-sm">
                                                <i class="fas fa-sort-alpha-down me-1"></i>Sort by Name
                                            </button>
                                            <button type="button" id="sortBybibBtn" class="btn btn-outline-dark btn-sm">
                                                <i class="fas fa-sort-numeric-down me-1"></i>Sort by bib
                                            </button>
                                            <button type="button" id="sortByYearBtn" class="btn btn-outline-secondary btn-sm">
                                                <i class="fas fa-calendar me-1"></i>Sort by Year
                                            </button>
                                            <div class="vr mx-1"></div>
                                            <button type="button" class="btn btn-outline-success btn-sm" data-bs-toggle="modal" data-bs-target="#assignbibModal">
                                                <i class="fas fa-hashtag me-1"></i>Assign bib
                                            </button>
                                            <button type="button" id="moveToHeatBtn" class="btn btn-outline-info btn-sm" data-bs-toggle="modal" data-bs-target="#moveToHeatModal">
                                                <i class="fas fa-arrow-right me-1"></i>Move to Heat
                                            </button>
                                            <button type="button" id="promoteToHeatBtn" class="btn btn-outline-warning btn-sm">
                                                <i class="fas fa-level-up-alt me-1"></i>Promote to Heat
                                            </button>
                                            <div class="vr mx-1"></div>
                                            <button type="submit" class="btn btn-outline-danger btn-sm" form="bulkDeleteForm">
                                                <i class="fas fa-trash me-1"></i>Remove Selected
                                            </button>
                                        </div>
                                    </div>

                                    <!-- Table -->
                                    <div class="table-responsive">
                                        <table id="reorder-table" class="table table-hover table-sm">
                                            <thead class="table-light">
                                                <tr>
                                                    <th width="40">
                                                        <input type="checkbox" id="bulk-check-master" class="form-check-input">
                                                    </th>                                                   
                                                    <th width="60">Heat</th>
                                                    <th width="60">Bib</th>
                                                    <th>Name</th>
                                                    <!-- Club column hidden -->
                                                    <th>Category</th>
                                                    <th width="80">Gender</th>
                                                    <th width="80">Year</th>
                                                    <th width="80">Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if (empty($assignments)): ?>
                                                    <tr>
                                                        <td colspan="9" class="text-center text-muted py-4">
                                                            <i class="fas fa-users-slash fa-2x mb-2"></i>
                                                            <br>No participants assigned to heats yet
                                                            <br><small>Use the assignment form above to add participants</small>
                                                        </td>
                                                    </tr>
                                                <?php else: ?>
                                                    <?php foreach ($assignments as $a): ?>
                                                    <tr data-id="<?= $a['id'] ?>"
                                                        data-heat="<?= $a['heat_number'] ?>"
                                                        data-category="<?= htmlspecialchars($a['category'] ?? 'No Category') ?>"
                                                        data-club="<?= htmlspecialchars($a['club'] ?? '') ?>"
                                                        data-gender="<?= htmlspecialchars($a['gender'] ?? '') ?>"
                                                        data-year="<?= $a['date_of_birth'] ? date('Y', strtotime($a['date_of_birth'])) : '' ?>">
                                                        <td>
                                                            <input type="checkbox" name="delete_ids[]" value="<?= $a['id'] ?>" class="form-check-input bulk-check" form="bulkDeleteForm">
                                                        </td>                                                       
                                                        <td>
                                                            <span class="badge heat-number-<?= $a['heat_number'] ?>"><?= $a['heat_number'] ?></span>
                                                        </td>
                                                        <td class="css-bib">
                                                            <span class="badge bg-secondary"><?= $a['bib'] ?></span>
                                                        </td>
                                                        <td>
                                                            <strong><?= htmlspecialchars($a['last_name'] . ' ' . $a['first_name']) ?></strong>
                                                            <br><small class="text-muted">ID: <?= $a['participant_id'] ?></small>
                                                        </td>
                                                        <!-- Club column hidden -->
                                                        <td>
                                                            <span class="badge bg-info"><?= htmlspecialchars($a['category'] ?? 'No Category') ?></span>
                                                          
                                                        </td>
                                                        <td>
                                                            <span class="badge bg-<?= $a['gender'] === 'M' ? 'primary' : 'danger' ?>">
                                                                    <i class="fas fa-<?= $a['gender'] === 'M' ? 'male' : 'female' ?> me-1"></i>
                                                                    <?= htmlspecialchars($a['gender'] ?? '') ?>
                                                                </span>
                                                        </td>
                                                        <td>
                                                             <span class="badge_p">
                                                                    <?= $a['date_of_birth'] ? date('Y', strtotime($a['date_of_birth'])) : '' ?>
                                                                </span>
                                                        </td>
                                                        <td>
                                                            <div class="btn-group btn-group-sm">
                                                                <a href="participant_edit.php?id=<?= $a['participant_id'] ?? $a['id'] ?>" class="btn btn-outline-primary btn-sm" title="Edit">
                                                                    <i class="fas fa-edit"></i>
                                                                </a>
                                                                <a href="?delete_id=<?= $a['id'] ?>&event_id=<?= $selected_event ?>" class="btn btn-outline-danger btn-sm" title="Remove" onclick="return confirm('Remove from heat?')">
                                                                    <i class="fas fa-times"></i>
                                                                </a>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                    <?php endforeach; ?>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                            <!-- Bulk Delete Form (hidden) - Move this right after the table -->
                            <form id="bulkDeleteForm" method="post" action="heats_configure.php?event_id=<?= $selected_event ?>" style="display: none;">
                                <input type="hidden" name="bulk_delete" value="1">
                                <!-- Checkboxes are linked via form="bulkDeleteForm" attribute -->
                            </form>



<script>
// Debug version of filterParticipants
function filterParticipants() {
    console.log('filterParticipants called');
    
    const category = document.getElementById('categoryFilter').value;
    const gender = document.getElementById('genderFilter').value;
    const club = document.getElementById('clubFilter').value;
    const year = document.getElementById('yearFilter').value;
    const options = document.querySelectorAll('#participantSelect option');
    
    console.log('Filter values:', { category, gender, club, year });
    console.log('Options found:', options.length);
    
    let visibleCount = 0;
    
    options.forEach((option, index) => {
        let show = true;
        
        const optionData = {
            category: option.dataset.category || '',
            gender: option.dataset.gender || '',
            club: option.dataset.club || '',
            year: option.dataset.year || (option.dataset.date_of_birth ? option.dataset.date_of_birth.substring(0, 4) : ''),
            date_of_birth: option.dataset.date_of_birth || ''
        };
        
        // Debug first few options
        if (index < 3) {
            console.log(`Option ${index}:`, {
                text: option.textContent.trim(),
                value: option.value,
                data: optionData
            });
        }
        
        // Apply filters
        if (category && optionData.category !== category) show = false;
        if (gender && optionData.gender !== gender) show = false;
        if (club && optionData.club !== club) show = false;
        if (year && optionData.year !== year) show = false;
        
        // Set visibility
        option.style.display = show ? '' : 'none';
        if (show) visibleCount++;
        
        // Debug filtering result for first few options
        if (index < 3) {
            console.log(`Option ${index} show:`, show);
        }
    });
    
    console.log('Visible count:', visibleCount);
    
    // Update participant count
    const countElement = document.getElementById('participantCount');
    if (countElement) {
        countElement.textContent = visibleCount;
    }
    
    // Clear selection of hidden options
    options.forEach(option => {
        if (option.style.display === 'none') {
            option.selected = false;
        }
    });
}

// Select all visible participants
function selectAllVisible() {
    const options = document.querySelectorAll('#participantSelect option');
    let selectedCount = 0;
    
    options.forEach(option => {
        if (option.style.display !== 'none') {
            option.selected = true;
            selectedCount++;
        }
    });
    
    console.log('Selected', selectedCount, 'visible participants');
}

// Clear selection
function clearSelection() {
    const options = document.querySelectorAll('#participantSelect option');
    options.forEach(option => {
        option.selected = false;
    });
    console.log('Selection cleared');
}

// Clear all filters
function clearAllFilters() {
    document.getElementById('categoryFilter').value = '';
    document.getElementById('genderFilter').value = '';
    document.getElementById('clubFilter').value = '';
    document.getElementById('yearFilter').value = '';
    filterParticipants();
    clearSelection();
    console.log('All filters cleared');
}

// Test function to verify everything is working
function testFilters() {
    console.log('Testing filters...');
    const participantSelect = document.getElementById('participantSelect');
    const categoryFilter = document.getElementById('categoryFilter');
    
    console.log('participantSelect found:', !!participantSelect);
    console.log('categoryFilter found:', !!categoryFilter);
    
    if (participantSelect) {
        console.log('Total options in participantSelect:', participantSelect.options.length);
        
        // Test first option data
        if (participantSelect.options.length > 0) {
            const firstOption = participantSelect.options[0];
            console.log('First option data:', {
                text: firstOption.textContent,
                category: firstOption.dataset.category,
                gender: firstOption.dataset.gender,
                club: firstOption.dataset.club,
                year: firstOption.dataset.year
            });
        }
    }
    
    if (categoryFilter && categoryFilter.options.length > 1) {
        console.log('Testing category filter...');
        //categoryFilter.value = categoryFilter.options[1].value;
        filterParticipants();
    }
}

// Run test when page loads
document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM loaded, running test...');
    setTimeout(testFilters, 1000);
});
</script>
<script>

function filterReorderTable() {
    const heat = document.getElementById('filterHeat').value;
    const category = document.getElementById('filterCategory').value;
    const club = document.getElementById('filterClub').value;
    const gender = document.getElementById('filterGender').value;
    const yearFilter = document.getElementById('filterYear').value;
    
    const currentYear = new Date().getFullYear();
    let serial = 1;
    
    document.querySelectorAll('#reorder-table tbody tr').forEach(row => {
        // Skip the "no data" row
        if (row.cells.length === 1) return;
        
        let show = true;
        const rowYear = parseInt(row.dataset.year);
        
        if (heat && row.dataset.heat !== heat) show = false;
        if (category && row.dataset.category !== category) show = false;
        if (club && row.dataset.club !== club) show = false;
        if (gender && row.dataset.gender !== gender) show = false;
        
        // Enhanced year filtering with ranges
        if (yearFilter && show) {
            if (yearFilter.includes('-') && !yearFilter.startsWith('before-') && !yearFilter.startsWith('after-')) {
                // Handle year ranges like "2010-2015"
                const [startYear, endYear] = yearFilter.split('-').map(y => parseInt(y));
                if (rowYear < startYear || rowYear > endYear) show = false;
            } else if (yearFilter === 'before-2010') {
                if (rowYear >= 2010) show = false;
            } else if (yearFilter === 'after-2020') {
                if (rowYear <= 2020) show = false;
            } else if (yearFilter.startsWith('under-')) {
                // Age group filters
                const ageLimit = parseInt(yearFilter.split('-')[1]);
                const birthYear = currentYear - ageLimit;
                if (rowYear <= birthYear) show = false;
            } else if (yearFilter.startsWith('over-')) {
                // Age group filters
                const ageLimit = parseInt(yearFilter.split('-')[1]);
                const birthYear = currentYear - ageLimit;
                if (rowYear >= birthYear) show = false;
            } else {
                // Single year filter
                if (row.dataset.year !== yearFilter) show = false;
            }
        }
        
        row.style.display = show ? '' : 'none';
        
        // Set serial number only for visible rows
        if (show) {
            const serialCell = row.querySelector('.serial-number');
            if (serialCell) {
                serialCell.textContent = serial++;
            }
        }
    });
    
    // Update master checkbox state
    updateMasterCheckbox();
    
    // Update visible count in header
    const visibleCount = document.querySelectorAll('#reorder-table tbody tr:not([style*="display: none"])').length;
    const headerText = document.querySelector('.card-header h6');
    if (headerText) {
        const originalText = headerText.textContent.replace(/\(\d+[^)]*\)/, '');
        headerText.innerHTML = `<i class="fas fa-fire me-2"></i>${originalText.trim()} (${visibleCount} visible)`;
    }
}

function clearFilters() {
    document.getElementById('filterHeat').value = '';
    document.getElementById('filterCategory').value = '';
    document.getElementById('filterClub').value = '';
    document.getElementById('filterGender').value = '';
    document.getElementById('filterYear').value = '';
    filterReorderTable();
}

function updateMasterCheckbox() {
    const visibleCheckboxes = document.querySelectorAll('#reorder-table tbody tr:not([style*="display: none"]) .bulk-check');
    const checkedBoxes = document.querySelectorAll('#reorder-table tbody tr:not([style*="display: none"]) .bulk-check:checked');
    const masterCheckbox = document.getElementById('bulk-check-master');
    
    if (visibleCheckboxes.length === 0) {
        masterCheckbox.indeterminate = false;
        masterCheckbox.checked = false;
    } else if (checkedBoxes.length === visibleCheckboxes.length) {
        masterCheckbox.indeterminate = false;
        masterCheckbox.checked = true;
    } else if (checkedBoxes.length > 0) {
        masterCheckbox.indeterminate = true;
        masterCheckbox.checked = false;
    } else {
        masterCheckbox.indeterminate = false;
        masterCheckbox.checked = false;
    }
}

function confirmBulkDelete() {
    const selectedCount = document.querySelectorAll('#reorder-table .bulk-check:checked').length;
    if (selectedCount === 0) {
        alert('Please select participants to remove.');
        return false;
    }
    return confirm(`Remove ${selectedCount} selected participant(s) from their heats?`);
}

// Update master checkbox functionality to work with the form
jQuery('#bulk-check-master').on('change', function () {
    const checked = this.checked;
    jQuery('#reorder-table tbody tr:visible .bulk-check').each(function () {
        this.checked = checked;
        jQuery(this).closest('tr').toggleClass('selected-row', checked);
    });
    updateMasterCheckbox();
});

// Individual checkbox functionality
jQuery(document).on('change', '.bulk-check', function () {
    jQuery(this).closest('tr').toggleClass('selected-row', this.checked);
    updateMasterCheckbox();
});

// Make sure the bulk delete button works
jQuery(document).on('click', 'button[form="bulkDeleteForm"]', function(e) {
    e.preventDefault();
    if (confirmBulkDelete()) {
        jQuery('#bulkDeleteForm').submit();
    }
});

// Initial numbering on page load
document.addEventListener('DOMContentLoaded', function() {
    let serial = 1;
    document.querySelectorAll('#reorder-table tbody tr').forEach(row => {
        const serialCell = row.querySelector('.serial-number');
        if (serialCell) {
            serialCell.textContent = serial++;
        }
    });
    
    // Update master checkbox on individual checkbox change
    document.addEventListener('change', function(e) {
        if (e.target.classList.contains('bulk-check')) {
            updateMasterCheckbox();
        }
    });
});

// Enhanced participant selection with table-based UX
let selectedParticipants = new Set();

// Initialize the interface
document.addEventListener('DOMContentLoaded', function() {
    updateParticipantCounts();
    updateSelectionStatus();
    
    // Initialize master checkbox functionality
    document.getElementById('selectAllParticipants').addEventListener('change', function() {
        const isChecked = this.checked;
        const visibleRows = document.querySelectorAll('#participantsTable tbody .participant-row:not(.d-none)');
        
        visibleRows.forEach(row => {
            const checkbox = row.querySelector('.participant-checkbox');
            const participantId = row.dataset.id;
            
            if (isChecked) {
                if (!selectedParticipants.has(participantId)) {
                    selectedParticipants.add(participantId);
                    checkbox.checked = true;
                    row.classList.add('selected');
                    
                    const hiddenOption = document.querySelector(`#participantSelect option[value="${participantId}"]`);
                    if (hiddenOption) hiddenOption.selected = true;
                }
            } else {
                selectedParticipants.delete(participantId);
                checkbox.checked = false;
                row.classList.remove('selected');
                
                const hiddenOption = document.querySelector(`#participantSelect option[value="${participantId}"]`);
                if (hiddenOption) hiddenOption.selected = false;
            }
        });
        
        updateSelectionStatus();
    });
});

// Toggle table row selection
function toggleTableRowSelection(rowElement) {
    const participantId = rowElement.dataset.id;
    const checkbox = rowElement.querySelector('.participant-checkbox');
    const hiddenOption = document.querySelector(`#participantSelect option[value="${participantId}"]`);
    
    if (selectedParticipants.has(participantId)) {
        // Deselect
        selectedParticipants.delete(participantId);
        rowElement.classList.remove('selected');
        checkbox.checked = false;
        if (hiddenOption) hiddenOption.selected = false;
    } else {
        // Select
        selectedParticipants.add(participantId);
        rowElement.classList.add('selected');
        checkbox.checked = true;
        if (hiddenOption) hiddenOption.selected = true;
    }
    
    updateSelectionStatus();
    updateMasterCheckboxState();
}

// Update master checkbox state based on individual selections
function updateMasterCheckboxState() {
    const visibleRows = document.querySelectorAll('#participantsTable tbody .participant-row:not(.d-none)');
    const selectedVisibleRows = Array.from(visibleRows).filter(row => selectedParticipants.has(row.dataset.id));
    const masterCheckbox = document.getElementById('selectAllParticipants');
    
    if (visibleRows.length === 0) {
        masterCheckbox.indeterminate = false;
        masterCheckbox.checked = false;
    } else if (selectedVisibleRows.length === visibleRows.length) {
        masterCheckbox.indeterminate = false;
        masterCheckbox.checked = true;
    } else if (selectedVisibleRows.length > 0) {
        masterCheckbox.indeterminate = true;
    } else {
        masterCheckbox.indeterminate = false;
        masterCheckbox.checked = false;
    }
}

// Enhanced filtering with table row visibility
function filterParticipants() {
    console.log('filterParticipants called');
    
    const category = document.getElementById('categoryFilter').value;
    const gender = document.getElementById('genderFilter').value;
    const club = document.getElementById('clubFilter').value;
    const year = document.getElementById('yearFilter').value;
    const rows = document.querySelectorAll('#participantsTable tbody .participant-row');
    
    console.log('Filter values:', { category, gender, club, year });
    
    let visibleCount = 0;
    
    rows.forEach((row, index) => {
        let show = true;
        
        const rowData = {
            category: row.dataset.category || '',
            gender: row.dataset.gender || '',
            club: row.dataset.club || '',
            year: row.dataset.year || ''
        };
        
        // Apply filters
        if (category && rowData.category !== category) show = false;
        if (gender && rowData.gender !== gender) show = false;
        if (club && rowData.club !== club) show = false;
        if (year && rowData.year !== year) show = false;
        
        // Set visibility
        if (show) {
            row.classList.remove('d-none');
            visibleCount++;
        } else {
            row.classList.add('d-none');
            
            // Deselect if hidden
            const participantId = row.dataset.id;
            if (selectedParticipants.has(participantId)) {
                selectedParticipants.delete(participantId);
                row.classList.remove('selected');
                row.querySelector('.participant-checkbox').checked = false;
                const hiddenOption = document.querySelector(`#participantSelect option[value="${participantId}"]`);
                if (hiddenOption) hiddenOption.selected = false;
            }
        }
    });
    
    console.log('Visible count:', visibleCount);
    updateParticipantCounts();
    updateSelectionStatus();
    updateMasterCheckboxState();
    showNoResultsMessage(visibleCount === 0);
}

// Search functionality
function searchParticipants() {
    const searchTerm = document.getElementById('participantSearch').value.toLowerCase();
    const rows = document.querySelectorAll('#participantsTable tbody .participant-row');
    
    let visibleCount = 0;
    
    rows.forEach(row => {
        const searchText = row.dataset.searchText || '';
        const matchesSearch = searchTerm === '' || searchText.includes(searchTerm);
        
        // Also check if it passes current filters
        const category = document.getElementById('categoryFilter').value;
        const gender = document.getElementById('genderFilter').value;
        const club = document.getElementById('clubFilter').value;
        const year = document.getElementById('yearFilter').value;
        
        let passesFilters = true;
        if (category && row.dataset.category !== category) passesFilters = false;
        if (gender && row.dataset.gender !== gender) passesFilters = false;
        if (club && row.dataset.club !== club) passesFilters = false;
        if (year && row.dataset.year !== year) passesFilters = false;
        
        const show = matchesSearch && passesFilters;
        
        if (show) {
            row.classList.remove('d-none');
            visibleCount++;
        } else {
            row.classList.add('d-none');
            
            // Deselect if hidden
            const participantId = row.dataset.id;
            if (selectedParticipants.has(participantId)) {
                selectedParticipants.delete(participantId);
                row.classList.remove('selected');
                row.querySelector('.participant-checkbox').checked = false;
                const hiddenOption = document.querySelector(`#participantSelect option[value="${participantId}"]`);
                if (hiddenOption) hiddenOption.selected = false;
            }
        }
    });
    
    updateParticipantCounts();
    updateSelectionStatus();
    updateMasterCheckboxState();
    showNoResultsMessage(visibleCount === 0);
}

// Clear search
function clearSearch() {
    document.getElementById('participantSearch').value = '';
    searchParticipants();
}

// Select all visible participants
function selectAllVisible() {
    const visibleRows = document.querySelectorAll('#participantsTable tbody .participant-row:not(.d-none)');
    let selectedCount = 0;
    
    visibleRows.forEach(row => {
        const participantId = row.dataset.id;
        if (!selectedParticipants.has(participantId)) {
            selectedParticipants.add(participantId);
            row.classList.add('selected');
            row.querySelector('.participant-checkbox').checked = true;
            
            const hiddenOption = document.querySelector(`#participantSelect option[value="${participantId}"]`);
            if (hiddenOption) hiddenOption.selected = true;
            
            selectedCount++;
        }
    });
    
    updateSelectionStatus();
    updateMasterCheckboxState();
    
    // Visual feedback
    if (selectedCount > 0) {
        document.getElementById('participantStatusBadge').classList.add('has-selection');
        setTimeout(() => {
            document.getElementById('participantStatusBadge').classList.remove('has-selection');
        }, 1000);
    }
    
    console.log('Selected', selectedCount, 'visible participants');
}

// Clear selection
function clearSelection() {
    selectedParticipants.clear();
    
    // Update all table rows
    document.querySelectorAll('#participantsTable tbody .participant-row').forEach(row => {
        row.classList.remove('selected');
        row.querySelector('.participant-checkbox').checked = false;
    });
    
    // Update master checkbox
    const masterCheckbox = document.getElementById('masterCheckbox');
    if (masterCheckbox) {
        masterCheckbox.checked = false;
    }
    
    // Update hidden select
    document.querySelectorAll('#participantSelect option').forEach(option => {
        option.selected = false;
    });
    
    updateSelectionStatus();
    console.log('Selection cleared');
}

// Clear all filters and search
function clearAllFiltersAndSearch() {
    document.getElementById('categoryFilter').value = '';
    document.getElementById('genderFilter').value = '';
    document.getElementById('clubFilter').value = '';
    document.getElementById('yearFilter').value = '';
    document.getElementById('participantSearch').value = '';
    
    filterParticipants();
    clearSelection();
    console.log('All filters and search cleared');
}

// Alias for backward compatibility
function clearAllFilters() {
    clearAllFiltersAndSearch();
}

// Update participant counts
function updateParticipantCounts() {
    const allRows = document.querySelectorAll('#participantsTable tbody .participant-row');
    const visibleRows = document.querySelectorAll('#participantsTable tbody .participant-row:not(.d-none)');
    
    document.getElementById('participantCount').textContent = allRows.length;
    document.getElementById('visibleCount').textContent = visibleRows.length;
}

// Update selection status
function updateSelectionStatus() {
    const selectedCount = selectedParticipants.size;
    
    document.getElementById('selectedCount').textContent = selectedCount;
    
    const badge = document.getElementById('participantStatusBadge');
    if (selectedCount > 0) {
        badge.textContent = `${selectedCount} selected`;
        badge.className = 'badge bg-success ms-2';
    } else {
        badge.textContent = '0 selected';
        badge.className = 'badge bg-info ms-2';
    }
}

// Show/hide no results message
function showNoResultsMessage(show) {
    const noResultsMessage = document.getElementById('noParticipantsMessage');
    const participantTable = document.getElementById('participantsTable');
    
    if (show) {
        noResultsMessage.style.display = 'block';
        participantTable.style.display = 'none';
    } else {
        noResultsMessage.style.display = 'none';
        participantTable.style.display = 'table';
    }
}

// Enhanced keyboard shortcuts
document.addEventListener('keydown', function(e) {
    // Ctrl/Cmd + A to select all visible
    if ((e.ctrlKey || e.metaKey) && e.key === 'a' && document.activeElement.id !== 'participantSearch') {
        e.preventDefault();
        selectAllVisible();
    }
    
    // Escape to clear selection
    if (e.key === 'Escape') {
        clearSelection();
        if (document.activeElement.id === 'participantSearch') {
            document.activeElement.blur();
        }
    }
    
    // Ctrl/Cmd + F to focus search
    if ((e.ctrlKey || e.metaKey) && e.key === 'f') {
        e.preventDefault();
        document.getElementById('participantSearch').focus();
    }
});

// Touch support for mobile
document.addEventListener('touchstart', function() {
    // Enable touch selection for table rows
    document.querySelectorAll('#participantsTable tbody .participant-row').forEach(row => {
        row.addEventListener('touchend', function(e) {
            e.preventDefault();
            toggleTableRowSelection(this);
        });
    });
});

// Simplified participant selection for table
function toggleParticipantSelection(element) {
    const participantId = element.dataset.id;
    const hiddenOption = document.querySelector(`#participantSelect option[value="${participantId}"]`);
    
    // Find table row
    const tableRow = document.querySelector(`#participantsTable tbody .participant-row[data-id="${participantId}"]`);
    const checkbox = tableRow ? tableRow.querySelector('.participant-checkbox') : null;
    
    if (selectedParticipants.has(participantId)) {
        // Deselect
        selectedParticipants.delete(participantId);
        if (tableRow) tableRow.classList.remove('selected');
        if (checkbox) checkbox.checked = false;
        if (hiddenOption) hiddenOption.selected = false;
    } else {
        // Select
        selectedParticipants.add(participantId);
        if (tableRow) tableRow.classList.add('selected');
        if (checkbox) checkbox.checked = true;
        if (hiddenOption) hiddenOption.selected = true;
    }
    
    updateSelectionStatus();
}

// Table filtering function
function filterParticipants() {
    console.log('filterParticipants called for table');
    
    const category = document.getElementById('categoryFilter').value;
    const gender = document.getElementById('genderFilter').value;
    const club = document.getElementById('clubFilter').value;
    const year = document.getElementById('yearFilter').value;
    
    console.log('Filter values:', { category, gender, club, year });
    
    let visibleCount = 0;
    
    const rows = document.querySelectorAll('#participantsTable tbody .participant-row');
    
    rows.forEach((row) => {
        let show = true;
        
        const rowData = {
            category: row.dataset.category || '',
            gender: row.dataset.gender || '',
            club: row.dataset.club || '',
            year: row.dataset.year || ''
        };
        
        // Apply filters
        if (category && rowData.category !== category) show = false;
        if (gender && rowData.gender !== gender) show = false;
        if (club && rowData.club !== club) show = false;
        if (year && rowData.year !== year) show = false;
        
        // Set visibility
        if (show) {
            row.classList.remove('d-none');
            visibleCount++;
        } else {
            row.classList.add('d-none');
            
            // Deselect if hidden
            const participantId = row.dataset.id;
            if (selectedParticipants.has(participantId)) {
                selectedParticipants.delete(participantId);
                row.classList.remove('selected');
                const checkbox = row.querySelector('.participant-checkbox');
                if (checkbox) checkbox.checked = false;
                const hiddenOption = document.querySelector(`#participantSelect option[value="${participantId}"]`);
                if (hiddenOption) hiddenOption.selected = false;
            }
        }
    });
    
    console.log('Visible count:', visibleCount);
    updateParticipantCounts();
    updateSelectionStatus();
    showNoResultsMessage(visibleCount === 0);
}

// Table search function
function searchParticipants() {
    const searchTerm = document.getElementById('participantSearch').value.toLowerCase();
    
    let visibleCount = 0;
    
    const rows = document.querySelectorAll('#participantsTable tbody .participant-row');
    
    rows.forEach(row => {
        const searchText = row.dataset.searchText || '';
        const matchesSearch = searchTerm === '' || searchText.includes(searchTerm);
        
        // Also check if it passes current filters
        const passesFilters = checkElementPassesFilters(row);
        const show = matchesSearch && passesFilters;
        
        if (show) {
            row.classList.remove('d-none');
            visibleCount++;
        } else {
            row.classList.add('d-none');
            
            // Deselect if hidden
            deselectParticipant(row.dataset.id);
        }
    });
    
    updateParticipantCounts();
    updateSelectionStatus();
    showNoResultsMessage(visibleCount === 0);
}

function checkElementPassesFilters(element) {
    const category = document.getElementById('categoryFilter').value;
    const gender = document.getElementById('genderFilter').value;
    const club = document.getElementById('clubFilter').value;
    const year = document.getElementById('yearFilter').value;
    
    let passesFilters = true;
    if (category && element.dataset.category !== category) passesFilters = false;
    if (gender && element.dataset.gender !== gender) passesFilters = false;
    if (club && element.dataset.club !== club) passesFilters = false;
    if (year && element.dataset.year !== year) passesFilters = false;
    
    return passesFilters;
}

function deselectParticipant(participantId) {
    if (selectedParticipants.has(participantId)) {
        selectedParticipants.delete(participantId);
        
        const tableRow = document.querySelector(`#participantsTable tbody .participant-row[data-id="${participantId}"]`);
        const checkbox = tableRow ? tableRow.querySelector('.participant-checkbox') : null;
        const hiddenOption = document.querySelector(`#participantSelect option[value="${participantId}"]`);
        
        if (tableRow) tableRow.classList.remove('selected');
        if (checkbox) checkbox.checked = false;
        if (hiddenOption) hiddenOption.selected = false;
    }
}

// Select all visible table rows
function selectAllVisible() {
    const visibleRows = document.querySelectorAll('#participantsTable tbody .participant-row:not(.d-none)');
    let selectedCount = 0;
    
    visibleRows.forEach(row => {
        const participantId = row.dataset.id;
        if (!selectedParticipants.has(participantId)) {
            selectedParticipants.add(participantId);
            row.classList.add('selected');
            
            // Update checkbox
            const checkbox = row.querySelector('.participant-checkbox');
            if (checkbox) checkbox.checked = true;
            
            // Update hidden select
            const hiddenOption = document.querySelector(`#participantSelect option[value="${participantId}"]`);
            if (hiddenOption) hiddenOption.selected = true;
            
            selectedCount++;
        }
    });
    
    updateSelectionStatus();
    console.log('Selected all', selectedCount, 'visible participants');
}

// Visual feedback
function addSelectionFeedback() {
    const badge = document.getElementById('participantStatusBadge');
    if (badge) {
        badge.classList.add('has-selection');
        setTimeout(() => {
            badge.classList.remove('has-selection');
        }, 1000);
    }
}


// (View preference functions removed - only table view now)

// Enhanced keyboard shortcuts for table
document.addEventListener('keydown', function(e) {
    // Ctrl/Cmd + A to select all visible
    if ((e.ctrlKey || e.metaKey) && e.key === 'a' && document.activeElement.id !== 'participantSearch') {
        e.preventDefault();
        selectAllVisible();
    }
    
    // Escape to clear selection
    if (e.key === 'Escape') {
        clearSelection();
        if (document.activeElement.id === 'participantSearch') {
            document.activeElement.blur();
        }
    }
    
    // Ctrl/Cmd + F to focus search
    if ((e.ctrlKey || e.metaKey) && e.key === 'f') {
        e.preventDefault();
        document.getElementById('participantSearch').focus();
    }
    
    // (View switching removed - only table view now)
});

// Table initialization on page load
document.addEventListener('DOMContentLoaded', function() {
    // Initialize table functionality
    updateParticipantCounts();
    updateSelectionStatus();
});

// Touch support for mobile table rows
document.addEventListener('touchstart', function() {
    // Enable touch selection for table rows
    document.querySelectorAll('#participantsTable tbody .participant-row').forEach(row => {
        row.addEventListener('touchend', function(e) {
            e.preventDefault();
            toggleTableRowSelection(this);
        });
    });
});
// Test function for debugging table
function testFilters() {
    console.log('Testing table-based filters...');
    const participantTable = document.getElementById('participantsTable');
    const categoryFilter = document.getElementById('categoryFilter');
    
    console.log('participantTable found:', !!participantTable);
    console.log('categoryFilter found:', !!categoryFilter);
    
    if (participantTable) {
        const rows = participantTable.querySelectorAll('tbody .participant-row');
        console.log('Total rows in table:', rows.length);
        
        if (rows.length > 0) {
            const firstRow = rows[0];
            console.log('First row data:', {
                id: firstRow.dataset.id,
                category: firstRow.dataset.category,
                gender: firstRow.dataset.gender,
                club: firstRow.dataset.club,
                year: firstRow.dataset.year
            });
        }
    }
    
    console.log('Current selection:', Array.from(selectedParticipants));
}

// Run test when page loads (for debugging)
document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM loaded, running table-based test...');
    setTimeout(testFilters, 1000);
});
</script>
        

        
        
    <?php endif; ?>
</div>
<style>
tr.selected-row td {
    background-color: #d9f2ff;
}
.shuffled {
    animation: flash 0.5s ease-in-out;
}
@keyframes flash {
    0% { background-color: #fff176; }
    100% { background-color: transparent; }
}
</style>
<style>
/* Custom styling to match participant management */
.table-hover tbody tr:hover {
    background-color: rgba(0, 123, 255, 0.05);
}

tr.selected-row {
    background-color: rgba(0, 123, 255, 0.1) !important;
}

.shuffled {
    animation: flash 0.5s ease-in-out;
}

@keyframes flash {
    0% { background-color: #fff176; }
    100% { background-color: transparent; }
}

/* Sortable cursor */
#reorder-table tbody tr {
    cursor: move;
}

#reorder-table tbody tr:hover {
    background-color: rgba(0, 123, 255, 0.05);
}

/* Badge styling for pink gender */
.bg-pink {
    background-color: #f8d7da !important;
}

/* Drag helper styling */
.ui-sortable-helper {
    background-color: rgba(0, 123, 255, 0.1);
    border: 2px dashed #007bff;
}

/* Filter section styling */
.vr {
    width: 1px;
    height: 24px;
    background-color: #dee2e6;
}
.participant-select-container {
    position: relative;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    border: 2px solid #e9ecef;
    transition: border-color 0.3s ease;
}

.participant-select-container:focus-within {
    border-color: #0d6efd;
    box-shadow: 0 4px 12px rgba(13, 110, 253, 0.2);
}

.participant-multiselect {
    border: none !important;
    border-radius: 0 !important;
    box-shadow: none !important;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
    padding: 0;
}

.participant-multiselect:focus {
    outline: none;
    box-shadow: none !important;
}

.participant-option {
    padding: 0 !important;
    border: none !important;
    margin: 0 !important;
    background: transparent !important;
    border-bottom: 1px solid #f0f0f0 !important;
    transition: all 0.2s ease;
    cursor: pointer;
}

.participant-option:hover {
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%) !important;
    transform: translateX(4px);
}

.participant-option:checked {
    background: linear-gradient(135deg, #0d6efd 0%, #0b5ed7 100%) !important;
    color: white !important;
    transform: translateX(8px);
    box-shadow: inset 4px 0 0 rgba(255, 255, 255, 0.3);
}

.participant-option.already-assigned {
    background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%) !important;
    border-left: 4px solid #2196f3 !important;
}

.participant-option.already-assigned:checked {
    background: linear-gradient(135deg, #1976d2 0%, #1565c0 100%) !important;
}

.participant-card {
    padding: 12px 16px;
    display: flex;
    flex-direction: column;
    gap: 6px;
}

.participant-header {
    display: flex;
    align-items: center;
    gap: 10px;
    flex-wrap: wrap;
}

.participant-bib {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    background: linear-gradient(135deg, #6c757d 0%, #495057 100%);
    color: white;
    padding: 4px 10px;
    border-radius: 20px;
    font-size: 0.75rem;
    font-weight: bold;
    min-width: 45px;
    height: 24px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.participant-option:checked .participant-bib {
    background: linear-gradient(135deg, #ffffff 0%, #e9ecef 100%);
    color: #0d6efd;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.participant-name {
    font-weight: 600;
    font-size: 0.9rem;
    color: #212529;
    flex-grow: 1;
}

.participant-option:checked .participant-name {
    color: white;
    font-weight: 700;
}

.assignment-badge {
    background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
    color: white;
    padding: 2px 8px;
    border-radius: 12px;
    font-size: 0.7rem;
    font-weight: bold;
    display: inline-flex;
    align-items: center;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
}

.participant-option:checked .assignment-badge {
    background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
    color: #28a745;
}

.participant-details {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    align-items: center;
}

.detail-item {
    display: inline-flex;
    align-items: center;
    font-size: 0.75rem;
    padding: 2px 6px;
    border-radius: 8px;
    background: rgba(108, 117, 125, 0.1);
    color: #6c757d;
    transition: all 0.2s ease;
}

.participant-option:checked .detail-item {
    background: rgba(255, 255, 255, 0.2);
    color: rgba(255, 255, 255, 0.9);
}

.detail-item.club {
    background: rgba(13, 110, 253, 0.1);
    color: #0d6efd;
}

.detail-item.category {
    background: rgba(255, 193, 7, 0.1);
    color: #ffc107;
}

.detail-item.gender {
    background: rgba(220, 53, 69, 0.1);
    color: #dc3545;
}

.detail-item.year {
    background: rgba(108, 117, 125, 0.1);
    color: #6c757d;
}

.participant-select-footer {
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    padding: 12px 16px;
    border-top: 1px solid #dee2e6;
}

#participantStatusBadge {
    transition: all 0.3s ease;
}

#participantStatusBadge.has-selection {
    background: linear-gradient(135deg, #28a745 0%, #20c997 100%) !important;
    animation: pulse 1s ease-in-out;
}


.heat-number-1  { background-color: hsl(209, 100%, 50%) !important; } /* +14° */
.heat-number-6  { background-color: hsl(222, 100%, 50%) !important; } /* +13° */
.heat-number-2  { background-color: hsl(234, 100%, 50%) !important; } /* +12° */
.heat-number-5  { background-color: hsl(245, 100%, 50%) !important; } /* +11° */
.heat-number-4  { background-color: hsl(255, 100%, 50%) !important; } /* +10° */
.heat-number-3  { background-color: hsl(264, 100%, 50%) !important; } /* +9°  */
.heat-number-8  { background-color: hsl(272, 100%, 50%) !important; } /* +8°  */
.heat-number-7  { background-color: hsl(279, 100%, 50%) !important; } /* +7°  */
.heat-number-9  { background-color: hsl(285, 100%, 50%) !important; } /* +6°  */
.heat-number-11 { background-color: hsl(290, 100%, 50%) !important; } /* +5°  */
.heat-number-10 { background-color: hsl(294, 100%, 50%) !important; } /* +4°  */
.heat-number-13 { background-color: hsl(297, 100%, 50%) !important; } /* +3°  */
.heat-number-14 { background-color: hsl(299, 100%, 50%) !important; } /* +2° */
@keyframes pulse {
    0% { transform: scale(1); }
    50% { transform: scale(1.1); }
    100% { transform: scale(1); }
}

/* Responsive adjustments */
@media (max-width: 768px) {
    .participant-card {
        padding: 10px 12px;
    }
    
    .participant-header {
        gap: 8px;
    }
    
    .participant-bib {
        font-size: 0.7rem;
        padding: 3px 8px;
        min-width: 40px;
        height: 22px;
    }
    
    .participant-name {
        font-size: 0.85rem;
    }
    
    .detail-item {
        font-size: 0.7rem;
        padding: 1px 4px;
    }
}

/* Scrollbar styling for webkit browsers */
.participant-multiselect::-webkit-scrollbar {
    width: 8px;
}

.participant-multiselect::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 4px;
}

.participant-multiselect::-webkit-scrollbar-thumb {
    background: linear-gradient(135deg, #6c757d 0%, #495057 100%);
    border-radius: 4px;
}

.participant-multiselect::-webkit-scrollbar-thumb:hover {
    background: linear-gradient(135deg, #495057 0%, #343a40 100%);
}
/* Form enhancements */
.card-header p {
    margin-top: 4px;
}

/* Button hover effects */
#ajaxAssignBtn {
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    transition: all 0.2s ease;
}

#ajaxAssignBtn:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.15);
}

/* Loading state */
#ajaxAssignBtn.loading {
    position: relative;
    color: transparent;
}

#ajaxAssignBtn.loading::after {
    content: '';
    position: absolute;
    width: 16px;
    height: 16px;
    top: 50%;
    left: 50%;
    margin-left: -8px;
    margin-top: -8px;
    border: 2px solid #ffffff;
    border-radius: 50%;
    border-top-color: transparent;
    animation: spin 0.8s linear infinite;
}

@keyframes spin {
    to {
        transform: rotate(360deg);
    }
}

/* Filter section styling */
.form-select-sm {
    font-size: 0.875rem;
}

/* Responsive adjustments */
@media (max-width: 768px) {
    .participant-multiselect {
        font-size: 0.875rem;
    }
    
    .participant-bib {
        font-size: 0.7rem;
        padding: 1px 6px;
        min-width: 35px;
    }
}
/* Row View Styling */
.participant-row-container {
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    border: 2px solid #e9ecef;
    background: #ffffff;
    max-height: 600px;
    overflow-y: auto;
}

.participant-row-header {
    display: grid;
    grid-template-columns: 80px 1fr 1fr 1fr 80px 80px 120px 80px;
    gap: 1px;
    background: #f8f9fa;
    border-bottom: 2px solid #dee2e6;
    position: sticky;
    top: 0;
    z-index: 10;
}

.row-header-item {
    padding: 12px 8px;
    font-weight: 600;
    font-size: 0.875rem;
    background: #e9ecef;
    text-align: center;
    color: #495057;
    border-right: 1px solid #dee2e6;
}

.row-header-item:last-child {
    border-right: none;
}

.participant-rows {
    background: #ffffff;
}

.participant-row-item {
    display: grid;
    grid-template-columns: 80px 1fr 1fr 1fr 80px 80px 120px 80px;
    gap: 1px;
    background: #f8f9fa;
    border-bottom: 1px solid #e9ecef;
    cursor: pointer;
    transition: all 0.2s ease;
    position: relative;
    min-height: 60px;
    align-items: center;
}

.participant-row-item:hover {
    background: #e3f2fd;
    transform: translateX(2px);
    box-shadow: 0 2px 8px rgba(0, 123, 255, 0.15);
}

/* Drag-and-Drop Styles */
#participantsTable tbody .participant-row[draggable="true"] {
    cursor: grab;
}

#participantsTable tbody .participant-row[draggable="true"]:active {
    cursor: grabbing;
}

#participantsTable tbody .participant-row[draggable="true"]:hover {
    background-color: #fff3cd;
    border-left: 3px solid #ffc107;
}

#reorder-table tbody.drag-over {
    background-color: #e3f2fd;
    border: 2px dashed #007bff;
}


.participant-row-item.selected {
    background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
    color: white;
    transform: translateX(4px);
    box-shadow: 0 4px 12px rgba(0, 123, 255, 0.3);
}

.participant-row-item.already-assigned {
    border-left: 4px solid #28a745;
    background: linear-gradient(135deg, #f8fffa 0%, #e8f5e8 100%);
}

.participant-row-item.already-assigned.selected {
    background: linear-gradient(135deg, #28a745 0%, #1e7e34 100%);
}

.row-selection-indicator {
    position: absolute;
    top: 8px;
    right: 8px;
    background: #28a745;
    color: white;
    width: 20px;
    height: 20px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 0.7rem;
    opacity: 0;
    transform: scale(0);
    transition: all 0.3s ease;
    border: 1px solid white;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
    z-index: 5;
}

.participant-row-item.selected .row-selection-indicator {
    opacity: 1;
    transform: scale(1);
}

.row-item {
    padding: 8px;
    background: white;
    display: flex;
    align-items: center;
    justify-content: center;
    text-align: center;
    border-right: 1px solid #e9ecef;
    min-height: 44px;
}
td.row-item{    text-align: left !important;
    justify-content: flex-start !important;}
.row-item:last-child {
    border-right: none;
}

.participant-row-item.selected .row-item {
    background: rgba(255, 255, 255, 0.1);
    color: white;
}

/* Individual row item styling */
.row-bib-badge {
    background: linear-gradient(135deg, #6c757d 0%, #495057 100%);
    color: white;
    padding: 4px 8px;
    border-radius: 12px;
    font-size: 0.8rem;
    font-weight: bold;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    min-width: 40px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}
.heat-badge {
    
    color: white;
    padding: 4px 8px;
    border-radius: 12px;
    font-size: 0.8rem;
    font-weight: bold;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}
.participant-row-item.selected .row-bib-badge {
    background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
    color: #007bff;
}

.name-col {
    text-align: left !important;
    justify-content: flex-start !important;
}

.row-name {
    font-weight: 600;
    font-size: 0.9rem;
    line-height: 1.2;
}
.row-name {
    display: inline-block;
}

.row-id {
    display: inline;
}
.row-id {
    font-size: 0.7rem;
    color: #6c757d;
    margin-top: 2px;
}

.participant-row-item.selected .row-id {
    color: rgba(255, 255, 255, 0.8);
}

.club-col, .category-col {
    text-align: left !important;
    justify-content: flex-start !important;
}

.row-club, .row-category {
    font-size: 0.85rem;
    padding: 2px 6px;
    border-radius: 6px;
    background: rgba(108, 117, 125, 0.1);
    display: inline-block;
    max-width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.participant-row-item.selected .row-club,
.participant-row-item.selected .row-category {
    background: rgba(255, 255, 255, 0.2);
}

.row-gender {
    font-size: 0.85rem;
    display: flex;
    align-items: center;
    gap: 4px;
}

.row-year {
    font-size: 0.85rem;
    color: #6c757d;
}

.participant-row-item.selected .row-year {
    color: rgba(255, 255, 255, 0.9);
}

.row-status {
    font-size: 0.8rem;
    padding: 4px 8px;
    border-radius: 12px;
    display: inline-flex;
    align-items: center;
    gap: 4px;
    font-weight: 500;
}

.row-status.assigned {
    background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
    color: white;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.row-status.unassigned {
    background: rgba(108, 117, 125, 0.1);
    color: #6c757d;
}

.participant-row-item.selected .row-status.assigned {
    background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
    color: #28a745;
}

.participant-row-item.selected .row-status.unassigned {
    background: rgba(255, 255, 255, 0.2);
    color: rgba(255, 255, 255, 0.9);
}

/* View Toggle Button Styling */
.btn-group .btn.active {
    background-color: #007bff;
    border-color: #007bff;
    color: white;
}

/* Responsive adjustments for row view */
@media (max-width: 768px) {
    .participant-row-header,
    .participant-row-item {
        grid-template-columns: 60px 1fr 100px 80px 60px 60px 100px;
        font-size: 0.8rem;
    }
    
    .row-header-item,
    .row-item {
        padding: 6px 4px;
        min-height: 40px;
    }
    
    .row-name {
        font-size: 0.8rem;
    }
    
    .row-id {
        font-size: 0.65rem;
    }
    
    .row-bib-badge {
        font-size: 0.7rem;
        padding: 2px 6px;
        min-width: 35px;
    }
}

@media (max-width: 576px) {
    .participant-row-header,
    .participant-row-item {
        grid-template-columns: 50px 1fr 80px 60px 50px 50px 80px;
    }
    
    .row-header-item,
    .row-item {
        padding: 4px 2px;
        font-size: 0.75rem;
    }
    
    .row-club, .row-category {
        font-size: 0.7rem;
    }
}

/* Hide/show animation for row view */
.participant-row-item.hidden {
    display: none;
}

.participant-row-item.show {
    animation: fadeInRow 0.3s ease;
}

@keyframes fadeInRow {
    from {
        opacity: 0;
        transform: translateX(-10px);
    }
    to {
        opacity: 1;
        transform: translateX(0);
    }
}

/* Scrollbar styling for row view */
.participant-row-container::-webkit-scrollbar {
    width: 8px;
}

.participant-row-container::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 4px;
}

.participant-row-container::-webkit-scrollbar-thumb {
    background: linear-gradient(135deg, #6c757d 0%, #495057 100%);
    border-radius: 4px;
}

.participant-row-container::-webkit-scrollbar-thumb:hover {
    background: linear-gradient(135deg, #495057 0%, #343a40 100%);
}

/* Ensure both views share the same container styling */
.participant-display-container {
    position: relative;
}
/* Modern Participant Grid Styling */
.participant-grid-container {
    position: relative;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    border: 2px solid #e9ecef;
    background: #f8f9fa;
    max-height: 600px;
    overflow-y: auto;
}

.participant-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 12px;
    padding: 16px;
}

.participant-card-item {
    background: white;
    border-radius: 12px;
    padding: 16px;
    border: 2px solid #e9ecef;
    cursor: pointer;
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;
}

.participant-card-item:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(0, 123, 255, 0.15);
    border-color: #007bff;
}

.participant-card-item.selected {
    background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
    color: white;
    border-color: #0056b3;
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(0, 123, 255, 0.3);
}

.participant-card-item.already-assigned {
    border-left: 4px solid #28a745;
    background: linear-gradient(135deg, #f8fffa 0%, #e8f5e8 100%);
}

.participant-card-item.already-assigned.selected {
    background: linear-gradient(135deg, #28a745 0%, #1e7e34 100%);
}

.participant-card-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 12px;
    position: relative;
}

.participant-bib-badge {
    background: linear-gradient(135deg, #6c757d 0%, #495057 100%);
    color: white;
    padding: 6px 12px;
    border-radius: 20px;
    font-size: 0.8rem;
    font-weight: bold;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    min-width: 50px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.participant-card-item.selected .participant-bib-badge {
    background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
    color: #007bff;
}

.participant-selection-indicator {
    position: absolute;
    top: -8px;
    right: -8px;
    background: #28a745;
    color: white;
    width: 24px;
    height: 24px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 0.7rem;
    opacity: 0;
    transform: scale(0);
    transition: all 0.3s ease;
    border: 2px solid white;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

.participant-card-item.selected .participant-selection-indicator {
    opacity: 1;
    transform: scale(1);
}

.assignment-indicator {
    background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
    color: white;
    padding: 2px 8px;
    border-radius: 12px;
    font-size: 0.7rem;
    font-weight: bold;
    display: flex;
    align-items: center;
    gap: 4px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.participant-card-item.selected .assignment-indicator {
    background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
    color: #28a745;
}

.participant-card-body {
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.participant-name {
    font-weight: 600;
    font-size: 1rem;
    color: #212529;
    line-height: 1.2;
}

.participant-card-item.selected .participant-name {
    color: white;
    font-weight: 700;
}

.participant-details-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 8px;
}

.detail-badge {
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 0.75rem;
    padding: 4px 8px;
    border-radius: 8px;
    background: rgba(108, 117, 125, 0.1);
    color: #6c757d;
    transition: all 0.2s ease;
}

.detail-badge i {
    width: 12px;
    text-align: center;
}

.detail-badge span {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.table-participants td{
    vertical-align: middle;
}
.table-responsive {
    position: relative;
    overflow: auto;
    max-height: 70vh;
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
}
.detail-badge.club {
    background: #343a4012;
    color: #343a40;
}
td .detail-badge {
    display: inline-block;
}
.detail-badge.category {
    background: #1987541c;
    color: #198754;
}

.detail-badge.gender {
    background: rgba(220, 53, 69, 0.1);
    color: #dc3545;
}
.detail-badge.gender-male {
    background: lch(49 81.77 283.4 / 0.1);
    color: #0d6efd;
}
.detail-badge.year {
    background: rgba(108, 117, 125, 0.1);
    color: #6c757d;
}

.participant-card-item.selected .detail-badge {
    background: rgba(255, 255, 255, 0.2);
    color: rgba(255, 255, 255, 0.9);
}

.no-participants-message {
    background: white;
    border-radius: 12px;
    margin: 16px;
}

.participant-select-footer {
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    padding: 12px 16px;
    border-top: 1px solid #dee2e6;
}

/* Search bar styling */
.input-group .input-group-text {
    background: white;
    border-color: #ced4da;
}

#participantSearch {
    border-color: #ced4da;
}

#participantSearch:focus {
    border-color: #007bff;
    box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
}

/* Selection status badge animation */
#participantStatusBadge {
    transition: all 0.3s ease;
}

#participantStatusBadge.has-selection {
    background: linear-gradient(135deg, #28a745 0%, #20c997 100%) !important;
    animation: pulse 1s ease-in-out;
}

@keyframes pulse {
    0% { transform: scale(1); }
    50% { transform: scale(1.1); }
    100% { transform: scale(1); }
}

/* Hide/show animation */
.participant-card-item.hidden {
    display: none;
}

.participant-card-item.show {
    animation: fadeInUp 0.3s ease;
}

@keyframes fadeInUp {
    from {
        opacity: 0;
        transform: translateY(20px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

/* Responsive design */
@media (max-width: 768px) {
    .participant-grid {
        grid-template-columns: 1fr;
        gap: 8px;
        padding: 12px;
    }
    
    .participant-card-item {
        padding: 12px;
    }
    
    .participant-details-grid {
        grid-template-columns: 1fr;
        gap: 6px;
    }
    
    .participant-bib-badge {
        font-size: 0.7rem;
        padding: 4px 8px;
        min-width: 40px;
    }
}

@media (max-width: 576px) {
    .participant-grid-container {
        max-height: 400px;
    }
    
    .participant-card-header {
        margin-bottom: 8px;
    }
    
    .participant-name {
        font-size: 0.9rem;
    }
    
    .detail-badge {
        font-size: 0.7rem;
        padding: 3px 6px;
    }
}

/* Scrollbar styling */
.participant-grid-container::-webkit-scrollbar {
    width: 8px;
}

.participant-grid-container::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 4px;
}

.participant-grid-container::-webkit-scrollbar-thumb {
    background: linear-gradient(135deg, #6c757d 0%, #495057 100%);
    border-radius: 4px;
}

.participant-grid-container::-webkit-scrollbar-thumb:hover {
    background: linear-gradient(135deg, #495057 0%, #343a40 100%);
}
</style>
<script>
jQuery(function() {
    jQuery("#reorder-table tbody").sortable({
        helper: fixWidthHelper,
        update: function(event, ui) {
            const order = jQuery("#reorder-table tbody tr").map(function() {
                return jQuery(this).data("id");
            }).get();

            jQuery.ajax({
                url: "save_reorder.php",
                method: "POST",
                data: { order: order },
                success: function(response) {
                    console.log("Saved order:", order);
                    console.log("Saved order:", response);
                }
            });
        }
    }).disableSelection();

    function fixWidthHelper(e, ui) {
        ui.children().each(function() {
            jQuery(this).width(jQuery(this).width());
        });
        return ui;
    }
});
jQuery(function () {
    const $tbody = jQuery("#reorder-table tbody");

    $tbody.sortable({
        helper: function (e, item) {
            let selected = item.closest('tbody').find('input.bulk-check:checked').closest('tr');

            // If the dragged row is not selected, deselect others
            if (!item.find('input.bulk-check').is(':checked')) {
                selected = item;
                $tbody.find('input.bulk-check').prop('checked', false);
                item.find('input.bulk-check').prop('checked', true);
            }

            // Clone all selected rows for visual feedback
            const helper = jQuery('<tbody/>');
            selected.each(function () {
                helper.append(jQuery(this).clone().css('background', '#f0f0f0'));
            });

            item.data('multidrag', selected); // Store original selection
            return helper;
        },
        start: function (e, ui) {
            const selected = ui.item.data('multidrag');
            selected.css('opacity', 0.5);
        },
        stop: function (e, ui) {
            const selected = ui.item.data('multidrag');
            const targetIndex = ui.item.index();

            // Move all selected rows to the new index
            selected.css('opacity', 1);
            selected.detach();

            if (targetIndex === 0) {
                $tbody.prepend(selected);
            } else {
                $tbody.find('tr').eq(targetIndex - 1).after(selected);
            }

            // Send new order via AJAX
            const newOrder = $tbody.find('tr').map(function () {
                return jQuery(this).data("id");
            }).get();

            jQuery.ajax({
                url: "save_reorder.php",
                method: "POST",
                data: { order: newOrder },
                success: function (response) {
                    console.log("New order saved", newOrder);
                }
            });
        },
        cancel: 'input,button',
        items: '> tr'
    });
});
jQuery('#reverseSelectedBtn').on('click', function () {
    const $tbody = jQuery('#reorder-table tbody');
    const $selectedRows = $tbody.find('tr:visible').has('input.bulk-check:checked');

    if ($selectedRows.length < 2) {
        alert('Select at least 2 rows to reverse.');
        return;
    }

    // Get index of the first selected row
    const firstIndex = $selectedRows.first().index();

    // Detach and reverse
    const $reversed = jQuery($selectedRows.get().reverse());
    $selectedRows.remove();
    if (firstIndex === 0) {
        $tbody.prepend($reversed);
    } else {
        $tbody.find('tr').eq(firstIndex - 1).after($reversed);
    }

    // Renumber serials
    let serial = 1;
    $tbody.find('tr:visible').each(function () {
        jQuery(this).find('.serial-number').text(serial++);
    });

    // Save new order via AJAX
    const newOrder = $tbody.find('tr').map(function () {
        return jQuery(this).data('id');
    }).get();

    jQuery.ajax({
        url: 'save_reorder.php',
        method: 'POST',
        data: { order: newOrder },
        success: function (res) {
            console.log('Reversed order saved');
        }
    });
});
jQuery('#shuffleSelectedBtn').on('click', function () {
    const $tbody = jQuery('#reorder-table tbody');
    const $selectedRows = $tbody.find('tr:visible').has('input.bulk-check:checked');

    if ($selectedRows.length < 2) {
        alert('Select at least 2 rows to shuffle.');
        return;
    }

    // Get index of first selected row
    const firstIndex = $selectedRows.first().index();

    // Convert selected rows to array and shuffle it
    const rowsArray = $selectedRows.get();
    for (let i = rowsArray.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [rowsArray[i], rowsArray[j]] = [rowsArray[j], rowsArray[i]];
    }

    const $shuffled = jQuery(rowsArray);
    $selectedRows.remove();

    if (firstIndex === 0) {
        $tbody.prepend($shuffled);
    } else {
        $tbody.find('tr').eq(firstIndex - 1).after($shuffled);
    }

    // Renumber serials
    let serial = 1;
    $tbody.find('tr:visible').each(function () {
        jQuery(this).find('.serial-number').text(serial++);
    });

    // Save new order via AJAX
    const newOrder = $tbody.find('tr').map(function () {
        return jQuery(this).data('id');
    }).get();

    jQuery.ajax({
        url: 'save_reorder.php',
        method: 'POST',
        data: { order: newOrder },
        success: function (res) {
            console.log('Shuffled order saved');
            $shuffled.addClass('shuffled');
setTimeout(() => $shuffled.removeClass('shuffled'), 600);

        }
    });
});
function sortSelectedRows(comparator) {
    const $tbody = jQuery('#reorder-table tbody');
    const $selectedRows = $tbody.find('tr:visible').has('input.bulk-check:checked');

    if ($selectedRows.length < 2) {
        alert('Select at least 2 rows to sort.');
        return;
    }

    const firstIndex = $selectedRows.first().index();
    const rowsArray = $selectedRows.get();

    rowsArray.sort(comparator);
    const $sorted = jQuery(rowsArray);
    $selectedRows.remove();

    if (firstIndex === 0) {
        $tbody.prepend($sorted);
    } else {
        $tbody.find('tr').eq(firstIndex - 1).after($sorted);
    }

    // Renumber serials
    let serial = 1;
    $tbody.find('tr:visible').each(function () {
        jQuery(this).find('.serial-number').text(serial++);
    });

    // Save new order
    const newOrder = $tbody.find('tr').map(function () {
        return jQuery(this).data('id');
    }).get();

    jQuery.ajax({
        url: 'save_reorder.php',
        method: 'POST',
        data: { order: newOrder },
        success: function (res) {
            console.log('Sorted order saved');
        }
    });
}

// Sort Alphabetically (Last + First)
jQuery('#sortByNameBtn').on('click', function () {
    sortSelectedRows(function (a, b) {
        const nameA = jQuery(a).find('td').eq(3).text().toLowerCase();
        const nameB = jQuery(b).find('td').eq(3).text().toLowerCase();
        return nameA.localeCompare(nameB);
    });
});

// Sort by bib (numerically)
jQuery('#sortBybibBtn').on('click', function () {
    sortSelectedRows(function (a, b) {
        const bibA = parseInt(jQuery(a).find('td').eq(2).text(), 10);
        const bibB = parseInt(jQuery(b).find('td').eq(2).text(), 10);
        return bibA - bibB;
    });
});

// Sort by Year (youngest last)
jQuery('#sortByYearBtn').on('click', function () {
    sortSelectedRows(function (a, b) {
        const yearA = parseInt(jQuery(a).data('year'), 10);
        const yearB = parseInt(jQuery(b).data('year'), 10);
        return yearA - yearB;
    });
});

</script>
<script>
// Enhanced AJAX assignment with better UX
jQuery('#ajaxAssignBtn').on('click', function () {
    const $btn = jQuery(this);
    const form = jQuery('#ajaxAssignForm');
    const eventId = form.data('event');
    const heatNumber = form.find('[name=heat_number]').val();
    const participants = form.find('[name="participant_ids[]"] option:selected').map(function () {
        return this.value;
    }).get();

    if (!heatNumber) {
        alert('Please select a heat first.');
        document.getElementById('heat_number').focus();
        return;
    }
    
    if (participants.length === 0) {
        alert('Please select at least one participant to assign.');
        document.getElementById('participantSelect').focus();
        return;
    }

    // Show loading state
    $btn.addClass('loading').prop('disabled', true);
    const originalText = $btn.html();

    jQuery.ajax({
        url: 'ajax_assing.php',
        method: 'POST',
        data: {
            event_id: eventId,
            heat_number: heatNumber,
            participant_ids: participants
        },
        dataType: 'json',
        success: function (response) {
            if (response.status === 'success') {
                // Show success message
                $btn.removeClass('loading btn-success').addClass('btn-outline-success').html('<i class="fas fa-check me-2"></i>Success!');
                
                // Show detailed success message
                const participantCount = participants.length;
                const heatName = jQuery('#heat_number option:selected').text();
                
                alert(`✅ Successfully assigned ${participantCount} participant(s) to ${heatName}!\n\n${response.message}`);
                
                // Reload page after short delay
                setTimeout(() => {
                    window.location.reload();
                }, 1000);
            } else {
                throw new Error(response.message || 'Assignment failed');
            }
        },
        error: function (xhr, status, error) {
            console.error('AJAX Error:', xhr.responseText);
            let errorMessage = 'Assignment failed. Please try again.';
            
            try {
                const response = JSON.parse(xhr.responseText);
                errorMessage = response.message || errorMessage;
            } catch (e) {
                if (xhr.responseText) {
                    errorMessage = 'Server error: ' + xhr.responseText.substring(0, 100);
                }
            }
            
            alert('❌ Error: ' + errorMessage);
        },
        complete: function () {
            // Restore button state
            $btn.removeClass('loading').prop('disabled', false);
            if (!$btn.hasClass('btn-outline-success')) {
                $btn.html(originalText);
            }
        }
    });
});

// Auto-clear selection after successful assignment
function clearFormAfterSuccess() {
    document.getElementById('heat_number').value = '';
    clearSelection();
    clearAllFilters();
}
</script>
<script>
    jQuery(document).ready(function () {
    // Master "select all" checkbox — only visible rows
    jQuery('#bulk-check-master').on('change', function () {
        const checked = this.checked;
        jQuery('#reorder-table tbody tr:visible .bulk-check').each(function () {
            this.checked = checked;
            jQuery(this).closest('tr').toggleClass('selected-row', checked);
        });
    });

    // Toggle row highlight on individual row selection
    jQuery(document).on('change', '.bulk-check', function () {
        jQuery(this).closest('tr').toggleClass('selected-row', this.checked);
    });
});
    </script>
   

    <div class="modal fade" id="assignbibModal" tabindex="-1" aria-labelledby="assignbibModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <form id="assignbibForm">
        <div class="modal-header">
          <h5 class="modal-title" id="assignbibModalLabel">Assign bib Numbers</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <div class="mb-3">
            <label for="bib_series_id" class="form-label">Select bib Series</label>
            <select name="bib_series_id" id="bib_series_id" class="form-select" required>
              <option value="">-- Choose Series --</option>
              <?php foreach ($bib_series as $series): ?>
                <option value="<?= $series['id'] ?>" data-start="<?= $series['start_number'] ?>" data-end="<?= $series['end_number'] ?>">
                  <?= htmlspecialchars($series['name']) ?> (<?= $series['start_number'] ?>–<?= $series['end_number'] ?>)
                </option>
              <?php endforeach; ?>
            </select>
          </div>
          
          <div class="mb-3">
            <label for="start_number" class="form-label">Start bib Number</label>
            <input type="number" name="start_number" id="start_number" class="form-control" placeholder="Auto from series" min="1">
            <small class="form-text text-muted">Leave empty to use next available from series</small>
          </div>
          
          <div class="form-check mb-3">
            <input type="checkbox" name="overwrite_existing" id="overwrite_existing" class="form-check-input">
            <label class="form-check-label" for="overwrite_existing">
              Overwrite existing bib numbers
            </label>
            <small class="form-text text-muted d-block">If unchecked, only participants without bib will be assigned</small>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
          <button type="submit" class="btn btn-primary">Assign bibs</button>
        </div>
      </form>
    </div>
  </div>
</div>
 <script>
// Auto-fill start number when series is selected
jQuery('#bib_series_id').on('change', function() {
    const selectedOption = jQuery(this).find('option:selected');
    const startNumber = selectedOption.data('start');
    if (startNumber) {
        jQuery('#start_number').attr('placeholder', 'Auto from series (' + startNumber + ')');
    }
});
// Replace the old #promoteToHeatBtn handler with this:
jQuery('#promoteToHeatBtn').on('click', function () {
    jQuery('#promoteToHeatModal').modal('show');
});


jQuery('#assignbibForm').on('submit', function (e) {
    e.preventDefault();

    const selectedIds = jQuery('#reorder-table tbody tr:visible .bulk-check:checked')
        .map(function () {
            return jQuery(this).val();
        }).get();

    const seriesId = jQuery('#bib_series_id').val();
    const startNumber = jQuery('#start_number').val();
    const overwriteExisting = jQuery('#overwrite_existing').is(':checked');
    const eventId = <?= json_encode($selected_event) ?>;

    if (!seriesId || selectedIds.length === 0) {
        alert('Please select at least one participant and a bib series.');
        return;
    }

    jQuery.ajax({
        url: 'ajax_assign_bib.php',
        method: 'POST',
        data: {
            participant_ids: selectedIds,
            bib_series_id: seriesId,
            start_number: startNumber,
            overwrite_existing: overwriteExisting ? 1 : 0,
            event_id: eventId
        },
        success: function (response) {
            try {
                const res = JSON.parse(response);
                if (res.status === 'success') {
                    alert(res.message);
                    location.reload();
                } else {
                    alert(res.message || 'An error occurred.');
                }
            } catch (e) {
                alert('Invalid response.');
                console.error(response);
            }
        },
        error: function () {
            alert('AJAX request failed.');
        }
    });
});
</script>

<!-- Drag-and-Drop Heat Assignment Modal -->
<div class="modal fade" id="dragDropHeatModal" tabindex="-1" aria-labelledby="dragDropHeatModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header bg-primary text-white">
        <h5 class="modal-title" id="dragDropHeatModalLabel">
          <i class="fas fa-fire me-2"></i>Assign to Heat
        </h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <div class="mb-3">
          <label class="form-label fw-bold">
            <span id="dragDropParticipantCount">1</span> Participant<span id="dragDropParticipantPlural">s</span>:
          </label>
          <div id="dragDropParticipantInfo" class="p-2 bg-light rounded" style="max-height: 200px; overflow-y: auto;">
            <!-- Participant list will be populated here -->
          </div>
        </div>
        <div class="mb-3">
          <label for="dragDropHeatSelect" class="form-label fw-bold">
            <i class="fas fa-fire me-1"></i>Select Heat:
          </label>
          <select id="dragDropHeatSelect" class="form-select">
            <option value="">-- Select Heat --</option>
            <?php foreach ($heat_options as $heat): ?>
              <option value="<?= $heat['heat_number'] ?>">
                Heat <?= $heat['heat_number'] ?><?= $heat['heat_name'] ? ' – ' . htmlspecialchars($heat['heat_name']) : '' ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
          <i class="fas fa-times me-1"></i>Cancel
        </button>
        <button type="button" id="dragDropAssignBtn" class="btn btn-success">
          <i class="fas fa-user-plus me-1"></i>Assign to Heat
        </button>
      </div>
    </div>
  </div>
</div>

<script>
// Drag-and-Drop functionality for participant assignment (supports multiple selection)
document.addEventListener('DOMContentLoaded', function() {
    let draggedParticipantIds = [];
    let draggedParticipants = [];
    
    // Make participant table rows draggable
    const participantRows = document.querySelectorAll('#participantsTable tbody .participant-row');
    participantRows.forEach(row => {
        row.setAttribute('draggable', 'true');
        
        row.addEventListener('dragstart', function(e) {
            // Check if there are selected checkboxes
            const selectedCheckboxes = document.querySelectorAll('#participantsTable tbody .participant-checkbox:checked');
            
            if (selectedCheckboxes.length > 0) {
                // Drag multiple selected participants
                draggedParticipantIds = [];
                draggedParticipants = [];
                
                selectedCheckboxes.forEach(checkbox => {
                    const participantRow = checkbox.closest('.participant-row');
                    if (participantRow) {
                        const participantId = participantRow.dataset.id;
                        const lastName = participantRow.querySelector('td:nth-child(3) .fw-bold')?.textContent || '';
                        const bib = participantRow.querySelector('.css-bib .badge')?.textContent || '';
                        const category = participantRow.dataset.category || '';
                        const gender = participantRow.dataset.gender || '';
                        const year = participantRow.dataset.year || '';
                        
                        draggedParticipantIds.push(participantId);
                        draggedParticipants.push({
                            id: participantId,
                            name: lastName,
                            bib: bib,
                            category: category,
                            gender: gender,
                            year: year
                        });
                    }
                });
                
                // Visual feedback for all selected rows
                selectedCheckboxes.forEach(checkbox => {
                    const row = checkbox.closest('.participant-row');
                    if (row) row.style.opacity = '0.5';
                });
            } else {
                // Drag single participant (the one being dragged)
                draggedParticipantIds = [this.dataset.id];
                const lastName = this.querySelector('td:nth-child(3) .fw-bold')?.textContent || '';
                const bib = this.querySelector('.css-bib .badge')?.textContent || '';
                const category = this.dataset.category || '';
                const gender = this.dataset.gender || '';
                const year = this.dataset.year || '';
                
                draggedParticipants = [{
                    id: this.dataset.id,
                    name: lastName,
                    bib: bib,
                    category: category,
                    gender: gender,
                    year: year
                }];
                
                // Visual feedback
                this.style.opacity = '0.5';
            }
            
            e.dataTransfer.effectAllowed = 'copy';
            e.dataTransfer.setData('text/html', this.innerHTML);
        });
        
        row.addEventListener('dragend', function(e) {
            // Reset opacity for all rows
            document.querySelectorAll('#participantsTable tbody .participant-row').forEach(r => {
                r.style.opacity = '1';
            });
        });
    });
    
    // Make reorder-table a drop target
    const reorderTable = document.querySelector('#reorder-table tbody');
    if (reorderTable) {
        reorderTable.addEventListener('dragover', function(e) {
            e.preventDefault();
            e.dataTransfer.dropEffect = 'copy';
            this.style.backgroundColor = '#e3f2fd';
        });
        
        reorderTable.addEventListener('dragleave', function(e) {
            this.style.backgroundColor = '';
        });
        
        reorderTable.addEventListener('drop', function(e) {
            e.preventDefault();
            this.style.backgroundColor = '';
            
            if (draggedParticipantIds.length > 0) {
                // Update participant count
                const count = draggedParticipants.length;
                document.getElementById('dragDropParticipantCount').textContent = count;
                document.getElementById('dragDropParticipantPlural').textContent = count === 1 ? '' : 's';
                
                // Populate modal with participant info
                const infoContainer = document.getElementById('dragDropParticipantInfo');
                infoContainer.innerHTML = '';
                
                draggedParticipants.forEach((participant, index) => {
                    const participantDiv = document.createElement('div');
                    participantDiv.className = 'mb-2 pb-2' + (index < draggedParticipants.length - 1 ? ' border-bottom' : '');
                    participantDiv.innerHTML = '<div class="fw-bold">' + participant.name + '</div>' +
                        '<small class="text-muted">BIB: ' + participant.bib + ' | ' + 
                        participant.category + ' | ' + participant.gender + ' | ' + participant.year + '</small>';
                    infoContainer.appendChild(participantDiv);
                });
                
                // Show modal
                const modal = new bootstrap.Modal(document.getElementById('dragDropHeatModal'));
                modal.show();
            }
        });
    }
    
    // Handle assignment button click
    document.getElementById('dragDropAssignBtn').addEventListener('click', function() {
        const heatNumber = document.getElementById('dragDropHeatSelect').value;
        const eventId = <?= json_encode($selected_event) ?>;
        
        if (!heatNumber) {
            alert('Please select a heat.');
            return;
        }
        
        if (draggedParticipantIds.length === 0) {
            alert('No participants selected.');
            return;
        }
        
        // Disable button during processing
        const btn = this;
        btn.disabled = true;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>Assigning...';
        
        // Assign all participants sequentially
        let assignedCount = 0;
        let errorCount = 0;
        
        const assignParticipant = (index) => {
            if (index >= draggedParticipantIds.length) {
                // All done
                btn.disabled = false;
                btn.innerHTML = '<i class="fas fa-user-plus me-1"></i>Assign to Heat';
                
                if (errorCount === 0) {
                    bootstrap.Modal.getInstance(document.getElementById('dragDropHeatModal')).hide();
                    alert('Successfully assigned ' + assignedCount + ' participant(s) to heat ' + heatNumber);
                    location.reload();
                } else {
                    alert('Assigned ' + assignedCount + ' participant(s). ' + errorCount + ' failed.');
                    location.reload();
                }
                return;
            }
            
            const participantId = draggedParticipantIds[index];
            
            fetch('heats_configure.php?event_id=' + eventId, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'participant_id=' + participantId + '&heat_number=' + heatNumber
            })
            .then(response => {
                if (response.ok) {
                    assignedCount++;
                } else {
                    errorCount++;
                }
                assignParticipant(index + 1);
            })
            .catch(error => {
                console.error('Error:', error);
                errorCount++;
                assignParticipant(index + 1);
            });
        };
        
        assignParticipant(0);
    });
    
    // Reset modal when closed
    document.getElementById('dragDropHeatModal').addEventListener('hidden.bs.modal', function() {
        document.getElementById('dragDropHeatSelect').value = '';
        draggedParticipantIds = [];
        draggedParticipants = [];
        
        // Clear all checkboxes
        document.querySelectorAll('#participantsTable tbody .participant-checkbox:checked').forEach(checkbox => {
            checkbox.checked = false;
        });
    });
});
</script>

<!-- Add this modal after the Move to Heat Modal -->
<div class="modal fade" id="promoteToHeatModal" tabindex="-1" aria-labelledby="promoteToHeatModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <form id="promoteToHeatForm">
        <div class="modal-header">
          <h5 class="modal-title" id="promoteToHeatModalLabel">Promote Participants to Heat</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <div class="mb-3">
            <label for="promote_target_heat" class="form-label">Target Heat</label>
            <select name="promote_target_heat" id="promote_target_heat" class="form-select" required>
              <option value="">-- Select Heat --</option>
              <?php foreach ($heat_options as $heat): ?>
                <option value="<?= $heat['heat_number'] ?>">
                  <?= $heat['heat_number'] ?><?= $heat['heat_name'] ? ' – ' . htmlspecialchars($heat['heat_name']) : '' ?>
                </option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="alert alert-warning">
            <small>
              Participants will be promoted to the selected heat based on promotion logic/results.
            </small>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
          <button type="submit" class="btn btn-warning">Promote to Heat</button>
        </div>
      </form>
    </div>
  </div>
</div>
<!-- Move to Heat Modal -->
<div class="modal fade" id="moveToHeatModal" tabindex="-1" aria-labelledby="moveToHeatModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <form id="moveToHeatForm">
        <div class="modal-header">
          <h5 class="modal-title" id="moveToHeatModalLabel">Move/Copy Selected to Heat</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <div class="mb-3">
            <label for="target_heat_number" class="form-label">Target Heat</label>
            <select name="target_heat_number" id="target_heat_number" class="form-select" required>
              <option value="">-- Select Heat --</option>
              <?php foreach ($heat_options as $heat): ?>
                <option value="<?= $heat['heat_number'] ?>">
                  <?= $heat['heat_number'] ?><?= $heat['heat_name'] ? ' – ' . htmlspecialchars($heat['heat_name']) : '' ?>
                </option>
              <?php endforeach; ?>
            </select>
          </div>
          
          <div class="mb-3">
            <label class="form-label">Action</label>
            <div class="form-check">
              <input type="radio" name="action_type" id="action_move" value="move" class="form-check-input" checked>
              <label class="form-check-label" for="action_move">
                <strong>Move</strong> - Transfer participants to target heat (remove from current heat)
              </label>
            </div>
            <div class="form-check">
              <input type="radio" name="action_type" id="action_copy" value="copy" class="form-check-input">
              <label class="form-check-label" for="action_copy">
                <strong>Copy</strong> - Duplicate participants in target heat (keep in current heat)
              </label>
            </div>            
          </div>
          
          <div class="alert alert-info">
            <small id="actionDescription">Selected participants will be moved to the target heat.</small>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
          <button type="submit" class="btn btn-primary" id="actionSubmitBtn">Move to Heat</button>
        </div>
      </form>
    </div>
  </div>
</div>
<script>
    jQuery('#promoteToHeatForm').on('submit', function (e) {
    e.preventDefault();

    const targetHeat = jQuery('#promote_target_heat').val();
    const eventId = <?= json_encode($selected_event) ?>;

    if (!targetHeat) {
        alert('Please select a target heat.');
        return;
    }

    if (!confirm(`Promote participants to Heat ${targetHeat}?`)) return;

    const $btn = jQuery('#promoteToHeatForm button[type="submit"]');
    $btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin me-1"></i>Promoting...');

    jQuery.ajax({
        url: '../api/summary_table_api.php',
        method: 'GET',
        data: {
            action: 'promote',
            event_id: eventId,
            target_heat: targetHeat
        },
        dataType: 'json',
        success: function (response) {
            alert((response.status === 'success' ? '✅ ' : '❌ ') + response.message);
            if (response.status === 'success') {
                location.reload();
            }
        },
        error: function (xhr) {
            alert('AJAX error: ' + xhr.responseText);
        },
        complete: function () {
            $btn.prop('disabled', false).html('Promote to Heat');
            jQuery('#promoteToHeatModal').modal('hide');
        }
    });
});</script>
<script>
// Update action description and button text based on selected radio
jQuery('input[name="action_type"]').on('change', function() {
    const actionType = jQuery(this).val();
    const description = jQuery('#actionDescription');
    const submitBtn = jQuery('#actionSubmitBtn');
    
    if (actionType === 'move') {
        description.text('Selected participants will be moved to the target heat.');
        submitBtn.text('Move to Heat');
        submitBtn.removeClass('btn-success').addClass('btn-primary');
    } else if (actionType === 'copy') {
        description.text('Selected participants will be copied to the target heat (originals remain).');
        submitBtn.text('Copy to Heat');
        submitBtn.removeClass('btn-primary').addClass('btn-success');
    } else if (actionType === 'promote') {
        description.text('Participants will be promoted to the target heat based on heat flow settings and results from the linked heat.');
        submitBtn.text('Promote to Heat');
        submitBtn.removeClass('btn-primary btn-success').addClass('btn-warning');
    }
});

jQuery('#moveToHeatForm').on('submit', function (e) {
    e.preventDefault();

    const selectedIds = jQuery('#reorder-table tbody tr:visible .bulk-check:checked')
        .map(function () {
            return jQuery(this).val(); // This gets the event_participants.id
        }).get();

    const targetHeat = jQuery('#target_heat_number').val();
    const actionType = jQuery('input[name="action_type"]:checked').val();
    const eventId = <?= json_encode($selected_event) ?>;

    if (!targetHeat) {
        alert('Please select a target heat.');
        return;
    }
    if (actionType !== 'promote' && selectedIds.length === 0) {
        alert('Please select at least one participant.');
        return;
    }

    if (!targetHeat || selectedIds.length === 0) {
        alert('Please select a target heat and at least one participant.');
        return;
    }

    const actionText = actionType === 'move' ? 'move' : 'copy';
    if (!confirm(`${actionText.charAt(0).toUpperCase() + actionText.slice(1)} ${selectedIds.length} selected participants to Heat ${targetHeat}?`)) {
        return;
    }

    jQuery.ajax({
        url: 'ajax_move_to_heat.php',
        method: 'POST',
        data: {
            event_participant_ids: selectedIds,
            target_heat: targetHeat,
            action_type: actionType,
            event_id: eventId
        },
        dataType: 'json',
        success: function (response) {
            if (response.status === 'success') {
                alert(response.message);
                jQuery('#moveToHeatModal').modal('hide');
                location.reload();
            } else {
                alert('Error: ' + response.message);
            }
        },
        error: function (xhr, status, error) {
            alert('AJAX request failed: ' + error);
            console.error(xhr.responseText);
        }
    });
});
</script>

        <!-- Help Modal for Configure Heats -->
        <div class="modal fade" id="heatsConfigureHelpModal" tabindex="-1" aria-labelledby="heatsConfigureHelpLabel" aria-hidden="true">
            <div class="modal-dialog modal-xl modal-dialog-scrollable">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="heatsConfigureHelpLabel"><i class="fas fa-question-circle me-2"></i>Configure Heats — Help</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body p-0" style="height:70vh;">
                        <iframe id="heatsConfigureHelpFrame" src="../help/heats_configure_help.html" style="border:0;width:100%;height:100%;"></iframe>
                    </div>
                </div>
            </div>
        </div>
        <script>
            function openHeatsConfigureHelp(){
                var frame = document.getElementById('heatsConfigureHelpFrame');
                if(frame && !frame.src){
                    frame.src = '../help/heats_configure_help.html';
                }
                var modalEl = document.getElementById('heatsConfigureHelpModal');
                if(window.bootstrap && modalEl){
                    var modal = bootstrap.Modal.getOrCreateInstance(modalEl);
                    modal.show();
                } else if (modalEl){
                    // Fallback for older Bootstrap bindings
                    try { jQuery(modalEl).modal('show'); } catch(e) {}
                }
            }
        </script>

        <?php include 'footer.php'; ?>
    </body>
    </html>
