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

$message = '';

// Get events for dropdown
$events = $pdo->query("SELECT id, name, date FROM events ORDER BY date DESC")->fetchAll(PDO::FETCH_ASSOC);

// Get distinct heat numbers for each event
$heats_query = $pdo->query("
    SELECT DISTINCT event_id, heat_number, 
           CONCAT('Heat ', heat_number) as heat_name
    FROM event_participants 
    WHERE heat_number IS NOT NULL 
    ORDER BY event_id, heat_number
");
// 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);


if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        // Check for duplicate BIB
        $bib_check = $pdo->prepare("SELECT id FROM participants WHERE bib = ?");
        $bib_check->execute([$_POST['bib']]);
        if ($bib_check->fetch()) {
            throw new Exception("BIB number already exists. Please use a different BIB number.");
        }

        // Handle file uploads
        $photo_path = null;
        $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)) {
                $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)) {
                $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");
            }
        }

        // Insert new participant
        $stmt = $pdo->prepare("INSERT INTO participants (
            bib, first_name, last_name, gender, fis_code, licence_code, licence_type,
            club, country, date_of_birth, category, photo, motion_video
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

        $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
        ]);

        $participant_id = $pdo->lastInsertId();

        // Handle participant facts (repeater field)
        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([$participant_id, trim($title), trim($fact_text), $sort_order]);
                }
            }
        }

        // If assign to event is selected
        if (!empty($_POST['assign_event_id'])) {
            $event_id = $_POST['assign_event_id'];
            
            // Add to participants_event (import tracking)
            $stmt = $pdo->prepare("INSERT INTO participants_event (participant_id, event_id) VALUES (?, ?)");
            $stmt->execute([$participant_id, $event_id]);

            // If heat is selected, also add to event_participants
            if (!empty($_POST['heat_number'])) {
                $heat_number = $_POST['heat_number'];
                
                // Check for duplicate BIB in same heat
                $bib_check = $pdo->prepare("
                    SELECT COUNT(*) FROM event_participants ep
                    JOIN participants p ON ep.participant_id = p.id
                    WHERE ep.event_id = ? AND ep.heat_number = ? AND p.bib = ?
                ");
                $bib_check->execute([$event_id, $heat_number, $_POST['bib']]);
                
                if ($bib_check->fetchColumn() == 0) {
                    $stmt = $pdo->prepare("INSERT INTO event_participants (event_id, participant_id, heat_number) VALUES (?, ?, ?)");
                    $stmt->execute([$event_id, $participant_id, $heat_number]);
                }
            }
        }

        $message = '<div class="alert alert-success alert alert-dismissible fade show" role="alert">
                        <i class="fas fa-check-circle me-2"></i>Participant added successfully!
                        <a href="participant_edit.php?id=' . $participant_id . '" class="alert alert-link">Edit participant</a> or 
                        <a href="participants.php" class="alert alert-link">view all participants</a>.
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>';
        
        // Clear form after successful submission
        $_POST = [];
        
    } 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 adding participant: ' . htmlspecialchars($e->getMessage()) . '
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>';
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add New Participant</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;
        }
        
        .fact-title {
            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'; 
            ?>
		 <div class="row justify-content-center">
       
            <div class="col-xl-10">
    <div class="container-fluid container-StyleScore p-4">
        
        <!-- Header -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h1 class="h2 mb-1">
                    <i class="fas fa-user-plus me-2 text-success"></i>
                    Add New Participant
                </h1>
                <p class="text-muted mb-0">Create a new participant profile and optionally assign to an event</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="participants.php" class="btn btn-outline-info">
                    <i class="fas fa-upload me-2"></i>Import Multiple
                </a>
            </div>
        </div>

        <?= $message ?>

        <div class="row g-4">
            
            <!-- Main Add 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-user-plus 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($_POST['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($_POST['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" <?= ($_POST['gender'] ?? '') === 'Male' ? 'selected' : '' ?>>Male</option>
                                        <option value="F" <?= ($_POST['gender'] ?? '') === 'Female' ? '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($_POST['date_of_birth'] ?? '') ?>">
                                    <div class="form-text" id="ageDisplay"></div>
                                </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($_POST['bib'] ?? '') ?>">
                                    <div class="form-text">Must be unique</div>
                                </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($_POST['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($_POST['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($_POST['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($_POST['category'] ?? '') ?>" 
                                           placeholder="e.g., U16, Senior, etc.">
                                </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($_POST['club'] ?? '') ?>">
                                </div>
                                
                                <div class="col-md-6">
                                    <label for="country" class="form-label fw-semibold">Country</label>
                                   
                                    <select name="country" class="form-control country-code" id="country">
                                        <?php echo getCountryOptions($participant['country'] ?? ''); ?>
                                    </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>
                                    <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)</div>
                                </div>
                                
                                <div class="col-md-6">
                                    <label for="motion_video" class="form-label fw-semibold">Motion Video</label>
                                    <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)</div>
                                </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">
                                        <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>
                                    </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="reset" class="btn btn-outline-warning">
                                    <i class="fas fa-undo me-2"></i>Clear Form
                                </button>
                                <button type="submit" class="btn btn-success">
                                    <i class="fas fa-user-plus me-2"></i>Add Participant
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
            
            <!-- Sidebar - Optional Assignment -->
            <div class="col-lg-4">
                
                <!-- Optional Event Assignment -->
                <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-plus me-2"></i>Optional Event Assignment
                        </h6>
                    </div>
                    <div class="border-0 shadow-none card-body">
                        <p class="text-muted small mb-3">
                            <i class="fas fa-info-circle me-1"></i>
                            Optionally assign this participant to an event immediately after creation.
                        </p>
                        
                        <div class="mb-3">
                            <label for="assign_event_id" class="form-label fw-semibold">Event</label>
                            <select id="assign_event_id" name="assign_event_id" class="form-select" form="participantForm" onchange="loadHeatsForAssignment(this.value)">
                                <option value="">No Assignment (Add Only)</option>
                                <?php foreach ($events as $event): ?>
                                    <option value="<?= $event['id'] ?>" <?= ($_POST['assign_event_id'] ?? '') == $event['id'] ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($event['name']) ?> (<?= date('M d, Y', strtotime($event['date'])) ?>)
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label for="heat_number_assign" class="form-label fw-semibold">Heat (Optional)</label>
                            <select id="heat_number_assign" name="heat_number" class="form-select" form="participantForm" disabled>
                                <option value="">Select Event First</option>
                            </select>
                            <div class="form-text">
                                <small id="heatAssignInfo" class="text-muted">Select an event to see available heats</small>
                            </div>
                        </div>
                        
                        <div class="alert alert-info alert alert-sm">
                            <i class="fas fa-lightbulb me-1"></i>
                            <small>
                                <strong>Tip:</strong> You can assign the participant to events later from the participants list.
                            </small>
                        </div>
                    </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">
                            <button type="button" class="btn btn-outline-primary btn-sm" onclick="generateBIB()">
                                <i class="fas fa-magic me-2"></i>Generate Next BIB
                            </button>
                            <a href="participants.php" class="btn btn-outline-info btn-sm">
                                <i class="fas fa-upload me-2"></i>Import Multiple Participants
                            </a>
                            <a href="participants.php" class="btn btn-outline-secondary btn-sm">
                                <i class="fas fa-list me-2"></i>View All Participants
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
 
				</div></div>
				<script>
        // Store heats data for JavaScript access
        const heatsData = <?= json_encode($heats) ?>;
        
        // Auto-calculate age when date of birth changes
        document.getElementById('date_of_birth').addEventListener('change', function() {
            const ageDisplay = document.getElementById('ageDisplay');
            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--;
                }
                
                ageDisplay.innerHTML = `<span class="text-success">Current Age: ${age} years</span>`;
            } else {
                ageDisplay.innerHTML = '';
            }
        });
        
        // 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;
            }
        });
        
        // Load heats for assignment
        function loadHeatsForAssignment(eventId) {
            const heatSelect = document.getElementById('heat_number_assign');
            const heatInfo = document.getElementById('heatAssignInfo');
            
            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</option>';
                heatInfo.innerHTML = '<span class="text-warning">No heats found for this event</span>';
                return;
            }
            
            // Populate heat dropdown
            heatSelect.disabled = false;
            heatSelect.innerHTML = '<option value="">No Heat Assignment</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>`;
        }
        
        // Generate next BIB number
        async function generateBIB() {
            try {
                const response = await fetch('ajax_generate_bib.php');
                const data = await response.json();
                
                if (data.success) {
                    document.getElementById('bib').value = data.next_bib;
                    document.getElementById('bib').focus();
                } else {
                    alert('Could not generate BIB: ' + (data.message || 'Unknown error'));
                }
            } catch (error) {
                console.error('Error generating BIB:', error);
                alert('Error generating BIB number');
            }
        }
        
        // Auto-uppercase country code
        document.getElementById('country').addEventListener('input', function() {
            this.value = this.value.toUpperCase();
        });
        
        // Clear form button
        document.querySelector('button[type="reset"]').addEventListener('click', function() {
            document.getElementById('ageDisplay').innerHTML = '';
            document.getElementById('heat_number_assign').disabled = true;
            document.getElementById('heat_number_assign').innerHTML = '<option value="">Select Event First</option>';
            document.getElementById('heatAssignInfo').textContent = 'Select an event to see available heats';
            
            // Reset facts to single item
            resetFacts();
        });
        
        // Facts repeater functionality
        let factIndex = 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';
                }
            });
        }
        
        function resetFacts() {
            const container = document.getElementById('factsContainer');
            container.innerHTML = `
                <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>
            `;
            factIndex = 1;
        }
        
        // 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>Video Selected:</strong> ${file.name}<br>
                    <small>Size: ${fileSizeMB} MB | Type: ${file.type}</small>
                `;
                videoInfo.style.display = 'block';
            }
        });
        
        // Initialize facts delete buttons
        updateFactDeleteButtons();
    </script>

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