<?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; }
}

/* Fixed Columns for Table */
.participant-display-container {
    position: relative;
    overflow: auto;
    max-height: 70vh;
}

.participant-display-container table {
    position: relative;
}

/* Fixed Left Columns (Checkbox, BIB, Name) */
.participant-display-container th:nth-child(1),
.participant-display-container td:nth-child(1) {
    position: sticky;
    left: 0;
    background-color: white !important;
    z-index: 10;
    border-right: 2px solid #dee2e6;
}

.participant-display-container th:nth-child(2),
.participant-display-container td:nth-child(2) {
    position: sticky;
    left: 40px;
    background-color: white !important;
    z-index: 10;
    border-right: 1px solid #dee2e6;
}

.participant-display-container th:nth-child(3),
.participant-display-container td:nth-child(3) {
    position: sticky;
    left: 90px;
    background-color: white !important;
    z-index: 10;
    border-right: 2px solid #dee2e6;
    min-width: 200px;
}
.participant-display-container th:nth-child(4),
.participant-display-container td:nth-child(4) {
        padding-left: 40px;
}

/* Fixed Right Column (Actions) */
.participant-display-container th:last-child,
.participant-display-container td:last-child {
    position: sticky;
    right: 0;
    background-color: white !important;
    z-index: 10;
    border-left: 2px solid #dee2e6;
}

/* Header styling for fixed columns */
.participant-display-container thead th {
    background-color: #f8f9fa;
    z-index: 11;
}

/* Hover effect for fixed columns */
.participant-display-container tbody tr:hover th,
.participant-display-container tbody tr:hover td {
    background-color: rgba(0, 123, 255, 0.05);
}

/* 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;
}
table#participantsTable thead {
    position: sticky !important;
    top: 0;
    z-index: 55;
}

/* Excel Paste Modal Styles */
.step-container {
    min-height: 400px;
}

#pasteArea {
    min-height: 300px;
    font-size: 0.875rem;
    line-height: 1.4;
}

#editableGrid input,
#editableGrid select {
    border: 1px solid transparent;
    padding: 0.25rem 0.5rem;
}

#editableGrid input:focus,
#editableGrid select:focus {
    border-color: #0d6efd;
    background-color: #fff;
}

#editableGrid td {
    padding: 0.25rem;
    vertical-align: middle;
}

#editableGrid tbody tr:hover {
    background-color: rgba(13, 110, 253, 0.05);
}

#editableGrid .table-warning input {
    background-color: #fff3cd;
}

.column-mapping-card {
    transition: transform 0.2s;
}

.column-mapping-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 6px rgba(0,0,0,0.1);
}

#editableGrid thead {
    position: sticky;
    top: 0;
    z-index: 10;
    background-color: #212529;
}

#columnMappingArea .card {
    transition: all 0.2s;
}

#columnMappingArea .card:hover {
    box-shadow: 0 0.25rem 0.5rem rgba(0,0,0,0.15);
}
</style>
</head>
<body class="body-bg-aurora-bright">
    <?php include '../menu.php'; ?>
   
        <!-- Help Button and Modal -->
        <div class="position-fixed end-0 top-0 p-3  help_f_button" style="z-index: 1055;">
            <button type="button" class="btn btn-info btn-lg rounded-circle shadow" title="Help / Guide" data-bs-toggle="modal" data-bs-target="#helpModal" style="width:56px; height:56px;">
                <i class="fas fa-question"></i>
            </button>
        </div>
        <!-- Help Modal -->
        <div class="modal fade" id="helpModal" tabindex="-1" aria-labelledby="helpModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-xl modal-dialog-scrollable">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="helpModalLabel"><i class="fas fa-users me-2"></i>Participant Management Help</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body p-0" style="height:80vh;">
                        <iframe src="../help/participants_help.html" style="width:100%;height:100%;border:0;" title="Participant Management Help"></iframe>
                    </div>
                </div>
            </div>
        </div>
        <div class="row justify-content-center">
            <div class="col-12">
    <div class="container-fluid container-StyleScore p-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">
            <div>
                <h2 class="h4 mb-1"><i class="fas fa-users me-2 text-primary"></i>Participant Management</h2>
                <p class="mb-0 small">Manage participants with import tracking and event assignments</p>
            </div>
             <!-- Statistics Cards -->
        <div class="d-flex justify-content-between mb-3">
            <div class="">
                <div class="border-0 shadow-none card">
                    <div class="border-0 shadow-none card-body p-1">
                        <div class="d-flex align-items-center mb-2">
                            <div class="bg-primary bg-opacity-10 rounded-circle d-flex align-items-center justify-content-center me-3" style="width: 40px; height: 40px;">
                                <i class="fas fa-users text-primary"></i>
                            </div>
                            <h5 class="fw-bold text-primary mb-0"><?= $total_participants ?></h5>
                        </div>
                        <small class="text-muted">Total Participants</small>
                    </div>
                </div>
            </div>
            <div class="">
                <div class="border-0 shadow-none card">
                    <div class="border-0 shadow-none card-body p-1">
                        <div class="d-flex align-items-center mb-2">
                            <div class="bg-success bg-opacity-10 rounded-circle d-flex align-items-center justify-content-center me-3" style="width: 40px; height: 40px;">
                                <i class="fas fa-calendar-check text-success"></i>
                            </div>
                            <h5 class="fw-bold text-success mb-0"><?= $participants_with_events ?></h5>
                        </div>
                        <small class="text-muted">Assigned to Events</small>
                    </div>
                </div>
            </div>
            <div class="">
                <div class="border-0 shadow-none card">
                    <div class="border-0 shadow-none card-body p-1">
                        <div class="d-flex align-items-center mb-2">
                            <div class="bg-info bg-opacity-10 rounded-circle d-flex align-items-center justify-content-center me-3" style="width: 40px; height: 40px;">
                                <i class="fas fa-upload text-info"></i>
                            </div>
                            <h5 class="fw-bold text-info mb-0"><?= $imported_participants ?></h5>
                        </div>
                        <small class="text-muted">Imported Participants</small>
                    </div>
                </div>
            </div>
            <div class="">
                <div class="border-0 shadow-none card">
                    <div class="border-0 shadow-none card-body p-1">
                        <div class="d-flex align-items-center mb-2">
                            <div class="bg-warning bg-opacity-10 rounded-circle d-flex align-items-center justify-content-center me-3" style="width: 40px; height: 40px;">
                                <i class="fas fa-user-clock text-warning"></i>
                            </div>
                            <h5 class="fw-bold text-warning mb-0"><?= $participants_without_events ?></h5>
                        </div>
                        <small class="text-muted">Unassigned</small>
                    </div>
                </div>
            </div>
        </div>
            <a href="participant_add.php" class="btn btn-success h-100">
                <i class="fas fa-user-plus me-1"></i>Add New Participant
            </a>
        </div>

        <?php echo $message; ?>

       

        <!-- Two Column Layout -->
        <div class="row">
            <!-- Left Column: Action Cards -->
            <div class="col-3">
                <!-- Action Cards -->
               
                    
                    <!-- Import Section -->
                
                    <div class="border-1 shadow-none card border-success mb-2">
                        <div class="border-0 shadow-none card-header text-success p-2">
                            <h6 class="mb-0 fw-bold">
                                <i class="fas fa-upload me-1"></i>CSV Import
                            </h6>
                        </div>
                        <div class="border-0 shadow-none 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="">(<?= 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>
                    
                    <!-- Excel Paste Import Section -->
                    <div class="border-1 shadow-none card border-primary mb-2">
                        <div class="border-0 shadow-none card-header text-primary p-2">
                            <h6 class="mb-0 fw-bold">
                                <i class="fas fa-table me-1"></i>Excel Paste Import
                            </h6>
                        </div>
                        <div class="border-0 shadow-none card-body p-3">
                            <p class="small mb-2">
                                <i class="fas fa-info-circle me-1"></i>
                                Copy data from Excel and paste directly into the editor below.
                            </p>
                            <div class="d-grid">
                                <button type="button" class="btn btn-primary btn-sm" onclick="showExcelPasteModal()">
                                    <i class="fas fa-paste me-1"></i>Open Paste Editor
                                </button>
                            </div>
                        </div>
                    </div>
                    
                    <div class="border-1 shadow-none card border-info mb-2">
                        <div class="border-0 shadow-none card-header text-info  p-2">
                            <h6 class="mb-0 fw-bold">
                                <i class="fas fa-users-cog me-1"></i>Bulk Assignment
                            </h6>
                        </div>
                        <div class="border-0 shadow-none card-body p-3">
                            <p class="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>
                                 <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 class="btn-group">
                                   
                                </div>
                            </div>
                            
                            <div class="mt-2">
                                <small class="">
                                    <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>                           

                    <!-- Export & Actions Section -->
          
                    <div class="border-1 shadow-none card mb-2">
                        <div class="border-0 shadow-none card-header text-primary  p-2">
                            <h6 class="mb-0 fw-bold">
                                <i class="fas fa-cogs me-1"></i>Actions & Export
                            </h6>
                        </div>
                        <div class="border-0 shadow-none 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="?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>
        <!-- End Left Column -->

        <!-- Right Column: Filters & Participants Table -->
        <div class="col-9">
            <div class="border-0 shadow-none card-header bg-white p-2 d-flex justify-content-between align-items-center">
                <h6 class="mb-0 fw-bold ">
                    <i class="fas fa-table me-1"></i>Participants List (<?= count($participants) ?> results)
                </h6>
                <div class="btn-group btn-group-sm">
                   
                </div>
            </div>
            <!-- Filters -->
            <div class="border-0 shadow-none card mb-3">
                
            <div class="border-0 shadow-none 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="border-0 shadow-none card">
            
            <div class="border-0 shadow-none card-body p-0">
                
                <!-- Participant Display Container -->
                <div class="">
                    <div class="table-responsive participant-display-container">
                        <table class="table table-sm" id="participantsTable">
                            <thead class="table-light">
                                <tr>
                                    <th width="40">
                                        <input type="checkbox" id="selectAllParticipants" class="form-check-input">
                                    </th>
                                    <th width="60">BIB</th>
                                    <th>Name</th>
                                    <th width="80">Gender</th>
                                    <th>FIS Code</th>
                                    <th>Club</th>
                                    <th>Country</th>
                                    <th>Category</th>
                                    <th>Event Assignments</th>
                                    <th>Import Status</th>
                                    <th width="80">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($participants)): ?>
                                    <tr>
                                        <td colspan="11" class="text-center text-muted py-4">
                                            <i class="fas fa-users fa-3x mb-3 opacity-50"></i>
                                            <p class="mb-0">No participants found matching your criteria</p>
                                        </td>
                                    </tr>
                                <?php else: ?>
                                    <?php foreach ($participants as $p): ?>
                                    <tr class="participant-row" 
                                        data-id="<?= $p['id'] ?>"
                                        data-category="<?= htmlspecialchars($p['category'] ?? '') ?>" 
                                        data-gender="<?= htmlspecialchars($p['gender'] ?? '') ?>" 
                                        data-club="<?= htmlspecialchars($p['club'] ?? '') ?>">
                                        
                                        <td>
                                            <input type="checkbox" class="form-check-input participant-checkbox" value="<?= $p['id'] ?>">
                                        </td>
                                        <td>
                                            <span class="badge bg-secondary"><?= htmlspecialchars($p['bib']) ?></span>
                                        </td>
                                        <td>
                                            <div class="fw-bold"><?= 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' ? 'primary' : 'danger' ?>">
                                                <i class="fas fa-<?= $p['gender'] === 'M' ? 'male' : 'female' ?> me-1"></i>
                                                <?= htmlspecialchars($p['gender']) ?>
                                            </span>
                                        </td>
                                        <td><?= htmlspecialchars($p['fis_code']) ?></td>
                                        <td><?= htmlspecialchars($p['club']) ?></td>
                                        <td>
                                            <span class="country-code">
                                                <?= htmlspecialchars(getCountryEmoji($p['country'])) ?>
                                            </span>
                                        </td>
                                        <td>
                                            <span class="badge bg-info"><?= htmlspecialchars($p['category']) ?></span>
                                        </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" 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">
                                                    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" 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">
                                                    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 btn-sm" title="Edit Participant">
                                                    <i class="fas fa-edit"></i>
                                                </a>
                                                <button type="button" class="btn btn-outline-info btn-sm" 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 btn-sm" 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>
                </div>

                
            </div>
        </div>
    </div>
   
             
        
            
        </div>


        </div>
        <!-- End Right Column -->
    </div>
    <!-- End Two Column Layout -->
    </div>
    <!-- End Container -->

 <!-- 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 ">
                                <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="">
                                                <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="">(<?= 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 "></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="border-0 shadow-none card border-info">
                                            <div class="border-0 shadow-none 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="border-0 shadow-none 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="">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>
    
    <!-- Excel Paste Import Modal -->
    <div class="modal fade" id="excelPasteModal" tabindex="-1">
        <div class="modal-dialog modal-fullscreen">
            <div class="modal-content">
                <div class="modal-header bg-primary text-white">
                    <h5 class="modal-title">
                        <i class="fas fa-table me-2"></i>Excel Paste Import Editor
                    </h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <!-- Step 1: Paste Area -->
                    <div id="pasteStep" class="step-container">
                        <div class="alert alert-info">
                            <h6><i class="fas fa-clipboard me-2"></i>Step 1: Paste Your Data</h6>
                            <p class="mb-0 small">Copy data from Excel (Ctrl+C) and paste it into the text area below (Ctrl+V)</p>
                        </div>
                        <div class="row">
                            <div class="col-md-8">
                                <textarea id="pasteArea" class="form-control font-monospace" rows="15" 
                                          placeholder="Paste your Excel data here...&#10;&#10;Example (Tab-separated):&#10;BIB&#9;First Name&#9;Last Name&#9;Gender&#9;Country&#9;Year of Birth&#10;101&#9;John&#9;Doe&#9;M&#9;USA&#9;1995&#10;102&#9;Jane&#9;Smith&#9;F&#9;CAN&#9;1998"></textarea>
                                <div class="mt-2">
                                    <button type="button" class="btn btn-primary" onclick="parsePastedData()">
                                        <i class="fas fa-arrow-right me-1"></i>Parse Data
                                    </button>
                                    <button type="button" class="btn btn-outline-secondary" onclick="clearPasteArea()">
                                        <i class="fas fa-eraser me-1"></i>Clear
                                    </button>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="card bg-light">
                                    <div class="card-body">
                                        <h6 class="card-title"><i class="fas fa-lightbulb me-1"></i>Tips</h6>
                                        <ul class="small mb-0">
                                            <li>Excel automatically preserves tabs when copying</li>
                                            <li>Include column headers in your first row</li>
                                            <li>You can paste partial data and add more later</li>
                                            <li>Data will be parsed automatically on paste</li>
                                        </ul>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Step 2: Column Mapping -->
                    <div id="mappingStep" class="step-container d-none">
                        <div class="alert alert-success">
                            <h6><i class="fas fa-columns me-2"></i>Step 2: Map Columns</h6>
                            <p class="mb-0 small">Match your Excel columns to participant fields</p>
                        </div>
                        <div class="row mb-3">
                            <div class="col-12">
                                <div id="columnMappingArea" class="d-flex flex-wrap gap-2"></div>
                            </div>
                        </div>
                        <div class="d-flex gap-2">
                            <button type="button" class="btn btn-secondary" onclick="backToPaste()">
                                <i class="fas fa-arrow-left me-1"></i>Back to Paste
                            </button>
                            <button type="button" class="btn btn-success" onclick="applyMapping()">
                                <i class="fas fa-check me-1"></i>Apply Mapping & Continue
                            </button>
                        </div>
                    </div>

                    <!-- Step 3: Edit Grid -->
                    <div id="editStep" class="step-container d-none">
                        <div class="alert alert-warning">
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <h6><i class="fas fa-edit me-2"></i>Step 3: Edit & Validate Data</h6>
                                    <p class="mb-0 small">Review and edit your data. Click any cell to edit.</p>
                                </div>
                                <div>
                                    <select id="eventSelectImport" class="form-select form-select-sm" style="width: 300px;" required>
                                        <option value="">Select Event for Import *</option>
                                        <?php foreach ($events as $event): ?>
                                            <option value="<?= $event['id'] ?>">
                                                <?= htmlspecialchars($event['name']) ?> (<?= date('M d, Y', strtotime($event['date'])) ?>)
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                        </div>
                        <div class="table-responsive" style="max-height: 60vh; overflow: auto;">
                            <table id="editableGrid" class="table table-bordered table-sm table-hover">
                                <thead class="table-dark sticky-top"></thead>
                                <tbody></tbody>
                            </table>
                        </div>
                        <div class="d-flex justify-content-between align-items-center mt-3">
                            <div>
                                <button type="button" class="btn btn-secondary" onclick="backToMapping()">
                                    <i class="fas fa-arrow-left me-1"></i>Back to Mapping
                                </button>
                                <button type="button" class="btn btn-outline-primary" onclick="addRow()">
                                    <i class="fas fa-plus me-1"></i>Add Row
                                </button>
                                <button type="button" class="btn btn-outline-danger" onclick="deleteSelectedRows()">
                                    <i class="fas fa-trash me-1"></i>Delete Selected
                                </button>
                            </div>
                            <div>
                                <span class="me-3 text-muted">
                                    <i class="fas fa-users me-1"></i>
                                    <span id="rowCount">0</span> participants
                                </span>
                                <button type="button" class="btn btn-success btn-lg" onclick="importData()">
                                    <i class="fas fa-upload me-2"></i>Import to Database
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <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'));
    
    // Initialize existing checkboxes
    initializeSelectionCheckboxes();
    updateBulkAssignButton();
});

function initializeSelectionCheckboxes() {
    // Add event listeners to existing checkboxes
    const participantCheckboxes = document.querySelectorAll('.participant-checkbox');
    const selectAllCheckbox = document.getElementById('selectAllParticipants');
    
    // Add event listeners to participant checkboxes
    participantCheckboxes.forEach(checkbox => {
        checkbox.addEventListener('change', function() {
            updateSelection(this);
        });
    });
    
    // Add event listener to select all checkbox
    if (selectAllCheckbox) {
        selectAllCheckbox.addEventListener('change', function() {
            toggleSelectAll();
        });
    }
}

function toggleSelectAll() {
    const selectAllBox = document.getElementById('selectAllParticipants');
    const checkboxes = document.querySelectorAll('.participant-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('selectAllParticipants');
    const checkboxes = document.querySelectorAll('.participant-checkbox');
    const checkedBoxes = document.querySelectorAll('.participant-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('.participant-checkbox:not(.d-none)');
    visibleCheckboxes.forEach(checkbox => {
        checkbox.checked = true;
        updateSelection(checkbox);
    });
}

function clearSelection() {
    selectedParticipants = [];
    document.querySelectorAll('.participant-checkbox').forEach(checkbox => {
        checkbox.checked = false;
    });
    document.getElementById('selectAllParticipants').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="">
                <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 checkbox = document.querySelector(`.participant-checkbox[value="${id}"]`);
        if (checkbox) {
            const row = checkbox.closest('tr');
            const bibBadge = row.querySelector('.badge.bg-secondary')?.textContent.trim() || '';
            const nameDiv = row.querySelector('.fw-bold')?.textContent.trim() || '';
            
            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="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 ">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);
                });
            });
        });
    
    // ==================== Excel Paste Import Functionality ====================
    
    let excelPasteModal;
    let parsedData = [];
    let columnMapping = {};
    let editableData = [];
    
    // Field definitions
    const fieldDefinitions = [
        { key: 'bib', label: 'BIB', required: true, type: 'text' },
        { key: 'first_name', label: 'First Name', required: true, type: 'text' },
        { key: 'last_name', label: 'Last Name', required: true, type: 'text' },
        { key: 'gender', label: 'Gender', required: true, type: 'select', options: ['', 'M', 'F'] },
        { key: 'fis_code', label: 'FIS Code', required: false, type: 'text' },
        { key: 'licence_code', label: 'Licence Code', required: false, type: 'text' },
        { key: 'licence_type', label: 'Licence Type', required: false, type: 'text' },
        { key: 'club', label: 'Club', required: false, type: 'text' },
        { key: 'country', label: 'Country', required: false, type: 'text' },
        { key: 'date_of_birth', label: 'Year of Birth', required: false, type: 'year' },
        { key: 'category', label: 'Category', required: false, type: 'text' }
    ];
    
    function showExcelPasteModal() {
        if (!excelPasteModal) {
            excelPasteModal = new bootstrap.Modal(document.getElementById('excelPasteModal'));
        }
        
        // Reset to step 1
        document.getElementById('pasteStep').classList.remove('d-none');
        document.getElementById('mappingStep').classList.add('d-none');
        document.getElementById('editStep').classList.add('d-none');
        document.getElementById('pasteArea').value = '';
        
        excelPasteModal.show();
    }
    
    function clearPasteArea() {
        document.getElementById('pasteArea').value = '';
        parsedData = [];
    }
    
    function parsePastedData() {
        const pasteArea = document.getElementById('pasteArea');
        const text = pasteArea.value.trim();
        
        if (!text) {
            alert('Please paste some data first!');
            return;
        }
        
        // Parse TSV (tab-separated) or CSV
        const lines = text.split('\n').filter(line => line.trim());
        
        if (lines.length < 2) {
            alert('Please paste at least a header row and one data row.');
            return;
        }
        
        // Detect delimiter (tab or comma)
        const firstLine = lines[0];
        const delimiter = firstLine.includes('\t') ? '\t' : ',';
        
        parsedData = lines.map(line => {
            // Split by delimiter, handling quoted values
            const cells = [];
            let currentCell = '';
            let inQuotes = false;
            
            for (let i = 0; i < line.length; i++) {
                const char = line[i];
                
                if (char === '"') {
                    inQuotes = !inQuotes;
                } else if (char === delimiter && !inQuotes) {
                    cells.push(currentCell.trim());
                    currentCell = '';
                } else {
                    currentCell += char;
                }
            }
            cells.push(currentCell.trim());
            
            return cells;
        });
        
        // Auto-detect column mapping
        autoDetectMapping();
        
        // Move to mapping step
        document.getElementById('pasteStep').classList.add('d-none');
        document.getElementById('mappingStep').classList.remove('d-none');
        
        renderColumnMapping();
    }
    
    function autoDetectMapping() {
        const headers = parsedData[0].map(h => h.toLowerCase().trim());
        columnMapping = {};
        
        headers.forEach((header, index) => {
            // Try to match header to field
            const matchedField = fieldDefinitions.find(field => {
                const fieldName = field.label.toLowerCase();
                const fieldKey = field.key.toLowerCase();
                
                return header.includes(fieldKey) || 
                       header.includes(fieldName) ||
                       fieldKey.includes(header) ||
                       (field.key === 'bib' && header.match(/^(bib|number|#|no)$/)) ||
                       (field.key === 'first_name' && header.match(/(first|name|given)/)) ||
                       (field.key === 'last_name' && header.match(/(last|surname|family)/)) ||
                       (field.key === 'gender' && header.match(/(gender|sex)/)) ||
                       (field.key === 'fis_code' && header.match(/fis/)) ||
                       (field.key === 'licence_code' && header.match(/licen[cs]e/)) ||
                       (field.key === 'club' && header.match(/club/)) ||
                       (field.key === 'country' && header.match(/(country|nation)/)) ||
                       (field.key === 'date_of_birth' && header.match(/(birth|dob|born|year)/)) ||
                       (field.key === 'category' && header.match(/categor/));
            });
            
            if (matchedField) {
                columnMapping[index] = matchedField.key;
            }
        });
    }
    
    function renderColumnMapping() {
        const container = document.getElementById('columnMappingArea');
        const headers = parsedData[0];
        
        container.innerHTML = '';
        
        headers.forEach((header, index) => {
            const card = document.createElement('div');
            card.className = 'card';
            card.style.minWidth = '200px';
            card.innerHTML = `
                <div class="card-body p-2">
                    <div class="small text-muted mb-1">Column ${index + 1}</div>
                    <div class="fw-bold mb-2">${header || '(No Header)'}</div>
                    <select class="form-select form-select-sm" data-column="${index}">
                        <option value="">-- Skip Column --</option>
                        ${fieldDefinitions.map(field => `
                            <option value="${field.key}" ${columnMapping[index] === field.key ? 'selected' : ''}>
                                ${field.label}${field.required ? ' *' : ''}
                            </option>
                        `).join('')}
                    </select>
                    <div class="small text-muted mt-1">
                        Sample: ${parsedData[1] ? parsedData[1][index] || '(empty)' : ''}
                    </div>
                </div>
            `;
            container.appendChild(card);
            
            // Add event listener
            card.querySelector('select').addEventListener('change', function() {
                const colIndex = parseInt(this.dataset.column);
                const value = this.value;
                
                if (value) {
                    // Remove this field from other mappings
                    Object.keys(columnMapping).forEach(key => {
                        if (columnMapping[key] === value && key != colIndex) {
                            delete columnMapping[key];
                        }
                    });
                    columnMapping[colIndex] = value;
                } else {
                    delete columnMapping[colIndex];
                }
                
                // Update all selects
                renderColumnMapping();
            });
        });
    }
    
    function backToPaste() {
        document.getElementById('pasteStep').classList.remove('d-none');
        document.getElementById('mappingStep').classList.add('d-none');
    }
    
    function applyMapping() {
        // Validate required fields are mapped
        const requiredFields = fieldDefinitions.filter(f => f.required).map(f => f.key);
        const mappedFields = Object.values(columnMapping);
        
        const missingFields = requiredFields.filter(field => !mappedFields.includes(field));
        
        if (missingFields.length > 0) {
            alert('Please map the following required fields:\n' + missingFields.join(', '));
            return;
        }
        
        // Transform data according to mapping
        editableData = [];
        
        for (let i = 1; i < parsedData.length; i++) {
            const row = {};
            
            fieldDefinitions.forEach(field => {
                row[field.key] = '';
            });
            
            Object.keys(columnMapping).forEach(colIndex => {
                const fieldKey = columnMapping[colIndex];
                row[fieldKey] = parsedData[i][colIndex] || '';
            });
            
            // Add internal ID
            row._id = Date.now() + i;
            row._selected = false;
            
            editableData.push(row);
        }
        
        // Move to edit step
        document.getElementById('mappingStep').classList.add('d-none');
        document.getElementById('editStep').classList.remove('d-none');
        
        renderEditableGrid();
    }
    
    function backToMapping() {
        document.getElementById('mappingStep').classList.remove('d-none');
        document.getElementById('editStep').classList.add('d-none');
    }
    
    function renderEditableGrid() {
        const table = document.getElementById('editableGrid');
        const thead = table.querySelector('thead');
        const tbody = table.querySelector('tbody');
        
        // Render header
        thead.innerHTML = `
            <tr>
                <th style="width: 40px;">
                    <input type="checkbox" class="form-check-input" onchange="toggleSelectAll(this)">
                </th>
                ${fieldDefinitions.map(field => `
                    <th>${field.label}${field.required ? ' <span class="text-danger">*</span>' : ''}</th>
                `).join('')}
                <th style="width: 80px;">Actions</th>
            </tr>
        `;
        
        // Render rows
        tbody.innerHTML = '';
        editableData.forEach((row, rowIndex) => {
            const tr = document.createElement('tr');
            tr.dataset.rowId = row._id;
            if (row._selected) tr.classList.add('table-primary');
            
            tr.innerHTML = `
                <td class="text-center">
                    <input type="checkbox" class="form-check-input row-select" ${row._selected ? 'checked' : ''} 
                           onchange="toggleRowSelect(${row._id}, this)">
                </td>
                ${fieldDefinitions.map(field => renderCell(row, field, rowIndex)).join('')}
                <td class="text-center">
                    <button type="button" class="btn btn-sm btn-outline-danger" onclick="deleteRow(${row._id})" title="Delete">
                        <i class="fas fa-trash"></i>
                    </button>
                </td>
            `;
            
            tbody.appendChild(tr);
        });
        
        // Update count
        document.getElementById('rowCount').textContent = editableData.length;
    }
    
    function renderCell(row, field, rowIndex) {
        const value = row[field.key] || '';
        const cellClass = field.required && !value ? 'table-warning' : '';
        
        if (field.type === 'select') {
            return `
                <td class="${cellClass}">
                    <select class="form-select form-select-sm" 
                            onchange="updateCell(${row._id}, '${field.key}', this.value)">
                        ${field.options.map(opt => `
                            <option value="${opt}" ${value === opt ? 'selected' : ''}>${opt || '(empty)'}</option>
                        `).join('')}
                    </select>
                </td>
            `;
        } else if (field.type === 'year') {
            // Year-only input
            return `
                <td class="${cellClass}">
                    <input type="number" class="form-control form-control-sm" 
                           value="${value}" 
                           min="1900" 
                           max="2100"
                           step="1"
                           placeholder="YYYY"
                           onchange="updateCell(${row._id}, '${field.key}', this.value)"
                           ${field.required ? 'required' : ''}>
                </td>
            `;
        } else {
            return `
                <td class="${cellClass}">
                    <input type="${field.type}" class="form-control form-control-sm" 
                           value="${value}" 
                           onchange="updateCell(${row._id}, '${field.key}', this.value)"
                           ${field.required ? 'required' : ''}>
                </td>
            `;
        }
    }
    
    function updateCell(rowId, fieldKey, value) {
        const row = editableData.find(r => r._id === rowId);
        if (row) {
            row[fieldKey] = value;
            // Re-render to update validation
            renderEditableGrid();
        }
    }
    
    function toggleRowSelect(rowId, checkbox) {
        const row = editableData.find(r => r._id === rowId);
        if (row) {
            row._selected = checkbox.checked;
            checkbox.closest('tr').classList.toggle('table-primary', checkbox.checked);
        }
    }
    
    function toggleSelectAll(checkbox) {
        editableData.forEach(row => {
            row._selected = checkbox.checked;
        });
        renderEditableGrid();
    }
    
    function addRow() {
        const newRow = {
            _id: Date.now(),
            _selected: false
        };
        
        fieldDefinitions.forEach(field => {
            newRow[field.key] = '';
        });
        
        editableData.push(newRow);
        renderEditableGrid();
    }
    
    function deleteRow(rowId) {
        if (confirm('Delete this row?')) {
            editableData = editableData.filter(r => r._id !== rowId);
            renderEditableGrid();
        }
    }
    
    function deleteSelectedRows() {
        const selectedCount = editableData.filter(r => r._selected).length;
        
        if (selectedCount === 0) {
            alert('No rows selected!');
            return;
        }
        
        if (confirm(`Delete ${selectedCount} selected row(s)?`)) {
            editableData = editableData.filter(r => !r._selected);
            renderEditableGrid();
        }
    }
    
    function importData() {
        const eventId = document.getElementById('eventSelectImport').value;
        
        if (!eventId) {
            alert('Please select an event for import!');
            return;
        }
        
        // Validate required fields
        const invalidRows = [];
        editableData.forEach((row, index) => {
            const requiredFields = fieldDefinitions.filter(f => f.required);
            const missingFields = requiredFields.filter(field => !row[field.key] || !row[field.key].trim());
            
            if (missingFields.length > 0) {
                invalidRows.push({
                    index: index + 1,
                    fields: missingFields.map(f => f.label).join(', ')
                });
            }
        });
        
        if (invalidRows.length > 0) {
            const message = 'The following rows are missing required fields:\n\n' +
                invalidRows.slice(0, 5).map(r => `Row ${r.index}: ${r.fields}`).join('\n') +
                (invalidRows.length > 5 ? `\n...and ${invalidRows.length - 5} more rows` : '');
            
            alert(message);
            return;
        }
        
        if (!confirm(`Import ${editableData.length} participants to the database?`)) {
            return;
        }
        
        // Prepare data for submission
        const importBtn = event.target;
        importBtn.disabled = true;
        importBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Importing...';
        
        // Send to server
        fetch('participants_excel_import.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                event_id: eventId,
                participants: editableData.map(row => {
                    const cleaned = {};
                    fieldDefinitions.forEach(field => {
                        cleaned[field.key] = row[field.key] || '';
                    });
                    return cleaned;
                })
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert(`Success! ${data.imported} participants imported, ${data.updated} updated.`);
                excelPasteModal.hide();
                window.location.reload();
            } else {
                alert('Import failed: ' + (data.message || 'Unknown error'));
                importBtn.disabled = false;
                importBtn.innerHTML = '<i class="fas fa-upload me-2"></i>Import to Database';
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Import failed: ' + error.message);
            importBtn.disabled = false;
            importBtn.innerHTML = '<i class="fas fa-upload me-2"></i>Import to Database';
        });
    }
    
    </script>
    <?php include 'footer.php'; ?>
</body>
</html>