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

$message = '';
// Handle export error messages
if (isset($_GET['error'])) {
    $message = '<div class="alert alert-danger alert alert-dismissible fade show" role="alert">
                    <i class="fas fa-exclamation-triangle me-2"></i>' . htmlspecialchars($_GET['error']) . '
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>';
}
// Get events for dropdown
$events = $pdo->query("SELECT id, name, date FROM events ORDER BY date DESC")->fetchAll(PDO::FETCH_ASSOC);

// Get heats for dropdown (you'll need this for the modal)
$heats = $pdo->query("SELECT id, heat_number, heat_name, event_id FROM event_heat_settings ORDER BY event_id, heat_number")->fetchAll(PDO::FETCH_ASSOC);


// Enhanced Assignment Handler
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['assign_to_event'])) {
    $participant_ids = $_POST['participant_ids'] ?? [];
    $event_id = $_POST['event_id'] ?? null;
    $assign_to_event_participants = isset($_POST['assign_to_event_participants']);
    $heat_number = $_POST['heat_number'] ?? null;
    $category = $_POST['category'] ?? '';
    
    if (!$event_id || empty($participant_ids)) {
        $message = '<div class="alert alert-danger alert alert-dismissible fade show" role="alert">
                        <i class="fas fa-exclamation-triangle me-2"></i>Please select an event and at least one participant.
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>';
    } else {
        try {
            $pdo->beginTransaction();
            
            $success_count = 0;
            $already_assigned_count = 0;
            $error_count = 0;
            $assignment_details = [];
            
            // Get event details
            $event_stmt = $pdo->prepare("SELECT name FROM events WHERE id = ?");
            $event_stmt->execute([$event_id]);
            $event_info = $event_stmt->fetch();
            $event_name = $event_info ? $event_info['name'] : 'Unknown Event';
            
            foreach ($participant_ids as $participant_id) {
                if (!$participant_id) continue;
                
                try {
                    // Get participant details
                    $participant_stmt = $pdo->prepare("SELECT first_name, last_name, bib, category FROM participants WHERE id = ?");
                    $participant_stmt->execute([$participant_id]);
                    $participant = $participant_stmt->fetch();
                    
                    if (!$participant) {
                        $error_count++;
                        continue;
                    }
                    
                    $participant_name = $participant['first_name'] . ' ' . $participant['last_name'];
                    $use_category = $category ?: $participant['category'];
                    
                    // 1. Always assign to participants_event (tracking table)
                    $tracking_stmt = $pdo->prepare("
                        INSERT IGNORE INTO participants_event (participant_id, event_id, imported_at) 
                        VALUES (?, ?, CURRENT_TIMESTAMP)
                    ");
                    $tracking_stmt->execute([$participant_id, $event_id]);
                    
                    // 2. Optionally assign to event_participants (heat assignments)
                    if ($assign_to_event_participants) {
                        // Check if already assigned to this event
                        $existing_assignment = $pdo->prepare("
                            SELECT id, heat_number FROM event_participants 
                            WHERE participant_id = ? AND event_id = ?
                        ");
                        $existing_assignment->execute([$participant_id, $event_id]);
                        $existing = $existing_assignment->fetch();
                        
                        if ($existing) {
                            $already_assigned_count++;
                            $assignment_details[] = [
                                'name' => $participant_name,
                                'bib' => $participant['bib'],
                                'status' => 'already_assigned',
                                'heat' => $existing['heat_number']
                            ];
                        } else {
                            // Insert into event_participants
                            $assignment_stmt = $pdo->prepare("
                                INSERT INTO event_participants 
                                (event_id, participant_id, bib_number, heat_number, category, created_at) 
                                VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP)
                            ");
                            $assignment_stmt->execute([
                                $event_id, 
                                $participant_id, 
                                $participant['bib'],
                                $heat_number,
                                $use_category
                            ]);
                            
                            $success_count++;
                            $assignment_details[] = [
                                'name' => $participant_name,
                                'bib' => $participant['bib'],
                                'status' => 'assigned',
                                'heat' => $heat_number
                            ];
                        }
                    } else {
                        // Just tracking assignment
                        $success_count++;
                        $assignment_details[] = [
                            'name' => $participant_name,
                            'bib' => $participant['bib'],
                            'status' => 'tracked',
                            'heat' => null
                        ];
                    }
                    
                } catch (Exception $e) {
                    $error_count++;
                    continue;
                }
            }
            
            $pdo->commit();
            
            // Generate comprehensive success message
            $message_parts = [];
            $message_class = 'success';
            
            if ($success_count > 0) {
                if ($assign_to_event_participants) {
                    $message_parts[] = "<strong>{$success_count} participants assigned to event</strong>";
                    if ($heat_number) {
                        $message_parts[] = "Assigned to Heat {$heat_number}";
                    }
                } else {
                    $message_parts[] = "<strong>{$success_count} participants tracked for event</strong>";
                }
                $message_parts[] = "Event: <strong>{$event_name}</strong>";
            }
            
            if ($already_assigned_count > 0) {
                $message_parts[] = "{$already_assigned_count} participants were already assigned";
                $message_class = 'warning';
            }
            
            if ($error_count > 0) {
                $message_parts[] = "{$error_count} participants had errors";
                $message_class = 'warning';
            }
            
            $message = '<div class="alert alert-' . $message_class . ' alert alert-dismissible fade show" role="alert">
                            <div class="d-flex align-items-start">
                                <i class="fas fa-calendar-plus fa-lg me-3 mt-1"></i>
                                <div class="flex-grow-1">
                                    <h6 class="mb-2">Assignment Complete!</h6>
                                    <div>' . implode('<br>', $message_parts) . '</div>';
            
            // Show assignment details
            if (!empty($assignment_details)) {
                $detail_preview = array_slice($assignment_details, 0, 5);
                $message .= '<div class="mt-3 small">
                                <strong>Assignment Details:</strong><br>';
                
                foreach ($detail_preview as $detail) {
                    $status_icon = '';
                    $status_text = '';
                    
                    switch ($detail['status']) {
                        case 'assigned':
                            $status_icon = '<i class="fas fa-check text-success me-1"></i>';
                            $status_text = $detail['heat'] ? "Heat {$detail['heat']}" : 'Assigned';
                            break;
                        case 'already_assigned':
                            $status_icon = '<i class="fas fa-info text-warning me-1"></i>';
                            $status_text = $detail['heat'] ? "Already in Heat {$detail['heat']}" : 'Already assigned';
                            break;
                        case 'tracked':
                            $status_icon = '<i class="fas fa-eye text-info me-1"></i>';
                            $status_text = 'Tracked for event';
                            break;
                    }
                    
                    $message .= "<span class='badge bg-primary me-1'>{$detail['bib']}</span> {$detail['name']} - {$status_icon}{$status_text}<br>";
                }
                
                if (count($assignment_details) > 5) {
                    $message .= '... and ' . (count($assignment_details) - 5) . ' more participants.';
                }
                $message .= '</div>';
            }
            
            $message .= '</div>
                            </div>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>';
            
        } catch (Exception $e) {
            $pdo->rollBack();
            $message = '<div class="alert alert-danger alert alert-dismissible fade show" role="alert">
                            <i class="fas fa-exclamation-triangle me-2"></i>Assignment failed: ' . htmlspecialchars($e->getMessage()) . '
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>';
        }
    }
}

// Delete handler
if (isset($_GET['delete'])) {
    $pid = intval($_GET['delete']);
    
    // Delete from related tables first
    $pdo->prepare("DELETE FROM event_participants WHERE participant_id = ?")->execute([$pid]);
    $pdo->prepare("DELETE FROM participants_event WHERE participant_id = ?")->execute([$pid]);
    // Then delete from participants table
    $pdo->prepare("DELETE FROM participants WHERE id = ?")->execute([$pid]);
    
    $message = '<div class="alert alert-success alert alert-dismissible fade show" role="alert">
                    <i class="fas fa-check-circle me-2"></i>Participant deleted successfully.
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>';
}

// Delete all handler
if (isset($_GET['delete_all']) && $_GET['delete_all'] === '1') {
    $pdo->exec("DELETE FROM event_participants");
    $pdo->exec("DELETE FROM participants_event");
    $pdo->exec("DELETE FROM participants");
    $message = '<div class="alert alert-warning alert alert-dismissible fade show" role="alert">
                    <i class="fas fa-exclamation-triangle me-2"></i>All participants deleted.
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>';
}

// Filter parameters
$filter_gender = $_GET['gender'] ?? '';
$filter_category = $_GET['category'] ?? '';
$filter_event = $_GET['event'] ?? '';
$filter_imported = $_GET['imported'] ?? '';
$search = $_GET['search'] ?? '';

// Build query with event filtering
$where_clauses = [];
$params = [];

if ($filter_gender !== '') {
    $where_clauses[] = "p.gender = ?";
    $params[] = $filter_gender;
}

if ($filter_category !== '') {
    $where_clauses[] = "p.category = ?";
    $params[] = $filter_category;
}

if ($filter_event !== '') {
    if ($filter_event === 'not_assigned') {
        $where_clauses[] = "ep.event_id IS NULL AND pe.event_id IS NULL";
    } else {
        $where_clauses[] = "(ep.event_id = ? OR pe.event_id = ?)";
        $params[] = $filter_event;
        $params[] = $filter_event;
    }
}

if ($filter_imported !== '') {
    if ($filter_imported === 'yes') {
        $where_clauses[] = "pe.event_id IS NOT NULL";
    } else {
        $where_clauses[] = "pe.event_id IS NULL";
    }
}

if ($search !== '') {
    $where_clauses[] = "(p.first_name LIKE ? OR p.last_name LIKE ? OR p.bib LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

$where_sql = $where_clauses ? "WHERE " . implode(" AND ", $where_clauses) : "";

// Updated query to show participants with both event assignments and import tracking
$query = "SELECT p.*, 
                 GROUP_CONCAT(DISTINCT e1.name SEPARATOR ', ') as assigned_event_names,
                 GROUP_CONCAT(DISTINCT e1.id SEPARATOR ',') as assigned_event_ids,
                 GROUP_CONCAT(DISTINCT e2.name SEPARATOR ', ') as imported_event_names,
                 GROUP_CONCAT(DISTINCT e2.id SEPARATOR ',') as imported_event_ids
          FROM participants p
          LEFT JOIN event_participants ep ON p.id = ep.participant_id
          LEFT JOIN events e1 ON ep.event_id = e1.id
          LEFT JOIN participants_event pe ON p.id = pe.participant_id
          LEFT JOIN events e2 ON pe.event_id = e2.id
          $where_sql
          GROUP BY p.id
          ORDER BY p.id DESC";

$stmt = $pdo->prepare($query);
$stmt->execute($params);
$participants = $stmt->fetchAll(PDO::FETCH_ASSOC);


// Get distinct values for filters
$genders = $pdo->query("SELECT DISTINCT gender FROM participants WHERE gender IS NOT NULL AND gender != '' ORDER BY gender")->fetchAll(PDO::FETCH_COLUMN);
$categories = $pdo->query("SELECT DISTINCT category FROM participants WHERE category IS NOT NULL AND category != '' ORDER BY category")->fetchAll(PDO::FETCH_COLUMN);

// CSV Import handler with enhanced functionality
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['import_file'])) {
    $assign_event_id = $_POST['assign_event_id'] ?? null;
    $overwrite_duplicates = isset($_POST['overwrite_duplicates']);
    
    // Validate required fields
    if (!$assign_event_id) {
        $message = '<div class="alert alert-danger alert alert-dismissible fade show" role="alert">
                        <i class="fas fa-exclamation-triangle me-2"></i>Please select an event for import.
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>';
    } elseif (!isset($_FILES['import_file']) || $_FILES['import_file']['error'] !== UPLOAD_ERR_OK) {
        $message = '<div class="alert alert-danger alert alert-dismissible fade show" role="alert">
                        <i class="fas fa-exclamation-triangle me-2"></i>Please select a valid CSV file.
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>';
    } else {
        try {
            $file = $_FILES['import_file']['tmp_name'];
            $handle = fopen($file, 'r');
            
            if (!$handle) {
                throw new Exception('Could not open the uploaded file.');
            }
            
            // Skip header row if present
            $header = fgetcsv($handle, 1000, ',');
            
            // Initialize counters and tracking arrays
            $imported_count = 0;
            $updated_count = 0;
            $skipped_count = 0;
            $error_count = 0;
            $duplicate_participants = [];
            $error_details = [];
            $import_log = [];
            
            // Get event details for logging
            $event_stmt = $pdo->prepare("SELECT name FROM events WHERE id = ?");
            $event_stmt->execute([$assign_event_id]);
            $event_info = $event_stmt->fetch();
            $event_name = $event_info ? $event_info['name'] : 'Unknown Event';
            
            // Enhanced date conversion function
            function convertDateToMysql($dateString) {
                if (empty($dateString) || trim($dateString) === '') {
                    return null;
                }
                
                $dateString = trim($dateString);
                
                // Common date formats to try
                $formats = [
                    'Y-m-d',        // 2023-12-25 (MySQL format)
                    'd/m/Y',        // 25/12/2023 (European)
                    'm/d/Y',        // 12/25/2023 (US)
                    'd.m.Y',        // 25.12.2023 (European with dots)
                    'd-m-Y',        // 25-12-2023 (European with dashes)
                    'Y/m/d',        // 2023/12/25 (ISO with slashes)
                    'Y.m.d',        // 2023.12.25 (ISO with dots)
                    'd/m/y',        // 25/12/23 (European short year)
                    'm/d/y',        // 12/25/23 (US short year)
                    'd.m.y',        // 25.12.23 (European short year with dots)
                    'd-m-y',        // 25-12-23 (European short year with dashes)
                    'j/n/Y',        // 5/3/2023 (no leading zeros)
                    'j.n.Y',        // 5.3.2023
                    'j-n-Y',        // 5-3-2023
                    'n/j/Y',        // 3/5/2023
                    'Y-n-j',        // 2023-3-5
                    'Y/n/j',        // 2023/3/5
                ];
                
                foreach ($formats as $format) {
                    $date = DateTime::createFromFormat($format, $dateString);
                    if ($date && $date->format($format) === $dateString) {
                        return $date->format('Y-m-d');
                    }
                }
                
                // Try strtotime as fallback
                $timestamp = strtotime($dateString);
                if ($timestamp !== false) {
                    return date('Y-m-d', $timestamp);
                }
                
                return null;
            }
            
            // Process each row
            $row_number = 1; // Start at 1 since we skipped header
            while (($data = fgetcsv($handle, 1000, ',')) !== FALSE) {
                $row_number++;
                
                try {
                    // Validate minimum required fields (First Name, Last Name, Gender)
                    if (count($data) < 3 || empty(trim($data[1])) || empty(trim($data[2])) || empty(trim($data[3]))) {
                        $error_details[] = "Row {$row_number}: Missing required fields (First Name, Last Name, Gender)";
                        $skipped_count++;
                        continue;
                    }
                    
                    // Clean and prepare data
                    $participant_data = [
                        'bib' => trim($data[0]),
                        'first_name' => trim($data[1]),
                        'last_name' => trim($data[2]),
                        'gender' => isset($data[3]) ? strtoupper(substr(trim($data[3]), 0, 1)) : '',
                        'fis_code' => isset($data[4]) ? trim($data[4]) : '',
                        'licence_code' => isset($data[5]) ? trim($data[5]) : '',
                        'licence_type' => isset($data[6]) ? trim($data[6]) : '',
                        'club' => isset($data[7]) ? trim($data[7]) : '',
                        'country' => isset($data[8]) ? strtoupper(trim($data[8])) : '',
                        'date_of_birth' => isset($data[9]) ? convertDateToMysql($data[9]) : null,
                        'category' => isset($data[10]) ? trim($data[10]) : ''
                    ];
                    
                    // Validate gender
                    if ($participant_data['gender'] && !in_array($participant_data['gender'], ['M', 'F'])) {
                        $participant_data['gender'] = '';
                        $error_details[] = "Row {$row_number}: Invalid gender value, set to empty";
                    }
                    
                    // Check for existing participant by BIB, FIS code, or licence code
                    $duplicate_check_sql = "SELECT id, first_name, last_name FROM participants WHERE ";
                    $duplicate_check_params = [];
                    $duplicate_conditions = [];
                    
                    // Always check BIB
                    $duplicate_conditions[] = "bib = ?";
                    $duplicate_check_params[] = $participant_data['bib'];
                    
                    // Check FIS code if provided
                    if (!empty($participant_data['fis_code'])) {
                        $duplicate_conditions[] = "(fis_code = ? AND fis_code != '')";
                        $duplicate_check_params[] = $participant_data['fis_code'];
                    }
                    
                    // Check licence code if provided
                    if (!empty($participant_data['licence_code'])) {
                        $duplicate_conditions[] = "(licence_code = ? AND licence_code != '')";
                        $duplicate_check_params[] = $participant_data['licence_code'];
                    }
                    
                    $duplicate_check_sql .= implode(' OR ', $duplicate_conditions);
                    
                    $existing_stmt = $pdo->prepare($duplicate_check_sql);
                    $existing_stmt->execute($duplicate_check_params);
                    $existing = $existing_stmt->fetch();
                    
                    $participant_id = null;
                    
                    if ($existing && !$overwrite_duplicates) {
                        // Skip duplicate
                        $duplicate_participants[] = $participant_data['first_name'] . ' ' . $participant_data['last_name'] . ' (BIB: ' . $participant_data['bib'] . ')';
                        $skipped_count++;
                        continue;
                        
                    } elseif ($existing && $overwrite_duplicates) {
                        // Update existing participant
                        $update_stmt = $pdo->prepare("
                            UPDATE participants SET 
                                first_name = ?, last_name = ?, gender = ?, fis_code = ?, 
                                licence_code = ?, licence_type = ?, club = ?, country = ?, 
                                date_of_birth = ?, category = ?, updated_at = CURRENT_TIMESTAMP
                            WHERE id = ?
                        ");
                        
                        $update_stmt->execute([
                            $participant_data['bib'],
                            $participant_data['first_name'],
                            $participant_data['last_name'],
                            $participant_data['gender'],
                            $participant_data['fis_code'],
                            $participant_data['licence_code'],
                            $participant_data['licence_type'],
                            $participant_data['club'],
                            $participant_data['country'],
                            $participant_data['date_of_birth'],
                            $participant_data['category'],
                            $existing['id']
                        ]);
                        
                        $participant_id = $existing['id'];
                        $updated_count++;
                        
                        $import_log[] = [
                            'action' => 'UPDATED',
                            'name' => $participant_data['first_name'] . ' ' . $participant_data['last_name'],
                            'bib' => $participant_data['bib'],
                            'row' => $row_number
                        ];
                        
                    } else {
                        // Insert new participant
                        $insert_stmt = $pdo->prepare("
                            INSERT INTO participants 
                            (bib, first_name, last_name, gender, fis_code, licence_code, licence_type, 
                             club, country, date_of_birth, category, created_at) 
                            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)
                        ");
                        
                        $insert_stmt->execute([
                            $participant_data['bib'],
                            $participant_data['first_name'],
                            $participant_data['last_name'],
                            $participant_data['gender'],
                            $participant_data['fis_code'],
                            $participant_data['licence_code'],
                            $participant_data['licence_type'],
                            $participant_data['club'],
                            $participant_data['country'],
                            $participant_data['date_of_birth'],
                            $participant_data['category']
                        ]);
                        
                        $participant_id = $pdo->lastInsertId();
                        $imported_count++;
                        
                        $import_log[] = [
                            'action' => 'CREATED',
                            'name' => $participant_data['first_name'] . ' ' . $participant_data['last_name'],
                            'bib' => $participant_data['bib'],
                            'row' => $row_number
                        ];
                    }
                    
                    // Track import for the selected event
                    if ($participant_id && $assign_event_id) {
                        // Check if already tracked for this event
                        $existing_import_stmt = $pdo->prepare("
                            SELECT id FROM participants_event 
                            WHERE participant_id = ? AND event_id = ?
                        ");
                        $existing_import_stmt->execute([$participant_id, $assign_event_id]);
                        
                        if (!$existing_import_stmt->fetch()) {
                            $import_tracking_stmt = $pdo->prepare("
                                INSERT INTO participants_event (participant_id, event_id, imported_at) 
                                VALUES (?, ?, CURRENT_TIMESTAMP)
                            ");
                            $import_tracking_stmt->execute([$participant_id, $assign_event_id]);
                        }
                        
                        // Optionally auto-assign to event_participants
                        $existing_assignment_stmt = $pdo->prepare("
                            SELECT id FROM event_participants 
                            WHERE participant_id = ? AND event_id = ?
                        ");
                        $existing_assignment_stmt->execute([$participant_id, $assign_event_id]);
                        
                        if (!$existing_assignment_stmt->fetch()) {
                            $assignment_stmt = $pdo->prepare("
                                INSERT INTO event_participants (event_id, participant_id, bib_number, category, created_at) 
                                VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP)
                            ");
                            $assignment_stmt->execute([
                                $assign_event_id, 
                                $participant_id, 
                                $participant_data['bib'],
                                $participant_data['category']
                            ]);
                        }
                    }
                    
                } catch (Exception $e) {
                    $error_count++;
                    $error_details[] = "Row {$row_number}: " . $e->getMessage();
                    continue;
                }
            }
            
            fclose($handle);
            
            // Generate comprehensive success/warning message
            $total_processed = $imported_count + $updated_count;
            $message_parts = [];
            
            if ($total_processed > 0) {
                $message_parts[] = "<strong>{$total_processed} participants processed successfully</strong>";
                if ($imported_count > 0) {
                    $message_parts[] = "{$imported_count} new participants imported";
                }
                if ($updated_count > 0) {
                    $message_parts[] = "{$updated_count} existing participants updated";
                }
                $message_parts[] = "All assigned to event: <strong>{$event_name}</strong>";
            }
            
            if ($skipped_count > 0) {
                $message_parts[] = "{$skipped_count} entries skipped (duplicates or invalid data)";
            }
            
            if ($error_count > 0) {
                $message_parts[] = "{$error_count} entries had errors";
            }
            
            $message_class = 'success';
            if ($error_count > 0 || ($skipped_count > 0 && $total_processed === 0)) {
                $message_class = 'warning';
            }
            
            $message = '<div class="alert alert-' . $message_class . ' alert alert-dismissible fade show" role="alert">
                            <div class="d-flex align-items-start">
                                <i class="fas fa-upload fa-lg me-3 mt-1"></i>
                                <div class="flex-grow-1">
                                    <h6 class="mb-2">Import Complete!</h6>
                                    <div>' . implode('<br>', $message_parts) . '</div>';
            
            // Show sample of duplicates if any
            if (!empty($duplicate_participants) && !$overwrite_duplicates) {
                $duplicate_preview = array_slice($duplicate_participants, 0, 3);
                $message .= '<div class="mt-2 small">
                                <strong>Duplicates found:</strong> ' . implode(', ', $duplicate_preview);
                if (count($duplicate_participants) > 3) {
                    $message .= ' and ' . (count($duplicate_participants) - 3) . ' more...';
                }
                $message .= '<br><em>Enable "Overwrite duplicates" to update existing participants.</em>
                            </div>';
            }
            
            // Show error details if any
            if (!empty($error_details)) {
                $error_preview = array_slice($error_details, 0, 5);
                $message .= '<div class="mt-2 small">
                                <strong>Errors:</strong><br>' . implode('<br>', $error_preview);
                if (count($error_details) > 5) {
                    $message .= '<br>... and ' . (count($error_details) - 5) . ' more errors.';
                }
                $message .= '</div>';
            }
            
            // Add helpful notes
            $message .= '<div class="mt-3 small">
                            <i class="fas fa-info-circle me-1"></i>
                            <strong>Notes:</strong> Date formats automatically converted to YYYY-MM-DD. 
                            Import tracking added for event management.
                        </div>';
            
            $message .= '</div>
                            </div>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>';
            
        } catch (Exception $e) {
            $message = '<div class="alert alert-danger alert alert-dismissible fade show" role="alert">
                            <i class="fas fa-exclamation-triangle me-2"></i>Import failed: ' . htmlspecialchars($e->getMessage()) . '
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>';
        }
    }
}

// CSV Export handler
if (isset($_GET['export']) && $_GET['export'] === 'csv') {
    // Use the same filtering logic as the main query
    $export_where_clauses = [];
    $export_params = [];
    
    if ($filter_gender !== '') {
        $export_where_clauses[] = "p.gender = ?";
        $export_params[] = $filter_gender;
    }
    
    if ($filter_category !== '') {
        $export_where_clauses[] = "p.category = ?";
        $export_params[] = $filter_category;
    }
    
    if ($filter_event !== '') {
        if ($filter_event === 'not_assigned') {
            $export_where_clauses[] = "ep.event_id IS NULL AND pe.event_id IS NULL";
        } else {
            $export_where_clauses[] = "(ep.event_id = ? OR pe.event_id = ?)";
            $export_params[] = $filter_event;
            $export_params[] = $filter_event;
        }
    }
    
    if ($filter_imported !== '') {
        if ($filter_imported === 'yes') {
            $export_where_clauses[] = "pe.event_id IS NOT NULL";
        } else {
            $export_where_clauses[] = "pe.event_id IS NULL";
        }
    }
    
    if ($search !== '') {
        $export_where_clauses[] = "(p.first_name LIKE ? OR p.last_name LIKE ? OR p.bib LIKE ?)";
        $export_params[] = "%$search%";
        $export_params[] = "%$search%";
        $export_params[] = "%$search%";
    }
    
    $export_where_sql = $export_where_clauses ? "WHERE " . implode(" AND ", $export_where_clauses) : "";
    
    // Export query - get all participant data with event information
    $export_query = "SELECT DISTINCT p.id, p.bib, p.first_name, p.last_name, p.gender, 
                            p.fis_code, p.licence_code, p.licence_type, p.club, p.country, 
                            p.date_of_birth, p.category, p.created_at,
                            GROUP_CONCAT(DISTINCT e1.name SEPARATOR '; ') as assigned_events,
                            GROUP_CONCAT(DISTINCT e2.name SEPARATOR '; ') as imported_events
                     FROM participants p
                     LEFT JOIN event_participants ep ON p.id = ep.participant_id
                     LEFT JOIN events e1 ON ep.event_id = e1.id
                     LEFT JOIN participants_event pe ON p.id = pe.participant_id
                     LEFT JOIN events e2 ON pe.event_id = e2.id
                     $export_where_sql
                     GROUP BY p.id
                     ORDER BY p.id ASC";
    
    try {
        $export_stmt = $pdo->prepare($export_query);
        $export_stmt->execute($export_params);
        $export_participants = $export_stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Generate filename with current date and filters
        $filename = 'participants_export_' . date('Y-m-d_H-i-s');
        if ($filter_event && $filter_event !== 'not_assigned') {
            $event_name_stmt = $pdo->prepare("SELECT name FROM events WHERE id = ?");
            $event_name_stmt->execute([$filter_event]);
            $event_result = $event_name_stmt->fetch();
            if ($event_result) {
                $filename .= '_' . preg_replace('/[^a-zA-Z0-9_-]/', '_', $event_result['name']);
            }
        }
        if ($filter_gender) {
            $filename .= '_' . $filter_gender;
        }
        if ($filter_category) {
            $filename .= '_' . preg_replace('/[^a-zA-Z0-9_-]/', '_', $filter_category);
        }
        $filename .= '.csv';
        
        // Clear any previous output
        if (ob_get_level()) {
            ob_end_clean();
        }
        
        // Set headers for CSV download
        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Cache-Control: no-cache, must-revalidate');
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
        header('Pragma: no-cache');
        
        // Create file pointer connected to the output stream
        $output = fopen('php://output', 'w');
        
        // Add BOM for proper UTF-8 encoding in Excel
        fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF));
        
        // CSV Headers
        $csv_headers = [
            'ID',
            'BIB',
            'First Name',
            'Last Name',
            'Gender',
            'FIS Code',
            'Licence Code',
            'Licence Type',
            'Club',
            'Country',
            'Date of Birth',
            'Category',
            'Assigned Events',
            'Imported Events',
            'Registration Date'
        ];
        
        fputcsv($output, $csv_headers);
        
        // Add data rows
        foreach ($export_participants as $participant) {
            $csv_row = [
                $participant['id'],
                $participant['bib'],
                $participant['first_name'],
                $participant['last_name'],
                $participant['gender'],
                $participant['fis_code'] ?: '',
                $participant['licence_code'] ?: '',
                $participant['licence_type'] ?: '',
                $participant['club'] ?: '',
                $participant['country'] ?: '',
                $participant['date_of_birth'] ?: '',
                $participant['category'] ?: '',
                $participant['assigned_events'] ?: 'None',
                $participant['imported_events'] ?: 'Manual Entry',
                $participant['created_at'] ?: ''
            ];
            
            fputcsv($output, $csv_row);
        }
        
        // Add summary footer
        fputcsv($output, []); // Empty row
        fputcsv($output, ['Export Summary:', '', '', '', '', '', '', '', '', '', '', '', '', '', '']);
        fputcsv($output, ['Total Participants:', count($export_participants), '', '', '', '', '', '', '', '', '', '', '', '', '']);
        fputcsv($output, ['Export Date:', date('Y-m-d H:i:s'), '', '', '', '', '', '', '', '', '', '', '', '', '']);
        fputcsv($output, ['Applied Filters:', '', '', '', '', '', '', '', '', '', '', '', '', '', '']);
        
        if ($filter_gender) {
            fputcsv($output, ['- Gender:', $filter_gender, '', '', '', '', '', '', '', '', '', '', '', '', '']);
        }
        if ($filter_category) {
            fputcsv($output, ['- Category:', $filter_category, '', '', '', '', '', '', '', '', '', '', '', '', '']);
        }
        if ($filter_event) {
            $event_filter_text = $filter_event === 'not_assigned' ? 'Not Assigned to Any Event' : 'Event ID: ' . $filter_event;
            fputcsv($output, ['- Event:', $event_filter_text, '', '', '', '', '', '', '', '', '', '', '', '', '']);
        }
        if ($filter_imported) {
            $import_filter_text = $filter_imported === 'yes' ? 'Imported Only' : 'Manual Entry Only';
            fputcsv($output, ['- Import Status:', $import_filter_text, '', '', '', '', '', '', '', '', '', '', '', '', '']);
        }
        if ($search) {
            fputcsv($output, ['- Search Term:', $search, '', '', '', '', '', '', '', '', '', '', '', '', '']);
        }
        
        fclose($output);
        exit;
        
    } catch (Exception $e) {
        // If there's an error, redirect back with error message
        header("Location: participants.php?error=" . urlencode("Export failed: " . $e->getMessage()));
        exit;
    }
}
// Get statistics
$total_participants = $pdo->query("SELECT COUNT(*) FROM participants")->fetchColumn();
$participants_with_events = $pdo->query("SELECT COUNT(DISTINCT participant_id) FROM event_participants")->fetchColumn();
$participants_without_events = $total_participants - $participants_with_events;
$imported_participants = $pdo->query("SELECT COUNT(DISTINCT participant_id) FROM participants_event")->fetchColumn();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Participant Management</title>
    <?php include_once '../includes/stylesheets.php'; ?>
<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;
}
div#table-view {
    max-height: 80vh;
}
</style>
</head>
<body class="body-bg-aurora-bright">
    <?php include '../menu.php'; ?>
   
        <div class="row justify-content-center">
            <div class="col-12">
    <div class="container mt-4">
    <!-- event action menu. -->
<div class="row mb-3">
    <div class="col-12">
        <?php       
        $use_localStorage = true;
        $show_header = false;
        //$show_public_view = false;
        include 'event_actions_menu.php'; 
        ?>
    </div>
</div>
        <!-- Header -->
        <div class="d-flex justify-content-between align-items-center mb-3">
            <div>
                <h2 class="h4 mb-1"><i class="fas fa-users me-2 text-primary"></i>Participant Management</h2>
                <p class="text-muted mb-0 small">Manage participants with import tracking and event assignments</p>
            </div>
            <a href="participant_add.php" class="btn btn-success">
                <i class="fas fa-user-plus me-1"></i>Add New Participant
            </a>
        </div>

        <?php echo $message; ?>

        <!-- Statistics Cards -->
        <div class="row g-2 mb-3">
            <div class="col-md-3">
                <div class="card">
                    <div class="card-body text-center p-3">
                        <div class="bg-primary bg-opacity-10 rounded-circle d-inline-flex align-items-center justify-content-center mb-2" style="width: 40px; height: 40px;">
                            <i class="fas fa-users text-primary"></i>
                        </div>
                        <h5 class="fw-bold text-primary mb-1"><?= $total_participants ?></h5>
                        <small class="text-muted">Total Participants</small>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card">
                    <div class="card-body text-center p-3">
                        <div class="bg-success bg-opacity-10 rounded-circle d-inline-flex align-items-center justify-content-center mb-2" style="width: 40px; height: 40px;">
                            <i class="fas fa-calendar-check text-success"></i>
                        </div>
                        <h5 class="fw-bold text-success mb-1"><?= $participants_with_events ?></h5>
                        <small class="text-muted">Assigned to Events</small>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card">
                    <div class="card-body text-center p-3">
                        <div class="bg-info bg-opacity-10 rounded-circle d-inline-flex align-items-center justify-content-center mb-2" style="width: 40px; height: 40px;">
                            <i class="fas fa-upload text-info"></i>
                        </div>
                        <h5 class="fw-bold text-info mb-1"><?= $imported_participants ?></h5>
                        <small class="text-muted">Imported Participants</small>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card">
                    <div class="card-body text-center p-3">
                        <div class="bg-warning bg-opacity-10 rounded-circle d-inline-flex align-items-center justify-content-center mb-2" style="width: 40px; height: 40px;">
                            <i class="fas fa-user-clock text-warning"></i>
                        </div>
                        <h5 class="fw-bold text-warning mb-1"><?= $participants_without_events ?></h5>
                        <small class="text-muted">Unassigned</small>
                    </div>
                </div>
            </div>
        </div>

        <!-- Action Cards -->
        <div class="row g-3 mb-3">
            
            <!-- Import Section -->
            <div class="col-lg-4">
                <div class="card border-success">
                    <div class="card-header bg-success text-white p-2">
                        <h6 class="mb-0 fw-bold">
                            <i class="fas fa-upload me-1"></i>CSV Import
                        </h6>
                    </div>
                    <div class="card-body p-3">
                        <form method="post" enctype="multipart/form-data" id="importForm">
                            <div class="mb-2">
                                <label class="form-label fw-semibold small">
                                    <i class="fas fa-calendar-alt me-1 text-primary"></i>Target Event <span class="text-danger">*</span>
                                </label>
                                <select name="assign_event_id" class="form-select form-select-sm" required>
                                    <option value="">Select Event for Import</option>
                                    <?php foreach ($events as $event): ?>
                                        <option value="<?= $event['id'] ?>">
                                            <?= htmlspecialchars($event['name']) ?> 
                                            <span class="text-muted">(<?= date('M d, Y', strtotime($event['date'])) ?>)</span>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="mb-2">
                                <label class="form-label fw-semibold small">
                                    <i class="fas fa-file-csv me-1 text-primary"></i>CSV File <span class="text-danger">*</span>
                                </label>
                                <input type="file" name="import_file" class="form-control form-control-sm" accept=".csv" required>
                                <div class="form-text small">
                                    <strong>Columns:</strong> BIB, First Name, Last Name, Gender, FIS Code, Licence Code, etc.
                                </div>
                            </div>
                            
                            <div class="mb-2">
                                <div class="form-check form-switch">
                                    <input class="form-check-input" type="checkbox" name="overwrite_duplicates" id="overwrite_duplicates">
                                    <label class="form-check-label fw-semibold small" for="overwrite_duplicates">
                                        <i class="fas fa-sync-alt me-1"></i>Overwrite Existing
                                    </label>
                                </div>
                            </div>
                            
                            <div class="d-grid">
                                <button type="submit" class="btn btn-success btn-sm">
                                    <i class="fas fa-upload me-1"></i>Import Participants
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>

            <!-- Export & Actions Section -->
            <div class="col-lg-4">
                <div class="card">
                    <div class="card-header bg-primary text-white p-2">
                        <h6 class="mb-0 fw-bold">
                            <i class="fas fa-cogs me-1"></i>Actions & Export
                        </h6>
                    </div>
                    <div class="card-body p-3">
                        <div class="d-grid gap-2">
                            <?php 
                            // Build export URL with current filters
                            $export_params = array_filter([
                                'export' => 'csv',
                                'gender' => $filter_gender,
                                'category' => $filter_category,
                                'event' => $filter_event,
                                'imported' => $filter_imported,
                                'search' => $search
                            ]);
                            $export_url = '?' . http_build_query($export_params);
                            ?>
                            <a href="<?= $export_url ?>" class="btn btn-outline-primary btn-sm">
                                <i class="fas fa-file-csv me-1"></i>Export CSV
                                <?php if (array_filter([$filter_gender, $filter_category, $filter_event, $filter_imported, $search])): ?>
                                    <span class="badge bg-primary ms-1"><?= count($participants) ?></span>
                                <?php endif; ?>
                            </a>
                            <a href="participant_add.php" class="btn btn-success btn-sm">
                                <i class="fas fa-user-plus me-1"></i>Add Participant
                            </a>
                            <a href="?delete_all=1" class="btn btn-outline-danger btn-sm" onclick="return confirm('Are you sure you want to delete ALL participants? This action cannot be undone!')">
                                <i class="fas fa-trash-alt me-1"></i>Delete All
                            </a>
                        </div>
                    </div>
                </div>
            </div>
           
            <!-- Bulk Assignment Section -->
            <div class="col-lg-4">
                <div class="card border-info">
                    <div class="card-header bg-info text-white p-2">
                        <h6 class="mb-0 fw-bold">
                            <i class="fas fa-users-cog me-1"></i>Bulk Assignment
                        </h6>
                    </div>
                    <div class="card-body p-3">
                        <p class="text-muted mb-2 small">Assign multiple participants to events with advanced options.</p>
                        
                        <div class="d-grid gap-2">
                            <button type="button" class="btn btn-info btn-sm" onclick="showBulkAssignModal()">
                                <i class="fas fa-calendar-plus me-1"></i>Bulk Assign Selected
                                <span id="bulkAssignCount" class="badge bg-white text-info ms-1">0</span>
                            </button>
                            
                            <div class="btn-group">
                                <button type="button" class="btn btn-outline-info btn-sm" onclick="selectAllVisible()">
                                    <i class="fas fa-check-double me-1"></i>Select All Visible
                                </button>
                                <button type="button" class="btn btn-outline-secondary btn-sm" onclick="clearSelection()">
                                    <i class="fas fa-times me-1"></i>Clear Selection
                                </button>
                            </div>
                        </div>
                        
                        <div class="mt-2">
                            <small class="text-muted">
                                <i class="fas fa-lightbulb me-1"></i>
                                <strong>Tip:</strong> Use filters to narrow down participants, then select and assign them to events in bulk.
                            </small>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        

        <!-- Filters -->
        <div class="card mb-3">
            <div class="card-header bg-light p-2">
                <h6 class="mb-0 fw-bold text-dark">
                    <i class="fas fa-filter me-1"></i>Filters & Search
                </h6>
            </div>
            <div class="card-body p-3">
                <form method="get" class="row g-2">
                    <div class="col-md-2">
                        <label class="form-label fw-semibold small">Search</label>
                        <div class="input-group input-group-sm">
                            <span class="input-group-text"><i class="fas fa-search"></i></span>
                            <input type="text" class="form-control" name="search" value="<?= htmlspecialchars($search) ?>" placeholder="Name or BIB...">
                        </div>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label fw-semibold small">Gender</label>
                        <select name="gender" class="form-select form-select-sm">
                            <option value="">All Genders</option>
                            <?php foreach ($genders as $gender): ?>
                                <option value="<?= $gender ?>" <?= $filter_gender === $gender ? 'selected' : '' ?>>
                                    <?= ucfirst($gender) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label fw-semibold small">Category</label>
                        <select name="category" class="form-select form-select-sm">
                            <option value="">All Categories</option>
                            <?php foreach ($categories as $cat): ?>
                                <option value="<?= $cat ?>" <?= $filter_category === $cat ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($cat) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label fw-semibold small">Event</label>
                        <select name="event" class="form-select form-select-sm">
                            <option value="">All Events</option>
                            <option value="not_assigned" <?= $filter_event === 'not_assigned' ? 'selected' : '' ?>>
                                <i class="fas fa-user-slash me-1"></i>Not Assigned
                            </option>
                            <?php foreach ($events as $event): ?>
                                <option value="<?= $event['id'] ?>" <?= $filter_event == $event['id'] ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($event['name']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label fw-semibold small">Imported</label>
                        <select name="imported" class="form-select form-select-sm">
                            <option value="">All</option>
                            <option value="yes" <?= $filter_imported === 'yes' ? 'selected' : '' ?>>Imported Only</option>
                            <option value="no" <?= $filter_imported === 'no' ? 'selected' : '' ?>>Manual Only</option>
                        </select>
                    </div>
                    <div class="col-md-2 d-flex align-items-end">
                        <div class="d-grid gap-1 w-100">
                            <button type="submit" class="btn btn-primary btn-sm">
                                <i class="fas fa-search me-1"></i>Filter
                            </button>
                            <a href="participants.php" class="btn btn-outline-secondary btn-sm">
                                <i class="fas fa-times me-1"></i>Clear
                            </a>
                        </div>
                    </div>
                </form>
            </div>
        </div>
<!-- Active Filters Display -->
        <?php if ($filter_gender || $filter_category || $filter_event || $filter_imported || $search): ?>
            <div class="alert alert-info alert alert-dismissible fade show mb-3">
                <div class="d-flex align-items-center">
                    <i class="fas fa-filter me-2"></i>
                    <span class="fw-bold me-2">Active Filters:</span>
                    <div class="d-flex flex-wrap gap-1">
                        <?php if ($search): ?>
                            <span class="badge bg-primary">Search: "<?= htmlspecialchars($search) ?>"</span>
                        <?php endif; ?>
                        <?php if ($filter_gender): ?>
                            <span class="badge bg-info">Gender: <?= htmlspecialchars($filter_gender) ?></span>
                        <?php endif; ?>
                        <?php if ($filter_category): ?>
                            <span class="badge bg-secondary">Category: <?= htmlspecialchars($filter_category) ?></span>
                        <?php endif; ?>
                        <?php if ($filter_event): ?>
                            <?php 
                            $event_name = 'Unknown Event';
                            if ($filter_event === 'not_assigned') {
                                $event_name = 'Not Assigned';
                            } else {
                                $event_query = $pdo->prepare("SELECT name FROM events WHERE id = ?");
                                $event_query->execute([$filter_event]);
                                $event_result = $event_query->fetch();
                                if ($event_result) {
                                    $event_name = $event_result['name'];
                                }
                            }
                            ?>
                            <span class="badge bg-success">Event: <?= htmlspecialchars($event_name) ?></span>
                        <?php endif; ?>
                        <?php if ($filter_imported): ?>
                            <span class="badge bg-warning">
                                Import: <?= $filter_imported === 'yes' ? 'Imported Only' : 'Manual Only' ?>
                            </span>
                        <?php endif; ?>
                    </div>
                </div>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>
        <!-- Participants Table -->
        <div class="card">
            <div class="card-header bg-white p-2 d-flex justify-content-between align-items-center">
                <h6 class="mb-0 fw-bold text-dark">
                    <i class="fas fa-table me-1"></i>Participants List (<?= count($participants) ?> results)
                </h6>
                <div class="btn-group btn-group-sm">
                    <button class="btn btn-outline-secondary active" onclick="toggleView('table')">
                        <i class="fas fa-table"></i>
                    </button>
                    <button class="btn btn-outline-secondary" onclick="toggleView('cards')">
                        <i class="fas fa-th-large"></i>
                    </button>
                </div>
            </div>
            <div class="card-body p-0">
                
                <!-- Table View -->
                <div id="table-view" class="table-responsive">
                    <table class="table table-hover mb-0 table-sm">
                        <thead class="table-light">
                            <tr>
                                <th class="small">BIB</th>
                                <th class="small">Name</th>
                                <th class="small">Gender</th>
                                <th class="small">FIS Code</th>
                                <th class="small">Club</th>
                                <th class="small">Country</th>
                                <th class="small">Category</th>
                                <th class="small">Event Assignments</th>
                                <th class="small">Import Status</th>
                                <th width="120" class="small">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($participants)): ?>
                                <tr>
                                    <td colspan="10" class="text-center text-muted py-3">
                                        <i class="fas fa-users fa-2x mb-2 opacity-50"></i>
                                        <p class="mb-0 small">No participants found matching your criteria</p>
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($participants as $p): ?>
                                <tr>
                                    <td>
                                        <span class="badge bg-primary rounded-pill small"><?= htmlspecialchars($p['bib']) ?></span>
                                    </td>
                                    <td>
                                        <div class="fw-semibold small"><?= htmlspecialchars($p['first_name'] . ' ' . $p['last_name']) ?></div>
                                        <small class="text-muted">ID: <?= $p['id'] ?></small>
                                    </td>
                                    <td>
                                        <span class="badge bg-<?= $p['gender'] === 'M' ? 'info' : 'pink' ?> bg-opacity-20 text-dark small">
                                            <?= htmlspecialchars($p['gender']) ?>
                                        </span>
                                    </td>
                                    <td><small><?= htmlspecialchars($p['fis_code']) ?></small></td>
                                    <td><small><?= htmlspecialchars($p['club']) ?></small></td>
                                    <td>
                                        <span class="badge bg-light text-dark small">
                                            <?= htmlspecialchars($p['country']) ?>
                                        </span>
                                    </td>
                                    <td><small class="badge bg-opacity-20 bg-secondary text-secondary"><?= htmlspecialchars($p['category']) ?></small></td>
                                      <td>
                                        <?php if ($p['assigned_event_names']): ?>
                                            <div class="d-flex flex-wrap gap-1">
                                                <?php
                                                $event_names = array_filter(explode(', ', $p['assigned_event_names']));
                                                $event_ids = array_filter(explode(',', $p['assigned_event_ids']));
                                                
                                                for ($i = 0; $i < count($event_names); $i++) {
                                                    $event_name = $event_names[$i] ?? '';
                                                    $event_id = $event_ids[$i] ?? '';
                                                    if ($event_name && $event_id) {
                                                        echo '<a href="heats_configure.php?event_id=' . $event_id . '" class="text-decoration-none">
                                                                <span class="badge bg-success bg-opacity-20 text-muted" title="View event details">
                                                                    <i class="fas fa-external-link-alt me-1"></i>' . htmlspecialchars($event_name) . '
                                                                </span>
                                                              </a>';
                                                    }
                                                }
                                                ?>
                                            </div>
                                        <?php else: ?>
                                            <span class="badge bg-warning bg-opacity-20 text-muted">
                                                Not Assigned
                                            </span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php if ($p['imported_event_names']): ?>
                                            <div class="d-flex flex-wrap gap-1">
                                                <?php
                                                $imported_events = array_filter(explode(', ', $p['imported_event_names']));
                                                $imported_event_ids = array_filter(explode(',', $p['imported_event_ids']));
                                                
                                                for ($i = 0; $i < count($imported_events); $i++) {
                                                    $imported_event = $imported_events[$i] ?? '';
                                                    $imported_event_id = $imported_event_ids[$i] ?? '';
                                                    if ($imported_event && $imported_event_id) {
                                                        echo '<a href="event_details.php?id=' . $imported_event_id . '" class="text-decoration-none">
                                                                <span class="badge bg-info bg-opacity-20 text-muted" title="View import details">
                                                                    <i class="fas fa-upload me-1"></i>' . htmlspecialchars($imported_event) . '
                                                                </span>
                                                              </a>';
                                                    }
                                                }
                                                ?>
                                            </div>
                                        <?php else: ?>
                                            <span class="badge bg-secondary bg-opacity-20 text-secondary">
                                                Manual Entry
                                            </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" title="Edit">
                                                <i class="fas fa-edit"></i>
                                            </a>
                                            <button type="button" class="btn btn-outline-info" title="Assign to Event" 
                                                    onclick="showAssignModal(<?= $p['id'] ?>, '<?= htmlspecialchars($p['first_name'] . ' ' . $p['last_name']) ?>', '<?= htmlspecialchars($p['bib']) ?>')">
                                                <i class="fas fa-calendar-plus"></i>
                                            </button>
                                            <a href="?delete=<?= $p['id'] ?>" class="btn btn-outline-danger" title="Delete" 
                                               onclick="return confirm('Delete <?= htmlspecialchars($p['first_name'] . ' ' . $p['last_name']) ?>?')">
                                                <i class="fas fa-trash"></i>
                                            </a>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>

                <!-- Cards View -->
                <div id="cards-view" class="d-none p-4">
                    <div class="row g-3">
                        <?php foreach ($participants as $p): ?>
                            <div class="col-md-6 col-lg-4">
                                <div class="card  ">
                                    <div class="card-body">
                                        <div class="d-flex justify-content-between align-items-start mb-2">
                                            <span class="badge bg-primary"><?= htmlspecialchars($p['bib']) ?></span>
                                            <span class="badge bg-<?= $p['gender'] === 'Male' ? 'info' : 'pink' ?> bg-opacity-20 text-dark">
                                                <?= htmlspecialchars($p['gender']) ?>
                                            </span>
                                        </div>
                                        <h6 class="fw-bold"><?= htmlspecialchars($p['first_name'] . ' ' . $p['last_name']) ?></h6>
                                        <p class="small text-muted mb-2">
                                            <i class="fas fa-id-card me-1"></i><?= htmlspecialchars($p['fis_code']) ?><br>
                                            <i class="fas fa-building me-1"></i><?= htmlspecialchars($p['club']) ?><br>
                                            <i class="fas fa-flag me-1"></i><?= htmlspecialchars($p['country']) ?>
                                        </p>
                                        
                                        <!-- Event Assignments -->
                                        <?php if ($p['assigned_event_names']): ?>
                                            <div class="mb-2">
                                                <small class="text-muted fw-semibold d-block mb-1">Event Assignments:</small>
                                                <div class="d-flex flex-wrap gap-1">
                                                    <?php
                                                    $event_names = array_filter(explode(', ', $p['assigned_event_names']));
                                                    foreach ($event_names as $event_name) {
                                                        echo '<span class="badge bg-success text-muted bg-opacity-20  small">' . htmlspecialchars($event_name) . '</span>';
                                                    }
                                                    ?>
                                                </div>
                                            </div>
                                        <?php endif; ?>
                                        
                                        <!-- Import Status -->
                                        <?php if ($p['imported_event_names']): ?>
                                            <div class="mb-2">
                                                <small class="text-muted fw-semibold d-block mb-1">Imported for:</small>
                                                <div class="d-flex flex-wrap gap-1">
                                                    <?php
                                                    $imported_events = array_filter(explode(', ', $p['imported_event_names']));
                                                    foreach ($imported_events as $imported_event) {
                                                        echo '<span class="badge bg-info text-muted bg-opacity-20  small">
                                                                <i class="fas fa-upload me-1"></i>' . htmlspecialchars($imported_event) . '
                                                              </span>';
                                                    }
                                                    ?>
                                                </div>
                                            </div>
                                        <?php else: ?>
                                            <span class="badge bg-secondary bg-opacity-20 text-secondary mb-2">
                                                Manual Entry
                                            </span>
                                        <?php endif; ?>
                                        
                                        <div class="d-grid gap-1">
                                            <div class="btn-group btn-group-sm">
                                                <a href="participant_edit.php?id=<?= $p['id'] ?>" class="btn btn-outline-primary">
                                                    <i class="fas fa-edit me-1"></i>Edit
                                                </a>
                                                <a href="assign_participant.php?id=<?= $p['id'] ?>" class="btn btn-outline-info">
                                                    <i class="fas fa-calendar-plus me-1"></i>Assign
                                                </a>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

			</div></div>
    <!-- Enhanced Assignment Modal -->
<div class="modal fade" id="assignModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title">
                    <i class="fas fa-calendar-plus me-2"></i>Assign Participants to Event
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div id="assignAlert"></div>
                
                <form id="assignForm" method="post">
                    <input type="hidden" name="assign_to_event" value="1">
                    <input type="hidden" id="selectedParticipants" name="participant_ids[]">
                    
                    <!-- Selected Participants Display -->
                    <div class="mb-4">
                        <label class="form-label fw-semibold">Selected Participants</label>
                        <div id="selectedParticipantsDisplay" class="p-3 bg-light rounded border">
                            <div class="text-muted">
                                <i class="fas fa-info-circle me-1"></i>No participants selected. Click "Bulk Assign" to select participants.
                            </div>
                        </div>
                    </div>
                    
                    <!-- Event Selection -->
                    <div class="mb-3">
                        <label for="assignEventSelect" class="form-label fw-semibold">
                            <i class="fas fa-calendar me-1 text-primary"></i>Target Event <span class="text-danger">*</span>
                        </label>
                        <select id="assignEventSelect" name="event_id" class="form-select form-select-lg" required onchange="loadEventHeats(this.value)">
                            <option value="">Select Event</option>
                            <?php foreach ($events as $event): ?>
                                <option value="<?= $event['id'] ?>">
                                    <?= htmlspecialchars($event['name']) ?> 
                                    <span class="text-muted">(<?= date('M d, Y', strtotime($event['date'])) ?>)</span>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <!-- Assignment Options -->
                    <div class="mb-4">
                        <label class="form-label fw-semibold">
                            <i class="fas fa-cogs me-1 text-secondary"></i>Assignment Options
                        </label>
                        
                        <div class="row g-3">
                            <div class="col-12">
                                <div class="form-check form-switch">
                                    <input class="form-check-input" type="checkbox" name="assign_to_event_participants" id="assignToEventParticipants" onchange="toggleHeatOptions()">
                                    <label class="form-check-label fw-semibold" for="assignToEventParticipants">
                                        <i class="fas fa-fire me-1"></i>Assign to Event Competition (Heat Assignment)
                                    </label>
                                </div>
                                <div class="form-text">
                                    <small>
                                        <strong>Unchecked:</strong> Only track participants for this event (participants_event table)<br>
                                        <strong>Checked:</strong> Also assign to event competition with heat assignment (event_participants table)
                                    </small>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Heat Assignment Options (shown when event_participants is selected) -->
                    <div id="heatOptions" class="mb-3" style="display: none;">
                        <div class="card border-info">
                            <div class="card-header bg-info bg-opacity-10">
                                <h6 class="mb-0 fw-bold text-info">
                                    <i class="fas fa-fire me-2"></i>Heat Assignment Options
                                </h6>
                            </div>
                            <div class="card-body">
                                <div class="row g-3">
                                    <div class="col-md-6">
                                        <label for="assignHeatSelect" class="form-label fw-semibold">Heat (Optional)</label>
                                        <select id="assignHeatSelect" name="heat_number" class="form-select" disabled>
                                            <option value="">No specific heat (assign later)</option>
                                        </select>
                                        <div class="form-text">
                                            <small id="heatInfo" class="text-muted">Select an event to see available heats</small>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <label for="assignCategory" class="form-label fw-semibold">Category Override</label>
                                        <input type="text" id="assignCategory" name="category" class="form-control" placeholder="Leave empty to use participant's category">
                                        <div class="form-text">
                                            <small>Override the participant's default category for this event</small>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Assignment Summary -->
                    <div class="alert alert-info">
                        <div class="d-flex">
                            <i class="fas fa-info-circle fa-lg me-2 mt-1"></i>
                            <div>
                                <strong>Assignment Process:</strong>
                                <ul class="mb-0 mt-1 small">
                                    <li><strong>Step 1:</strong> Track participants for the selected event (always done)</li>
                                    <li><strong>Step 2:</strong> Optionally assign to event competition with heat details</li>
                                    <li>Duplicate assignments will be detected and skipped</li>
                                    <li>Assignment status will be reported for each participant</li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-success" onclick="submitAssignment()">
                    <i class="fas fa-calendar-plus me-2"></i>Assign Participants
                </button>
            </div>
        </div>
    </div>
</div>

       <!-- Assignment Modal -->
    <script>

        // Enhanced assignment functionality
let assignModal;
let selectedParticipants = [];

// Store heats data for JavaScript access
const heatsData = <?= json_encode($heats) ?>;

document.addEventListener('DOMContentLoaded', function() {
    assignModal = new bootstrap.Modal(document.getElementById('assignModal'));
    
    // Add checkboxes to participant rows
    addSelectionCheckboxes();
    updateBulkAssignButton();
});

function addSelectionCheckboxes() {
    const participantRows = document.querySelectorAll('#table-view tbody tr');
    
    // Add header checkbox
    const headerRow = document.querySelector('#table-view thead tr');
    if (headerRow && !headerRow.querySelector('.select-checkbox')) {
        const headerCell = document.createElement('th');
        headerCell.className = 'select-checkbox';
        headerCell.innerHTML = '<input type="checkbox" id="selectAll" onchange="toggleSelectAll()">';
        headerRow.insertBefore(headerCell, headerRow.firstChild);
    }
    
    participantRows.forEach((row, index) => {
        if (row.children.length > 1) { // Skip empty message rows
            const participantId = row.querySelector('a[href*="participant_edit.php"]')?.href.match(/id=(\d+)/)?.[1];
            
            if (participantId && !row.querySelector('.select-checkbox')) {
                const checkboxCell = document.createElement('td');
                checkboxCell.className = 'select-checkbox';
                checkboxCell.innerHTML = `<input type="checkbox" value="${participantId}" onchange="updateSelection(this)">`;
                row.insertBefore(checkboxCell, row.firstChild);
            }
        }
    });
}

function toggleSelectAll() {
    const selectAllBox = document.getElementById('selectAll');
    const checkboxes = document.querySelectorAll('#table-view tbody input[type="checkbox"]');
    
    checkboxes.forEach(checkbox => {
        checkbox.checked = selectAllBox.checked;
        updateSelection(checkbox);
    });
}

function updateSelection(checkbox) {
    const participantId = parseInt(checkbox.value);
    
    if (checkbox.checked) {
        if (!selectedParticipants.includes(participantId)) {
            selectedParticipants.push(participantId);
        }
    } else {
        selectedParticipants = selectedParticipants.filter(id => id !== participantId);
    }
    
    updateBulkAssignButton();
    updateSelectAllState();
}

function updateSelectAllState() {
    const selectAllBox = document.getElementById('selectAll');
    const checkboxes = document.querySelectorAll('#table-view tbody input[type="checkbox"]');
    const checkedBoxes = document.querySelectorAll('#table-view tbody input[type="checkbox"]:checked');
    
    if (selectAllBox) {
        selectAllBox.indeterminate = checkedBoxes.length > 0 && checkedBoxes.length < checkboxes.length;
        selectAllBox.checked = checkedBoxes.length === checkboxes.length && checkboxes.length > 0;
    }
}

function updateBulkAssignButton() {
    const countBadge = document.getElementById('bulkAssignCount');
    const bulkButton = document.querySelector('[onclick="showBulkAssignModal()"]');
    
    if (countBadge) {
        countBadge.textContent = selectedParticipants.length;
        countBadge.className = selectedParticipants.length > 0 ? 
            'badge bg-white text-info ms-2' : 
            'badge bg-secondary ms-2';
    }
    
    if (bulkButton) {
        bulkButton.disabled = selectedParticipants.length === 0;
    }
}

function selectAllVisible() {
    const visibleCheckboxes = document.querySelectorAll('#table-view tbody tr:not(.d-none) input[type="checkbox"]');
    visibleCheckboxes.forEach(checkbox => {
        checkbox.checked = true;
        updateSelection(checkbox);
    });
}

function clearSelection() {
    selectedParticipants = [];
    document.querySelectorAll('#table-view input[type="checkbox"]').forEach(checkbox => {
        checkbox.checked = false;
    });
    updateBulkAssignButton();
    updateSelectAllState();
}

function showBulkAssignModal() {
    if (selectedParticipants.length === 0) {
        alert('Please select at least one participant.');
        return;
    }
    
    // Populate selected participants display
    updateSelectedParticipantsDisplay();
    
    // Clear previous alerts and form
    document.getElementById('assignAlert').innerHTML = '';
    document.getElementById('assignForm').reset();
    
    // Populate hidden input with selected participant IDs
    const hiddenInput = document.getElementById('selectedParticipants');
    hiddenInput.value = '';
    selectedParticipants.forEach(id => {
        const input = document.createElement('input');
        input.type = 'hidden';
        input.name = 'participant_ids[]';
        input.value = id;
        document.getElementById('assignForm').appendChild(input);
    });
    
    // Reset heat options
    toggleHeatOptions();
    
    assignModal.show();
}

function updateSelectedParticipantsDisplay() {
    const displayDiv = document.getElementById('selectedParticipantsDisplay');
    
    if (selectedParticipants.length === 0) {
        displayDiv.innerHTML = `
            <div class="text-muted">
                <i class="fas fa-info-circle me-1"></i>No participants selected.
            </div>
        `;
        return;
    }
    
    // Get participant details from the table
    let participantDetails = [];
    selectedParticipants.forEach(id => {
        const row = document.querySelector(`input[value="${id}"]`)?.closest('tr');
        if (row) {
            const bibBadge = row.querySelector('.badge.bg-primary')?.textContent || '';
            const nameDiv = row.querySelector('.fw-semibold')?.textContent || '';
            
            participantDetails.push({
                id: id,
                bib: bibBadge,
                name: nameDiv
            });
        }
    });
    
    let html = `
        <div class="d-flex justify-content-between align-items-center mb-2">
            <span class="fw-bold">
                <i class="fas fa-users me-1 text-primary"></i>
                ${selectedParticipants.length} participant(s) selected
            </span>
            <button type="button" class="btn btn-sm btn-outline-secondary" onclick="clearSelection(); assignModal.hide();">
                <i class="fas fa-times me-1"></i>Clear Selection
            </button>
        </div>
        <div class="selected-participants-grid">
    `;
    
    participantDetails.forEach(participant => {
        html += `
            <div class="participant-item">
                <span class="badge bg-primary me-1">${participant.bib}</span>
                <span class="participant-name">${participant.name}</span>
            </div>
        `;
    });
    
    html += '</div>';
    displayDiv.innerHTML = html;
}

function loadEventHeats(eventId) {
    const heatSelect = document.getElementById('assignHeatSelect');
    const heatInfo = document.getElementById('heatInfo');
    
    if (!eventId) {
        heatSelect.disabled = true;
        heatSelect.innerHTML = '<option value="">No specific heat (assign later)</option>';
        heatInfo.textContent = 'Select an event to see available heats';
        return;
    }
    
    // Filter heats for selected event
    const eventHeats = heatsData.filter(heat => heat.event_id == eventId);
    
    heatSelect.innerHTML = '<option value="">No specific heat (assign later)</option>';
    
    if (eventHeats.length === 0) {
        heatInfo.innerHTML = '<span class="text-warning">No heats configured for this event</span>';
    } else {
        eventHeats.forEach(heat => {
            const option = document.createElement('option');
            option.value = heat.heat_number;
            option.textContent = `Heat ${heat.heat_number}${heat.heat_name ? ' - ' + heat.heat_name : ''}`;
            heatSelect.appendChild(option);
        });
        
        heatInfo.innerHTML = `<span class="text-success">${eventHeats.length} heat(s) available</span>`;
    }
    
    // Enable heat select if event_participants is checked
    heatSelect.disabled = !document.getElementById('assignToEventParticipants').checked;
}

function toggleHeatOptions() {
    const checkbox = document.getElementById('assignToEventParticipants');
    const heatOptions = document.getElementById('heatOptions');
    const heatSelect = document.getElementById('assignHeatSelect');
    
    if (checkbox.checked) {
        heatOptions.style.display = 'block';
        heatSelect.disabled = false;
        
        // Load heats for currently selected event
        const eventId = document.getElementById('assignEventSelect').value;
        if (eventId) {
            loadEventHeats(eventId);
        }
    } else {
        heatOptions.style.display = 'none';
        heatSelect.disabled = true;
    }
}

function submitAssignment() {
    const form = document.getElementById('assignForm');
    const eventId = document.getElementById('assignEventSelect').value;
    
    if (!eventId) {
        document.getElementById('assignAlert').innerHTML = `
            <div class="alert alert-warning alert alert-dismissible fade show" role="alert">
                <i class="fas fa-exclamation-triangle me-2"></i>Please select an event.
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        `;
        return;
    }
    
    if (selectedParticipants.length === 0) {
        document.getElementById('assignAlert').innerHTML = `
            <div class="alert alert-warning alert alert-dismissible fade show" role="alert">
                <i class="fas fa-exclamation-triangle me-2"></i>No participants selected.
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        `;
        return;
    }
    
    const submitBtn = document.querySelector('[onclick="submitAssignment()"]');
    const originalText = submitBtn.innerHTML;
    
    // Show loading state
    submitBtn.disabled = true;
    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Assigning...';
    
    // Submit the form
    form.submit();
}

// Individual participant assignment (keep existing functionality)
function showAssignModal(participantId, participantName, bib) {
    // Clear selections and use single participant
    selectedParticipants = [participantId];
    updateSelectedParticipantsDisplay();
    
    // Populate form
    const hiddenInput = document.getElementById('selectedParticipants');
    const form = document.getElementById('assignForm');
    
    // Clear existing hidden inputs
    form.querySelectorAll('input[name="participant_ids[]"]').forEach(input => input.remove());
    
    // Add single participant
    const input = document.createElement('input');
    input.type = 'hidden';
    input.name = 'participant_ids[]';
    input.value = participantId;
    form.appendChild(input);
    
    // Clear alerts and reset form
    document.getElementById('assignAlert').innerHTML = '';
    form.reset();
    
    // Reset heat options
    toggleHeatOptions();
    
    assignModal.show();
}

// Style for selected participants display
const style = document.createElement('style');
style.textContent = `
.selected-participants-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 8px;
    max-height: 200px;
    overflow-y: auto;
    padding: 8px;
    background: white;
    border-radius: 6px;
    border: 1px solid #dee2e6;
}

.participant-item {
    display: flex;
    align-items: center;
    padding: 4px 8px;
    background: #f8f9fa;
    border-radius: 4px;
    font-size: 0.875rem;
}

.participant-name {
    flex-grow: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.select-checkbox {
    width: 40px;
    text-align: center;
}
`;
document.head.appendChild(style);

        function loadHeats(eventId) {
            const heatSelect = document.getElementById('heatSelect');
            const heatInfo = document.getElementById('heatInfo');
            
            if (!eventId) {
                heatSelect.disabled = true;
                heatSelect.innerHTML = '<option value="">Select Event First</option>';
                heatInfo.textContent = 'Select an event to see available heats';
                return;
            }
            
            // Filter heats for selected event
            const eventHeats = heatsData.filter(heat => heat.event_id == eventId);
            
            if (eventHeats.length === 0) {
                heatSelect.disabled = true;
                heatSelect.innerHTML = '<option value="">No heats configured for this event</option>';
                heatInfo.innerHTML = '<span class="text-warning">No heats found. Please configure heats for this event first.</span>';
                return;
            }
            
            // Populate heat dropdown
            heatSelect.disabled = false;
            heatSelect.innerHTML = '<option value="">Select Heat</option>';
            
            eventHeats.forEach(heat => {
                const option = document.createElement('option');
                option.value = heat.heat_number;
                option.textContent = heat.heat_name;
                heatSelect.appendChild(option);
            });
            
            heatInfo.innerHTML = `<span class="text-success">${eventHeats.length} heat(s) available</span>`;
        }

        function assignParticipant() {
            const form = document.getElementById('assignForm');
            const formData = new FormData(form);
            
            // Validate selections
            const eventId = document.getElementById('eventSelect').value;
            const heatId = document.getElementById('heatSelect').value;
            
            if (!eventId || !heatId) {
                document.getElementById('assignAlert').innerHTML = `
                    <div class="alert alert-warning alert alert-dismissible fade show" role="alert">
                        <i class="fas fa-exclamation-triangle me-2"></i>Please select both event and heat.
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                `;
                return;
            }
            
            // Add participant ID as array (to match existing AJAX endpoint)
            formData.delete('participant_id');
            formData.append('participant_ids[]', document.getElementById('participantId').value);
            
            const submitBtn = document.querySelector('[onclick="assignParticipant()"]');
            const originalText = submitBtn.innerHTML;
            
            // Show loading state
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Assigning...';
            
            fetch('ajax_assing.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                const alertDiv = document.getElementById('assignAlert');
                
                if (data.status === 'success') {
                    alertDiv.innerHTML = `
                        <div class="alert alert-success alert alert-dismissible fade show" role="alert">
                            <i class="fas fa-check-circle me-2"></i>${data.message}
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    `;
                    
                    // Refresh page after 2 seconds to show updated assignments
                    setTimeout(() => {
                        window.location.reload();
                    }, 2000);
                    
                } else {
                    alertDiv.innerHTML = `
                        <div class="alert alert-danger alert alert-dismissible fade show" role="alert">
                            <i class="fas fa-exclamation-triangle me-2"></i>${data.message || 'Assignment failed'}
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    `;
                }
            })
            .catch(error => {
                console.error('Error:', error);
                document.getElementById('assignAlert').innerHTML = `
                    <div class="alert alert-danger alert alert-dismissible fade show" role="alert">
                        <i class="fas fa-exclamation-triangle me-2"></i>An error occurred while assigning participant.
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                `;
            })
            .finally(() => {
                // Restore button state
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalText;
            });
        }

        function toggleView(view) {
            const tableView = document.getElementById('table-view');
            const cardsView = document.getElementById('cards-view');
            const buttons = document.querySelectorAll('.btn-group-sm .btn');
            
            buttons.forEach(btn => btn.classList.remove('active'));
            
            if (view === 'table') {
                tableView.classList.remove('d-none');
                cardsView.classList.add('d-none');
                buttons[0].classList.add('active');
            } else {
                tableView.classList.add('d-none');
                cardsView.classList.remove('d-none');
                buttons[1].classList.add('active');
            }
        }

        // Auto-submit filters on change
        document.querySelectorAll('select[name="gender"], select[name="category"], select[name="event"], select[name="imported"]').forEach(select => {
            select.addEventListener('change', function() {
                this.form.submit();
            });
        });


        // Enhanced import form handling
        document.getElementById('importForm')?.addEventListener('submit', function(e) {
            const eventSelect = this.querySelector('select[name="assign_event_id"]');
            const fileInput = this.querySelector('input[name="import_file"]');
            const submitBtn = this.querySelector('button[type="submit"]');
            
            // Validate event selection
            if (!eventSelect.value) {
                e.preventDefault();
                alert('Please select an event for the import.');
                eventSelect.focus();
                return false;
            }
            
            // Validate file selection
            if (!fileInput.files.length) {
                e.preventDefault();
                alert('Please select a CSV file to import.');
                fileInput.focus();
                return false;
            }
            
            // Validate file type
            const file = fileInput.files[0];
            if (!file.name.toLowerCase().endsWith('.csv')) {
                e.preventDefault();
                alert('Please select a valid CSV file.');
                fileInput.focus();
                return false;
            }
            
            // Show loading state
            const originalText = submitBtn.innerHTML;
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Processing Import...';
            
            // Create progress indicator
            const progressDiv = document.createElement('div');
            progressDiv.id = 'importProgress';
            progressDiv.className = 'mt-3';
            progressDiv.innerHTML = `
                <div class="progress">
                    <div class="progress-bar progress-bar-striped progress-bar-animated" 
                         role="progressbar" style="width: 100%">
                        Processing CSV file...
                    </div>
                </div>
                <small class="text-muted mt-1 d-block">
                    <i class="fas fa-info-circle me-1"></i>Please wait while we import your participants...
                </small>
            `;
            submitBtn.parentNode.appendChild(progressDiv);
            
            // Note: Form will submit normally, progress will be replaced by the result message
        });
        
        // File input preview
        document.querySelector('input[name="import_file"]')?.addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    const text = e.target.result;
                    const lines = text.split('\n').slice(0, 3); // First 3 lines
                    
                    // Show preview
                    let existingPreview = document.getElementById('csvPreview');
                    if (existingPreview) {
                        existingPreview.remove();
                    }
                    
                    const preview = document.createElement('div');
                    preview.id = 'csvPreview';
                    preview.className = 'mt-2 p-2 bg-light rounded border';
                    preview.innerHTML = `
                        <small class="fw-bold text-muted">CSV Preview (first 3 lines):</small>
                        <pre class="small mb-0 mt-1" style="font-size: 0.75rem;">${lines.join('\n')}</pre>
                    `;
                    
                    e.target.parentNode.appendChild(preview);
                };
                reader.readAsText(file.slice(0, 1024)); // Read first 1KB for preview
            }
        });

        // Show export notification
        document.addEventListener('DOMContentLoaded', function() {
            // Handle export button clicks
            document.querySelectorAll('a[href*="export=csv"]').forEach(link => {
                link.addEventListener('click', function(e) {
                    // Show loading indicator
                    const originalText = this.innerHTML;
                    this.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Generating CSV...';
                    this.classList.add('disabled');
                    
                    // Restore button after download starts
                    setTimeout(() => {
                        this.innerHTML = originalText;
                        this.classList.remove('disabled');
                        
                        // Show success message
                        const alertDiv = document.createElement('div');
                        alertDiv.className = 'alert alert-success alert alert-dismissible fade show';
                        alertDiv.innerHTML = `
                            <i class="fas fa-download me-2"></i>CSV export completed! Check your downloads folder.
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        `;
                        document.querySelector('.container').insertBefore(alertDiv, document.querySelector('.d-flex.justify-content-between'));
                        
                        // Auto-hide after 5 seconds
                        setTimeout(() => {
                            alertDiv.remove();
                        }, 5000);
                    }, 1000);
                });
            });
        });
    </script>
</body>
</html>