@extends('layouts.app')

@section('content')
<div class="container-fluid px-4 py-6">
    <div class="max-w-4xl mx-auto">
        <!-- Header -->
        <div class="d-flex align-items-center mb-4">
            <a href="{{ route('trainings.index') }}" class="btn btn-secondary">
                <i class="fas fa-arrow-left"></i> Back to Trainings
            </a>
        </div>

        <!-- Form Card -->
        <div class="card shadow-sm">
            <div class="card-header bg-white py-3">
                <h4 class="mb-0">Create New Training</h4>
            </div>
            <div class="card-body p-4">
                @if ($errors->any())
                    <div class="alert alert-danger">
                        <ul class="mb-0">
                            @foreach ($errors->all() as $error)
                                <li>{{ $error }}</li>
                            @endforeach
                        </ul>
                    </div>
                @endif

                <form action="{{ route('trainings.store') }}" method="POST">
                    @csrf
                    <!-- Select Training Sector -->
                    <div class="mb-4">
                        <label for="training_sector" class="form-label fw-semibold">Training Sector <span class="text-danger">*</span></label>
                        @php
                            $training_sectors = [
                                'WASH',
                                'Health',
                                'Protection',
                                'CVAs/Relief',
                                'PMER',
                                'CEA',
                                'Logistics',
                            ];
                        @endphp
                        <select name="training_sector" id="training_sector" class="form-select @error('training_sector') is-invalid @enderror" required>
                            <option value="">Select Training Sector</option>
                            @foreach($training_sectors as $training_sector)
                                <option value="{{ $training_sector }}" {{ old('training_sector') === $training_sector ? 'selected' : '' }}>
                                    {{ $training_sector }}
                                </option>
                            @endforeach
                        </select>
                        @error('training_sector')<div class="invalid-feedback">{{ $message }}</div>@enderror
                    </div>

                    <!-- Name of Training -->
                    <div class="mb-4">
                        <label for="name" class="form-label fw-semibold">Name of Training <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="name" name="name" value="{{ old('name') }}" required placeholder="e.g., Emergency Response Training">
                    </div>

                    <!-- Summary -->
                    <div class="mb-4">
                        <label for="summary" class="form-label fw-semibold">Summary of Training <span class="text-danger">*</span></label>
                        <textarea class="form-control" id="summary" name="summary" rows="3" required placeholder="Brief description of the training program...">{{ old('summary') }}</textarea>
                    </div>

                    <!-- Date of Creating Training -->
                    <div class="mb-4">
                        <label for="creation_date" class="form-label fw-semibold">Date of Creating Training <span class="text-danger">*</span></label>
                        <input type="date" class="form-control" id="creation_date" name="creation_date" value="{{ old('creation_date', date('Y-m-d')) }}" required>
                    </div>

                    <!-- Duration of Training -->
                    <div class="row mb-4">
                        <div class="col-md-4">
                            <label for="start_date" class="form-label fw-semibold">Start Date <span class="text-danger">*</span></label>
                            <input type="date" class="form-control" id="start_date" name="start_date" value="{{ old('start_date') }}" required>
                        </div>
                        <div class="col-md-4">
                            <label for="end_date" class="form-label fw-semibold">End Date <span class="text-danger">*</span></label>
                            <input type="date" class="form-control" id="end_date" name="end_date" value="{{ old('end_date') }}" required>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label fw-semibold">Duration</label>
                            <div class="form-control bg-light" id="duration-display">0 days</div>
                        </div>
                    </div>

                    <!-- Location -->
                    <div class="mb-4">
                        <label for="location" class="form-label fw-semibold">Location of Training <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="location" name="location" value="{{ old('location') }}" required placeholder="e.g., NDRT Training Center, Nairobi">
                    </div>

                    <!-- Course Outline -->
                    <div class="mb-4">
                        <label for="course_outline" class="form-label fw-semibold">Course Outline <span class="text-danger">*</span></label>
                        <textarea class="form-control" id="course_outline" name="course_outline" rows="5" required placeholder="Detailed course outline and topics to be covered...">{{ old('course_outline') }}</textarea>
                    </div>

                    <!-- Expected Participants -->
                    <div class="mb-4">
                        <label for="expected_participants" class="form-label fw-semibold">Expected Number of Participants <span class="text-danger">*</span></label>
                        <input type="number" class="form-control" id="expected_participants" name="expected_participants" value="{{ old('expected_participants') }}" min="1" required placeholder="e.g., 25">
                    </div>

                    <!-- Attendance List -->
                    <div class="mb-4">
                        <label class="form-label fw-semibold">Attendance List</label>
                        <p class="text-muted small mb-2">Select participants from the list below</p>
                        <!-- Officer Search -->
                        <input type="text" class="form-control mb-2" id="officer-search" placeholder="Search officers by name, department, or position...">
                        <div class="border rounded p-3" style="max-height: 300px; overflow-y: auto;">
                            @forelse($officers as $officer)
                                <div class="form-check mb-2 officer-entry" 
                                     data-name="{{ strtolower($officer->first_name . ' ' . $officer->surname) }}" 
                                     data-department="{{ strtolower($officer->department ?? '') }}"
                                     data-position="{{ strtolower($officer->position ?? '') }}"
                                     data-sector="{{ strtolower($officer->training_sector ?? '') }}">
                                    <input class="form-check-input" type="checkbox" name="participants[]" value="{{ $officer->id }}" id="officer_{{ $officer->id }}" 
                                        {{ in_array($officer->id, old('participants', [])) ? 'checked' : '' }}>
                                    <label class="form-check-label" for="officer_{{ $officer->id }}">
                                        <strong>{{ $officer->first_name }} {{ $officer->surname }}</strong>
                                        <small class="text-muted d-block">{{ $officer->id_number }} - {{ $officer->position }}</small>
                                    </label>
                                </div>
                            @empty
                                <p class="text-muted mb-0">No officers available. Please add officers first.</p>
                            @endforelse
                        </div>
                        <small class="text-muted mt-2 d-block">
                            <span id="selected-count">0</span> participant(s) selected
                        </small>
                    </div>

                    <!-- Trainer Name -->
                    <div class="mb-4">
                        <label for="trainer_name" class="form-label fw-semibold">Name of Trainer <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="trainer_name" name="trainer_name" value="{{ old('trainer_name') }}" required placeholder="e.g., Dr. Jane Smith">
                    </div>

                    <!-- Supervisor Name -->
                    <div class="mb-4">
                        <label for="supervisor_name" class="form-label fw-semibold">Name of Training Supervisor <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="supervisor_name" name="supervisor_name" value="{{ old('supervisor_name') }}" required placeholder="e.g., John Doe">
                    </div>

                    <!-- Remarks -->
                    <div class="mb-4">
                        <label for="remarks" class="form-label fw-semibold">Training Remarks</label>
                        <textarea class="form-control" id="remarks" name="remarks" rows="3" placeholder="Any additional remarks or notes...">{{ old('remarks') }}</textarea>
                    </div>

                    <!-- Submit Buttons -->
                    <div class="d-flex gap-2 pt-3">
                        <button type="submit" class="btn btn-success px-4">
                            <i class="fas fa-save"></i> Save Training
                        </button>
                        <a href="{{ route('trainings.index') }}" class="btn btn-outline-secondary px-4">Cancel</a>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function () {
    const startInput = document.getElementById('start_date');
    const endInput = document.getElementById('end_date');
    const durationDisplay = document.getElementById('duration-display');
    const participantCheckboxes = document.querySelectorAll('input[name="participants[]"]');
    const selectedCountEl = document.getElementById('selected-count');
    const searchInput = document.getElementById('officer-search');
    const sectorSelect = document.getElementById('training_sector');
    const officerEntries = document.querySelectorAll('.officer-entry');

    function calculateDuration() {
        if (!startInput || !endInput || !durationDisplay) {
            return;
        }

        const startDate = startInput.value;
        const endDate = endInput.value;

        if (startDate && endDate) {
            const start = new Date(startDate);
            const end = new Date(endDate);
            const diffTime = Math.abs(end - start);
            const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)) + 1;

            durationDisplay.textContent = diffDays + ' day' + (diffDays !== 1 ? 's' : '');
        }
    }

    if (startInput) {
        startInput.addEventListener('change', calculateDuration);
    }
    if (endInput) {
        endInput.addEventListener('change', calculateDuration);
    }

    function updateSelectedCount() {
        if (!selectedCountEl) {
            return;
        }

        const checked = document.querySelectorAll('input[name="participants[]"]:checked');
        selectedCountEl.textContent = checked.length;
    }

    participantCheckboxes.forEach(checkbox => {
        checkbox.addEventListener('change', updateSelectedCount);
    });

    function filterOfficers() {
        const term = (searchInput?.value || '').toLowerCase();
        const sector = (sectorSelect?.value || '').toLowerCase();

        officerEntries.forEach(entry => {
            const name = entry.dataset.name || '';
            const department = entry.dataset.department || '';
            const position = entry.dataset.position || '';
            const entrySector = entry.dataset.sector || '';

            const matchesSearch = !term || name.includes(term) || department.includes(term) || position.includes(term);
            const matchesSector = !sector || entrySector === sector;

            entry.style.display = matchesSearch && matchesSector ? '' : 'none';
        });
    }

    if (searchInput) {
        searchInput.addEventListener('input', filterOfficers);
    }
    if (sectorSelect) {
        sectorSelect.addEventListener('change', filterOfficers);
    }

    // Initialize UI state
    calculateDuration();
    updateSelectedCount();
    filterOfficers();
});
</script>
@endpush
@endsection