<?php
// filepath: c:\stylescore2025\htdocs\v2\admin\participant_add.php
include '../includes/auth.php';
include '../includes/db.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.");
        }

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

        $participant_id = $pdo->lastInsertId();

        // 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 -->
<link id="bootswatch-theme"
      href="/v2/assets/bootswatch/<?= btTheme('nameCode') ?>/bootstrap.min.css"
      rel="stylesheet">
<link rel="stylesheet" href="/v2/assets/css/backgrounds.css">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">

    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
</head>
<body class="body-bg-aurora-bright">
    <?php include '../menu.php'; ?>
    <div class="container-fluid py-4">
		 <div class="row justify-content-center">
       
            <div class="col-xl-10">
    <div class="container-fluid mt-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="card ">
                    <div class="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="card-body">
                        <form method="post" id="participantForm">
                            <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>
                                    <input type="text" id="country" name="country" class="form-control" 
                                           value="<?= htmlspecialchars($_POST['country'] ?? '') ?>"
                                           placeholder="3-letter country code (e.g., USA, GER)">
                                </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="card  mb-4">
                    <div class="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="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="card ">
                    <div class="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="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();
            //const bib = document.getElementById('bib').value.trim();
            
            if (!firstName || !lastName || !bib) {
                e.preventDefault();
                alert('Please fill in all required fields (First Name, Last Name).');
                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';
        });
    </script>
</body>
</html>