<?php
// filepath: c:\stylescore2025\htdocs\v2\admin\participant_edit.php
include '../includes/auth.php';
include '../includes/db.php';
include '../includes/country_codes.php';

$id = intval($_GET['id']);
$message = '';

// 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);


$participant = $pdo->prepare("SELECT * FROM participants WHERE id = ?");
$participant->execute([$id]);
$p = $participant->fetch(PDO::FETCH_ASSOC);

if (!$p) {
    die('Participant not found.');
}

// Get participant facts
$facts_query = $pdo->prepare("SELECT * FROM participant_facts WHERE participant_id = ? ORDER BY sort_order ASC");
$facts_query->execute([$id]);
$participant_facts = $facts_query->fetchAll(PDO::FETCH_ASSOC);

// Get participant's event assignments and import history
$assignments = $pdo->prepare("
    SELECT e.id, e.name as event_name, e.date as event_date, ep.heat_number, ep.bib_number
    FROM event_participants ep
    JOIN events e ON ep.event_id = e.id
    WHERE ep.participant_id = ?
    ORDER BY e.date DESC
");
$assignments->execute([$id]);
$event_assignments = $assignments->fetchAll(PDO::FETCH_ASSOC);

$imports = $pdo->prepare("
    SELECT e.id, e.name as event_name, e.date as event_date
    FROM participants_event pe
    JOIN events e ON pe.event_id = e.id
    WHERE pe.participant_id = ?
    ORDER BY e.date DESC
");
$imports->execute([$id]);
$import_history = $imports->fetchAll(PDO::FETCH_ASSOC);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        // Handle file uploads
        $photo_path = $p['photo']; // Keep existing photo by default
        $motion_video_path = $p['motion_video']; // Keep existing video by default
        
        // Handle photo removal
        if (isset($_POST['remove_photo']) && $_POST['remove_photo'] == '1') {
            if ($p['photo'] && file_exists('../' . $p['photo'])) {
                unlink('../' . $p['photo']);
            }
            $photo_path = null;
        }
        
        // Handle motion video removal
        if (isset($_POST['remove_motion_video']) && $_POST['remove_motion_video'] == '1') {
            if ($p['motion_video'] && file_exists('../' . $p['motion_video'])) {
                unlink('../' . $p['motion_video']);
            }
            $motion_video_path = null;
        }
        
        // Create uploads directory if it doesn't exist
        $upload_dir = '../uploads/participants/';
        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0755, true);
        }
        
        // Handle photo upload
        if (isset($_FILES['photo']) && $_FILES['photo']['error'] === UPLOAD_ERR_OK) {
            $photo_ext = strtolower(pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION));
            $allowed_photo_ext = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
            
            if (in_array($photo_ext, $allowed_photo_ext)) {
                // Delete old photo if exists
                if ($p['photo'] && file_exists('../' . $p['photo'])) {
                    unlink('../' . $p['photo']);
                }
                
                $photo_filename = 'photo_' . time() . '_' . uniqid() . '.' . $photo_ext;
                $photo_path = $upload_dir . $photo_filename;
                
                if (!move_uploaded_file($_FILES['photo']['tmp_name'], $photo_path)) {
                    throw new Exception("Failed to upload photo file.");
                }
                // Store relative path for database
                $photo_path = 'uploads/participants/' . $photo_filename;
            } else {
                throw new Exception("Invalid photo file type. Allowed: JPG, JPEG, PNG, GIF, WEBP");
            }
        }
        
        // Handle motion video upload
        if (isset($_FILES['motion_video']) && $_FILES['motion_video']['error'] === UPLOAD_ERR_OK) {
            $video_ext = strtolower(pathinfo($_FILES['motion_video']['name'], PATHINFO_EXTENSION));
            $allowed_video_ext = ['mp4', 'avi', 'mov', 'wmv', 'webm', 'mkv'];
            
            if (in_array($video_ext, $allowed_video_ext)) {
                // Delete old video if exists
                if ($p['motion_video'] && file_exists('../' . $p['motion_video'])) {
                    unlink('../' . $p['motion_video']);
                }
                
                $video_filename = 'motion_' . time() . '_' . uniqid() . '.' . $video_ext;
                $motion_video_path = $upload_dir . $video_filename;
                
                if (!move_uploaded_file($_FILES['motion_video']['tmp_name'], $motion_video_path)) {
                    throw new Exception("Failed to upload motion video file.");
                }
                // Store relative path for database
                $motion_video_path = 'uploads/participants/' . $video_filename;
            } else {
                throw new Exception("Invalid video file type. Allowed: MP4, AVI, MOV, WMV, WEBM, MKV");
            }
        }

        $stmt = $pdo->prepare("UPDATE participants SET
            bib=?, first_name=?, last_name=?, gender=?, fis_code=?, licence_code=?, licence_type=?,
            club=?, country=?, date_of_birth=?, category=?, photo=?, motion_video=? WHERE id=?");

        $date_of_birth = !empty($_POST['date_of_birth']) ? $_POST['date_of_birth'] : null;

        $stmt->execute([
            $_POST['bib'], $_POST['first_name'], $_POST['last_name'], $_POST['gender'],
            $_POST['fis_code'], $_POST['licence_code'], $_POST['licence_type'],
            $_POST['club'], $_POST['country'], $date_of_birth, $_POST['category'], 
            $photo_path, $motion_video_path, $id
        ]);

        // Handle participant facts (delete old ones and insert new ones)
        $pdo->prepare("DELETE FROM participant_facts WHERE participant_id = ?")->execute([$id]);
        
        if (isset($_POST['fact_titles']) && is_array($_POST['fact_titles'])) {
            $fact_stmt = $pdo->prepare("INSERT INTO participant_facts (participant_id, title, fact, sort_order) VALUES (?, ?, ?, ?)");
            
            foreach ($_POST['fact_titles'] as $index => $title) {
                $fact_text = $_POST['fact_texts'][$index] ?? '';
                $sort_order = $index + 1;
                
                if (!empty(trim($title)) && !empty(trim($fact_text))) {
                    $fact_stmt->execute([$id, trim($title), trim($fact_text), $sort_order]);
                }
            }
        }

        $message = '<div class="alert alert-success alert alert-dismissible fade show" role="alert">
                        <i class="fas fa-check-circle me-2"></i>Participant updated successfully!
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>';
        
        // Refresh participant data
        $participant = $pdo->prepare("SELECT * FROM participants WHERE id = ?");
        $participant->execute([$id]);
        $p = $participant->fetch(PDO::FETCH_ASSOC);
        
        // Refresh facts data
        $facts_query = $pdo->prepare("SELECT * FROM participant_facts WHERE participant_id = ? ORDER BY sort_order ASC");
        $facts_query->execute([$id]);
        $participant_facts = $facts_query->fetchAll(PDO::FETCH_ASSOC);
        
    } 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>Error updating participant: ' . htmlspecialchars($e->getMessage()) . '
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>';
    }
}

// Calculate age
$age = '';
if ($p['date_of_birth']) {
    $birthDate = new DateTime($p['date_of_birth']);
    $today = new DateTime();
    $age = $birthDate->diff($today)->y;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Participant - <?= htmlspecialchars($p['first_name'] . ' ' . $p['last_name']) ?></title>
    <!-- style skin holder -->
<?php include_once '../includes/stylesheets.php'; ?>
    
    <style>
        .fact-item {
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 8px;
            padding: 15px;
            transition: all 0.3s ease;
        }
        
        .fact-item:hover {
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        
        .file-upload-info {
            font-size: 0.875rem;
            color: #6c757d;
        }
        
        .media-preview {
            max-width: 200px;
            max-height: 150px;
            border-radius: 8px;
            margin-top: 10px;
        }
        
        .existing-media {
            border: 2px dashed #28a745;
            border-radius: 8px;
            padding: 10px;
            margin-bottom: 10px;
            background: #f8fff9;
        }
        
        .media-info {
            background: #e3f2fd;
            border-left: 4px solid #2196f3;
            padding: 8px 12px;
            border-radius: 4px;
            margin-bottom: 10px;
        }
    </style>
</head>
<body class="body-bg-aurora-bright">
    <?php include '../menu.php'; ?>

    <div class="container-fluid container-StyleScore p-4">
                    <?php       
            $use_localStorage = true;
            $show_header = false;
            include 'event_actions_menu.php'; 
            ?>
        <!-- Header -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h1 class="h2 mb-1">
                    <i class="fas fa-user-edit me-2 text-primary"></i>
                    Edit Participant
                </h1>
                <p class="text-muted mb-0">
                    <span class="badge bg-primary me-2"><?= htmlspecialchars($p['bib']) ?></span>
                    <?= htmlspecialchars($p['first_name'] . ' ' . $p['last_name']) ?>
                    <?php if ($age): ?>
                        <span class="text-muted ms-2">(Age: <?= $age ?>)</span>
                    <?php endif; ?>
                </p>
            </div>
            <div class="btn-group">
                <a href="participants.php" class="btn btn-outline-secondary">
                    <i class="fas fa-arrow-left me-2"></i>Back to List
                </a>
                <a href="#" class="btn btn-outline-info"  onclick="showAssignModal(<?= $p['id'] ?>, '<?= htmlspecialchars($p['first_name'] . ' ' . $p['last_name']) ?>', '<?= htmlspecialchars($p['bib']) ?>')">
                    <i class="fas fa-calendar-plus me-2"></i>Assign to Event
                </a>
            </div>
        </div>

        <?= $message ?>

        <div class="row g-4">
            
            <!-- Main Edit Form -->
            <div class="col-lg-8">
                <div class="border-0 shadow-none card ">
                    <div class="border-0 shadow-none card-header bg-white border-0">
                        <h5 class="mb-0 fw-bold">
                            <i class="fas fa-edit me-2"></i>Participant Information
                        </h5>
                    </div>
                    <div class="border-0 shadow-none card-body">
                        <form method="post" id="participantForm" enctype="multipart/form-data">
                            <div class="row g-3">
                                
                                <!-- Personal Information -->
                                <div class="col-12">
                                    <h6 class="text-muted fw-bold border-bottom pb-2 mb-3">
                                        <i class="fas fa-user me-1"></i>Personal Information
                                    </h6>
                                </div>
                                
                                <div class="col-md-6">
                                    <label for="first_name" class="form-label fw-semibold">First Name <span class="text-danger">*</span></label>
                                    <input type="text" id="first_name" name="first_name" class="form-control" 
                                           value="<?= htmlspecialchars($p['first_name']) ?>" required>
                                </div>
                                
                                <div class="col-md-6">
                                    <label for="last_name" class="form-label fw-semibold">Last Name <span class="text-danger">*</span></label>
                                    <input type="text" id="last_name" name="last_name" class="form-control" 
                                           value="<?= htmlspecialchars($p['last_name']) ?>" required>
                                </div>
                                
                                <div class="col-md-6">
                                    <label for="gender" class="form-label fw-semibold">Gender</label>
                                    <select id="gender" name="gender" class="form-select">
                                        <option value="">Select Gender</option>
                                        <option value="M" <?= $p['gender'] === 'M' ? 'selected' : '' ?>>Male</option>
                                        <option value="F" <?= $p['gender'] === 'F' ? 'selected' : '' ?>>Female</option>
                                    </select>
                                </div>
                                
                                <div class="col-md-6">
                                    <label for="date_of_birth" class="form-label fw-semibold">Date of Birth</label>
                                    <input type="date" id="date_of_birth" name="date_of_birth" class="form-control" 
                                           value="<?= htmlspecialchars($p['date_of_birth']) ?>">
                                    <?php if ($age): ?>
                                        <div class="form-text">Current Age: <?= $age ?> years</div>
                                    <?php endif; ?>
                                </div>
                                
                                <!-- Competition Information -->
                                <div class="col-12 mt-4">
                                    <h6 class="text-muted fw-bold border-bottom pb-2 mb-3">
                                        <i class="fas fa-id-card me-1"></i>Competition Information
                                    </h6>
                                </div>
                                
                                <div class="col-md-4">
                                    <label for="bib" class="form-label fw-semibold">BIB Number</label>
                                    <input type="text" id="bib" name="bib" class="form-control" 
                                           value="<?= htmlspecialchars($p['bib']) ?>">
                                </div>
                                
                                <div class="col-md-4">
                                    <label for="fis_code" class="form-label fw-semibold">FIS Code</label>
                                    <input type="text" id="fis_code" name="fis_code" class="form-control" 
                                           value="<?= htmlspecialchars($p['fis_code']) ?>">
                                </div>
                                
                                <div class="col-md-4">
                                    <label for="licence_code" class="form-label fw-semibold">Licence Code</label>
                                    <input type="text" id="licence_code" name="licence_code" class="form-control" 
                                           value="<?= htmlspecialchars($p['licence_code']) ?>">
                                </div>
                                
                                <div class="col-md-6">
                                    <label for="licence_type" class="form-label fw-semibold">Licence Type</label>
                                    <input type="text" id="licence_type" name="licence_type" class="form-control" 
                                           value="<?= htmlspecialchars($p['licence_type']) ?>">
                                </div>
                                
                                <div class="col-md-6">
                                    <label for="category" class="form-label fw-semibold">Category</label>
                                    <input type="text" id="category" name="category" class="form-control" 
                                           value="<?= htmlspecialchars($p['category']) ?>">
                                </div>
                                
                                <!-- Club & Country Information -->
                                <div class="col-12 mt-4">
                                    <h6 class="text-muted fw-bold border-bottom pb-2 mb-3">
                                        <i class="fas fa-flag me-1"></i>Club & Country Information
                                    </h6>
                                </div>
                                
                                <div class="col-md-6">
                                    <label for="club" class="form-label fw-semibold">Club</label>
                                    <input type="text" id="club" name="club" class="form-control" 
                                           value="<?= htmlspecialchars($p['club']) ?>">
                                </div>
                                
                                <div class="col-md-6">
                                    <label for="country" class="form-label fw-semibold">Country</label>
                                   
                                           <select id="country" name="country" class="form-control country-code">
                                               <option value="<?= htmlspecialchars($p['country']) ?>"><?= getCountryDisplay($p['country']) ?></option>
                                              <?php echo getCountryOptions(); ?>
                                           </select>
                                </div>
                                
                                <!-- Media Information -->
                                <div class="col-12 mt-4">
                                    <h6 class="text-muted fw-bold border-bottom pb-2 mb-3">
                                        <i class="fas fa-photo-video me-1"></i>Media Files
                                    </h6>
                                </div>
                                
                                <div class="col-md-6">
                                    <label for="photo" class="form-label fw-semibold">Participant Photo</label>
                                    
                                    <?php if ($p['photo']): ?>
                                        <div class="existing-media">
                                            <div class="d-flex align-items-center justify-content-between">
                                                <div>
                                                    <i class="fas fa-image text-success me-2"></i>
                                                    <strong>Current Photo:</strong>
                                                    <a href="../<?= htmlspecialchars($p['photo']) ?>" target="_blank">View Photo</a>
                                                </div>
                                                <button type="button" class="btn btn-sm btn-outline-danger" onclick="removeMedia('photo')">
                                                    <i class="fas fa-trash"></i> Remove
                                                </button>
                                            </div>
                                            <img src="../<?= htmlspecialchars($p['photo']) ?>" class="media-preview mt-2" alt="Current photo">
                                        </div>
                                    <?php endif; ?>
                                    
                                    <input type="file" id="photo" name="photo" class="form-control" 
                                           accept=".jpg,.jpeg,.png,.gif,.webp">
                                    <div class="form-text">Supported formats: JPG, JPEG, PNG, GIF, WEBP (Max 5MB)
                                        <?php if ($p['photo']): ?>
                                            <br><small class="text-info">Upload a new file to replace the current photo</small>
                                        <?php endif; ?>
                                    </div>
                                    <input type="hidden" name="remove_photo" id="remove_photo" value="0">
                                </div>
                                
                                <div class="col-md-6">
                                    <label for="motion_video" class="form-label fw-semibold">Motion Video</label>
                                    
                                    <?php if ($p['motion_video']): ?>
                                        <div class="existing-media">
                                            <div class="d-flex align-items-center justify-content-between">
                                                <div>
                                                    <i class="fas fa-video text-success me-2"></i>
                                                    <strong>Current Video:</strong>
                                                    <a href="../<?= htmlspecialchars($p['motion_video']) ?>" target="_blank">View Video</a>
                                                </div>
                                                <button type="button" class="btn btn-sm btn-outline-danger" onclick="removeMedia('motion_video')">
                                                    <i class="fas fa-trash"></i> Remove
                                                </button>
                                            </div>
                                            <?php
                                            $video_file = '../' . $p['motion_video'];
                                            if (file_exists($video_file)) {
                                                $video_size = round(filesize($video_file) / (1024 * 1024), 2);
                                                echo "<div class='media-info mt-2'><small>File size: {$video_size} MB</small></div>";
                                            }
                                            ?>
                                        </div>
                                    <?php endif; ?>
                                    
                                    <input type="file" id="motion_video" name="motion_video" class="form-control" 
                                           accept=".mp4,.avi,.mov,.wmv,.webm,.mkv">
                                    <div class="form-text">Supported formats: MP4, AVI, MOV, WMV, WEBM, MKV (Max 50MB)
                                        <?php if ($p['motion_video']): ?>
                                            <br><small class="text-info">Upload a new file to replace the current video</small>
                                        <?php endif; ?>
                                    </div>
                                    <input type="hidden" name="remove_motion_video" id="remove_motion_video" value="0">
                                </div>
                                
                                <!-- Facts/Information -->
                                <div class="col-12 mt-4">
                                    <h6 class="text-muted fw-bold border-bottom pb-2 mb-3">
                                        <i class="fas fa-list-ul me-1"></i>Participant Facts & Information
                                    </h6>
                                </div>
                                
                                <div class="col-12">
                                    <div id="factsContainer">
                                        <?php if (!empty($participant_facts)): ?>
                                            <?php foreach ($participant_facts as $index => $fact): ?>
                                                <div class="fact-item mb-3" data-index="<?= $index ?>">
                                                    <div class="row g-2">
                                                        <div class="col-md-4">
                                                            <label class="form-label fw-semibold">Fact Title</label>
                                                            <input type="text" name="fact_titles[]" class="form-control" 
                                                                   value="<?= htmlspecialchars($fact['title']) ?>"
                                                                   placeholder="e.g., Specialty, Achievement, etc.">
                                                        </div>
                                                        <div class="col-md-7">
                                                            <label class="form-label fw-semibold">Fact Description</label>
                                                            <textarea name="fact_texts[]" class="form-control" rows="2" 
                                                                      placeholder="Enter the fact or information..."><?= htmlspecialchars($fact['fact']) ?></textarea>
                                                        </div>
                                                        <div class="col-md-1 d-flex align-items-end">
                                                            <button type="button" class="btn btn-outline-danger btn-sm" 
                                                                    onclick="removeFact(this)">
                                                                <i class="fas fa-trash"></i>
                                                            </button>
                                                        </div>
                                                    </div>
                                                </div>
                                            <?php endforeach; ?>
                                        <?php else: ?>
                                            <div class="fact-item mb-3" data-index="0">
                                                <div class="row g-2">
                                                    <div class="col-md-4">
                                                        <label class="form-label fw-semibold">Fact Title</label>
                                                        <input type="text" name="fact_titles[]" class="form-control" 
                                                               placeholder="e.g., Specialty, Achievement, etc.">
                                                    </div>
                                                    <div class="col-md-7">
                                                        <label class="form-label fw-semibold">Fact Description</label>
                                                        <textarea name="fact_texts[]" class="form-control" rows="2" 
                                                                  placeholder="Enter the fact or information..."></textarea>
                                                    </div>
                                                    <div class="col-md-1 d-flex align-items-end">
                                                        <button type="button" class="btn btn-outline-danger btn-sm" 
                                                                onclick="removeFact(this)" style="display: none;">
                                                            <i class="fas fa-trash"></i>
                                                        </button>
                                                    </div>
                                                </div>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                    
                                    <div class="mt-2">
                                        <button type="button" class="btn btn-outline-success btn-sm" onclick="addFact()">
                                            <i class="fas fa-plus me-1"></i>Add Another Fact
                                        </button>
                                    </div>
                                    
                                    <div class="form-text mt-2">
                                        <i class="fas fa-info-circle me-1"></i>
                                        Add interesting facts, achievements, or other information about the participant.
                                    </div>
                                </div>
                                
                            </div>
                            
                            <!-- Action Buttons -->
                            <div class="d-flex justify-content-end gap-2 mt-4 pt-3 border-top">
                                <a href="participants.php" class="btn btn-outline-secondary">
                                    <i class="fas fa-times me-2"></i>Cancel
                                </a>
                                <button type="submit" class="btn btn-success">
                                    <i class="fas fa-save me-2"></i>Save Changes
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
            
            <!-- Sidebar Information -->
            <div class="col-lg-4">
                
                <!-- Current Event Assignments -->
                <div class="border-0 shadow-none card  mb-4">
                    <div class="border-0 shadow-none card-header bg-info bg-opacity-10 border-0">
                        <h6 class="mb-0 fw-bold text-info">
                            <i class="fas fa-calendar-check me-2"></i>Event Assignments
                        </h6>
                    </div>
                    <div class="border-0 shadow-none card-body">
                        <?php if (empty($event_assignments)): ?>
                            <p class="text-muted mb-0">
                                <i class="fas fa-info-circle me-1"></i>
                                No event assignments yet
                            </p>
                        <?php else: ?>
                            <div class="list-group list-group-flush">
                                                                   <?php foreach ($event_assignments as $assignment): ?>
                                    <div class="list-group-item px-0 py-2 border-0">
                                        <div class="d-flex justify-content-between align-items-start">
                                            <div>
                                                <h6 class="mb-1 fw-semibold"><a href="heats_configure.php?event_id=<?=$assignment['id']?>"><?= htmlspecialchars($assignment['event_name']) ?></a></h6>
                                                <small class="text-muted">
                                                    <i class="fas fa-calendar me-1"></i>
                                                    <?= date('M d, Y', strtotime($assignment['event_date'])) ?>
                                                </small>
                                                <?php if ($assignment['heat_number']): ?>
                                                    <br><small class="text-muted">
                                                        <i class="fas fa-fire me-1"></i>
                                                        Heat <?= $assignment['heat_number'] ?>
                                                    </small>
                                                <?php endif; ?>
                                                <?php if ($assignment['bib_number']): ?>
                                                    <br><small class="text-muted">
                                                        <i class="fas fa-hashtag me-1"></i>
                                                        BIB <?= $assignment['bib_number'] ?>
                                                    </small>
                                                <?php endif; ?>
                                            </div>
                                            <span class="badge bg-success text-success bg-opacity-20 ">Assigned</span>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
                
                <!-- Import History -->
                <div class="border-0 shadow-none card  mb-4">
                    <div class="border-0 shadow-none card-header bg-warning bg-opacity-10 border-0">
                        <h6 class="mb-0 fw-bold text-warning">
                            <i class="fas fa-upload me-2"></i>Import History
                        </h6>
                    </div>
                    <div class="border-0 shadow-none card-body">
                        <?php if (empty($import_history)): ?>
                            <p class="text-muted mb-0">
                                <i class="fas fa-info-circle me-1"></i>
                                No import records
                            </p>
                        <?php else: ?>
                            <div class="list-group list-group-flush">
                                <?php foreach ($import_history as $import): ?>
                                    <div class="list-group-item px-0 py-2 border-0">
                                        <div class="d-flex justify-content-between align-items-start">
                                            <div>
                                                <h6 class="mb-1 fw-semibold"><a href="heats_configure.php?event_id=<?=$import['id']?>"><?= htmlspecialchars($import['event_name']) ?></a></h6>
                                                <small class="text-muted">
                                                    <i class="fas fa-calendar me-1"></i>
                                                    <?= date('M d, Y', strtotime($import['event_date'])) ?>
                                                </small>
                                            </div>
                                            <span class="badge bg-info text-info bg-opacity-20 ">
                                                <i class="fas fa-upload me-1"></i>Imported
                                            </span>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
                
                <!-- Quick Actions -->
                <div class="border-0 shadow-none card ">
                    <div class="border-0 shadow-none card-header bg-secondary bg-opacity-10 border-0">
                        <h6 class="mb-0 fw-bold text-secondary">
                            <i class="fas fa-bolt me-2"></i>Quick Actions
                        </h6>
                    </div>
                    <div class="border-0 shadow-none card-body">
                        <div class="d-grid gap-2">
                            <a href="#" class="btn btn-outline-info btn-sm" onclick="showAssignModal(<?= $p['id'] ?>, '<?= htmlspecialchars($p['first_name'] . ' ' . $p['last_name']) ?>', '<?= htmlspecialchars($p['bib']) ?>')">
                                <i class="fas fa-calendar-plus me-2"></i>Assign to Event
                            </a>
                            <a href="participants.php?search=<?= urlencode($p['bib']) ?>" class="btn btn-outline-secondary btn-sm">
                                <i class="fas fa-search me-2"></i>Find Similar BIB
                            </a>
                            <button type="button" class="btn btn-outline-danger btn-sm" onclick="confirmDelete()">
                                <i class="fas fa-trash me-2"></i>Delete Participant
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        function confirmDelete() {
            if (confirm('Are you sure you want to delete this participant? This action cannot be undone.')) {
                window.location.href = 'participants.php?delete=<?= $id ?>';
            }
        }
        
        // Auto-calculate age when date of birth changes
        document.getElementById('date_of_birth').addEventListener('change', function() {
            if (this.value) {
                const birthDate = new Date(this.value);
                const today = new Date();
                let age = today.getFullYear() - birthDate.getFullYear();
                const monthDiff = today.getMonth() - birthDate.getMonth();
                
                if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
                    age--;
                }
                
                const helpText = this.parentNode.querySelector('.form-text');
                if (helpText) {
                    helpText.textContent = `Current Age: ${age} years`;
                }
            }
        });
        
        // Form validation
        document.getElementById('participantForm').addEventListener('submit', function(e) {
            const firstName = document.getElementById('first_name').value.trim();
            const lastName = document.getElementById('last_name').value.trim();
            
            if (!firstName || !lastName) {
                e.preventDefault();
                alert('Please fill in all required fields (First Name, Last Name).');
                return false;
            }
            
            // Validate file uploads
            const photo = document.getElementById('photo').files[0];
            const video = document.getElementById('motion_video').files[0];
            
            if (photo && photo.size > 5 * 1024 * 1024) {
                e.preventDefault();
                alert('Photo file size must be less than 5MB');
                return false;
            }
            
            if (video && video.size > 50 * 1024 * 1024) {
                e.preventDefault();
                alert('Video file size must be less than 50MB');
                return false;
            }
        });
        
        // Facts repeater functionality
        let factIndex = <?= count($participant_facts) > 0 ? count($participant_facts) : 1 ?>;
        
        function addFact() {
            const container = document.getElementById('factsContainer');
            const factItem = document.createElement('div');
            factItem.className = 'fact-item mb-3';
            factItem.setAttribute('data-index', factIndex);
            
            factItem.innerHTML = `
                <div class="row g-2">
                    <div class="col-md-4">
                        <label class="form-label fw-semibold">Fact Title</label>
                        <input type="text" name="fact_titles[]" class="form-control" 
                               placeholder="e.g., Specialty, Achievement, etc.">
                    </div>
                    <div class="col-md-7">
                        <label class="form-label fw-semibold">Fact Description</label>
                        <textarea name="fact_texts[]" class="form-control" rows="2" 
                                  placeholder="Enter the fact or information..."></textarea>
                    </div>
                    <div class="col-md-1 d-flex align-items-end">
                        <button type="button" class="btn btn-outline-danger btn-sm" 
                                onclick="removeFact(this)">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                </div>
            `;
            
            container.appendChild(factItem);
            factIndex++;
            updateFactDeleteButtons();
        }
        
        function removeFact(button) {
            const factItem = button.closest('.fact-item');
            factItem.remove();
            updateFactDeleteButtons();
        }
        
        function updateFactDeleteButtons() {
            const factItems = document.querySelectorAll('.fact-item');
            factItems.forEach((item, index) => {
                const deleteBtn = item.querySelector('.btn-outline-danger');
                if (factItems.length > 1) {
                    deleteBtn.style.display = 'block';
                } else {
                    deleteBtn.style.display = 'none';
                }
            });
        }
        
        // File upload validation and preview
        document.getElementById('photo').addEventListener('change', function() {
            const file = this.files[0];
            if (file) {
                const maxSize = 5 * 1024 * 1024; // 5MB
                if (file.size > maxSize) {
                    alert('Photo file size must be less than 5MB');
                    this.value = '';
                    return;
                }
                
                // Show preview
                const reader = new FileReader();
                reader.onload = function(e) {
                    let preview = document.getElementById('photoPreview');
                    if (!preview) {
                        preview = document.createElement('img');
                        preview.id = 'photoPreview';
                        preview.className = 'media-preview';
                        document.getElementById('photo').parentNode.appendChild(preview);
                    }
                    preview.src = e.target.result;
                    preview.style.display = 'block';
                };
                reader.readAsDataURL(file);
            }
        });
        
        document.getElementById('motion_video').addEventListener('change', function() {
            const file = this.files[0];
            if (file) {
                const maxSize = 50 * 1024 * 1024; // 50MB
                if (file.size > maxSize) {
                    alert('Video file size must be less than 50MB');
                    this.value = '';
                    return;
                }
                
                // Show video info
                let videoInfo = document.getElementById('videoInfo');
                if (!videoInfo) {
                    videoInfo = document.createElement('div');
                    videoInfo.id = 'videoInfo';
                    videoInfo.className = 'alert alert-info mt-2';
                    document.getElementById('motion_video').parentNode.appendChild(videoInfo);
                }
                
                const fileSizeMB = (file.size / (1024 * 1024)).toFixed(2);
                videoInfo.innerHTML = `
                    <i class="fas fa-video me-1"></i>
                    <strong>New Video Selected:</strong> ${file.name}<br>
                    <small>Size: ${fileSizeMB} MB | Type: ${file.type}</small>
                `;
                videoInfo.style.display = 'block';
            }
        });
        
        // Remove media functionality
        function removeMedia(type) {
            if (confirm('Are you sure you want to remove this ' + type.replace('_', ' ') + '?')) {
                document.getElementById('remove_' + type).value = '1';
                const existingDiv = document.querySelector('.existing-media');
                if (existingDiv) {
                    existingDiv.style.opacity = '0.5';
                    existingDiv.innerHTML = '<div class="text-muted"><i class="fas fa-trash me-2"></i>Marked for removal (will be deleted when form is saved)</div>';
                }
            }
        }
        
        // Initialize facts delete buttons
        document.addEventListener('DOMContentLoaded', function() {
            updateFactDeleteButtons();
        });
    </script>

    
        <!-- Assignment Modal -->
    <div class="modal fade" id="assignModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-calendar-plus me-2"></i>Assign Participant to Event
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div id="assignAlert"></div>
                    
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Participant</label>
                        <div class="p-2 bg-light rounded">
                            <span id="participantInfo" class="fw-bold"></span>
                        </div>
                    </div>
                    
                    <form id="assignForm">
                        <input type="hidden" id="participantId" name="participant_id">
                        
                         <div class="mb-3">
                            <label for="eventSelect" class="form-label fw-semibold">Event</label>
                            <select id="eventSelect" name="event_id" class="form-select" required onchange="loadHeats(this.value)">
                                <option value="">Select Event</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 class="mb-3">
                            <label for="heatSelect" class="form-label fw-semibold">Heat</label>
                            <select id="heatSelect" name="heat_number" class="form-select" required disabled>
                                <option value="">Select Event First</option>
                            </select>
                            <div class="form-text">
                                <small id="heatInfo" class="text-muted">Select an event to see available heats</small>
                            </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="assignParticipant()">
                        <i class="fas fa-calendar-plus me-2"></i>Assign to Heat
                    </button>
                </div>
            </div>
        </div>
    </div>

       <!-- Assignment Modal -->
    <script>
            let assignModal;
        
        // Store heats data for JavaScript access
        const heatsData = <?= json_encode($heats) ?>;
        
        document.addEventListener('DOMContentLoaded', function() {
            assignModal = new bootstrap.Modal(document.getElementById('assignModal'));
        });

        function showAssignModal(participantId, participantName, bib) {
            document.getElementById('participantId').value = participantId;
            document.getElementById('participantInfo').innerHTML = `
                <span class="badge bg-primary me-2">${bib}</span>
                ${participantName}
            `;
            
            // Clear previous alerts and form
            document.getElementById('assignAlert').innerHTML = '';
            document.getElementById('assignForm').reset();
            document.getElementById('participantId').value = participantId;
            
            // Reset heat dropdown
            const heatSelect = document.getElementById('heatSelect');
            heatSelect.disabled = true;
            heatSelect.innerHTML = '<option value="">Select Event First</option>';
            document.getElementById('heatInfo').textContent = 'Select an event to see available heats';
            
            assignModal.show();
        }

        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();
            });
        });
    </script>

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