@extends('layouts.app')

@section('title', isset($ndrt) ? 'Edit NDRT Officer' : 'Register NDRT Officer')

@section('content')
<div class="container">
    <div class="page-header">
        <h1>{{ isset($ndrt) ? 'Edit NDRT Officer' : 'Register New NDRT Officer' }}</h1>
        <a href="{{ route('ndrt.index') }}" class="btn btn-secondary">
            <i class="fas fa-arrow-left"></i> Back to List
        </a>
    </div>

    <form action="{{ isset($ndrt) ? route('ndrt.update', $ndrt) : route('ndrt.store') }}" 
          method="POST" 
          enctype="multipart/form-data">
        @csrf
        @if(isset($ndrt))
            @method('PUT')
        @endif

        <!-- Personal Information -->
        <div class="card mb-4">
            <div class="card-header bg-primary text-white">
                <h5 class="mb-0">Personal Information</h5>
            </div>
            <div class="card-body">
                <div class="row g-3">
                    <div class="col-md-4">
                        <label class="form-label required">First Name</label>
                        <input type="text" name="first_name" class="form-control @error('first_name') is-invalid @enderror" 
                               value="{{ old('first_name', $ndrt->first_name ?? '') }}" required>
                        @error('first_name')<div class="invalid-feedback">{{ $message }}</div>@enderror
                    </div>

                    <div class="col-md-4">
                        <label class="form-label">Middle Name</label>
                        <input type="text" name="middle_name" class="form-control @error('middle_name') is-invalid @enderror" 
                               value="{{ old('middle_name', $ndrt->middle_name ?? '') }}">
                        @error('middle_name')<div class="invalid-feedback">{{ $message }}</div>@enderror
                    </div>

                    <div class="col-md-4">
                        <label class="form-label required">Surname</label>
                        <input type="text" name="surname" class="form-control @error('surname') is-invalid @enderror" 
                               value="{{ old('surname', $ndrt->surname ?? '') }}" required>
                        @error('surname')<div class="invalid-feedback">{{ $message }}</div>@enderror
                    </div>

                    <div class="col-md-6">
                        <label class="form-label required">ID Type</label>
                        <select name="id_type" class="form-select @error('id_type') is-invalid @enderror" required>
                            <option value="">Select ID Type</option>
                            @foreach(['ID', 'Passport', 'Staff ID', 'Volunteer ID'] as $type)
                                <option value="{{ $type }}" 
                                    {{ old('id_type', $ndrt->id_type ?? '') == $type ? 'selected' : '' }}>
                                    {{ $type }}
                                </option>
                            @endforeach
                        </select>
                        @error('id_type')<div class="invalid-feedback">{{ $message }}</div>@enderror
                    </div>

                    <div class="col-md-6">
                        <label class="form-label required">ID Number</label>
                        <input type="text" name="id_number" class="form-control @error('id_number') is-invalid @enderror" 
                               value="{{ old('id_number', $ndrt->id_number ?? '') }}" required>
                        @error('id_number')<div class="invalid-feedback">{{ $message }}</div>@enderror
                    </div>

                    <div class="col-md-6">
                        <label class="form-label required">Gender</label>
                        <select name="gender" class="form-select @error('gender') is-invalid @enderror" required>
                            <option value="">Select Gender</option>
                            @foreach(['Male', 'Female'] as $gender)
                                <option value="{{ $gender }}" 
                                    {{ old('gender', $ndrt->gender ?? '') == $gender ? 'selected' : '' }}>
                                    {{ $gender }}
                                </option>
                            @endforeach
                        </select>
                        @error('gender')<div class="invalid-feedback">{{ $message }}</div>@enderror
                    </div>

                    <div class="col-md-6">
                        <label class="form-label required">Date of Birth</label>
                        <input type="date" name="date_of_birth" class="form-control @error('date_of_birth') is-invalid @enderror" 
                               value="{{ old('date_of_birth', isset($ndrt) ? $ndrt->date_of_birth->format('Y-m-d') : '') }}" required>
                        @error('date_of_birth')<div class="invalid-feedback">{{ $message }}</div>@enderror
                    </div>

                    <div class="col-12">
                        <label class="form-label">Physical Address</label>
                        <textarea name="physical_address" class="form-control @error('physical_address') is-invalid @enderror" 
                                  rows="2">{{ old('physical_address', $ndrt->physical_address ?? '') }}</textarea>
                        @error('physical_address')<div class="invalid-feedback">{{ $message }}</div>@enderror
                    </div>
                </div>
            </div>
        </div>

        <!-- Location -->
        <div class="card mb-4">
            <div class="card-header bg-primary text-white">
                <h5 class="mb-0">Location</h5>
            </div>
            <div class="card-body">
                <div class="row g-3">
                    <div class="col-md-4">
                        <label class="form-label required">Location Type</label>
                        <select name="location_type" id="location_type" class="form-select @error('location_type') is-invalid @enderror" required>
                            <option value="">Select Type</option>
                            @foreach(['HQ', 'Branch'] as $type)
                                <option value="{{ $type }}" 
                                    {{ old('location_type', $ndrt->location_type ?? '') == $type ? 'selected' : '' }}>
                                    {{ $type }}
                                </option>
                            @endforeach
                        </select>
                        @error('location_type')<div class="invalid-feedback">{{ $message }}</div>@enderror
                    </div>

                    <div class="col-md-4" id="branch_field" style="display: none;">
                        <label class="form-label">Branch</label>
                        <select name="branch_id" class="form-select @error('branch_id') is-invalid @enderror">
                            <option value="">Select Branch</option>
                            @foreach($branches as $branch)
                                <option value="{{ $branch->id }}" 
                                    {{ old('branch_id', $ndrt->branch_id ?? '') == $branch->id ? 'selected' : '' }}>
                                    {{ $branch->name }}
                                </option>
                            @endforeach
                        </select>
                        @error('branch_id')<div class="invalid-feedback">{{ $message }}</div>@enderror
                    </div>

                    <div class="col-md-4">
                        <label class="form-label">Unit</label>
                        <input type="text" name="unit" class="form-control @error('unit') is-invalid @enderror" 
                               value="{{ old('unit', $ndrt->unit ?? '') }}">
                        @error('unit')<div class="invalid-feedback">{{ $message }}</div>@enderror
                    </div>
                </div>
            </div>
        </div>

        <!-- Photo -->
        <div class="card mb-4">
            <div class="card-header bg-primary text-white">
                <h5 class="mb-0">Passport Photograph</h5>
            </div>
            <div class="card-body">
                @if(isset($ndrt) && $ndrt->photo_path)
                    <div class="mb-3">
                        <img src="{{ Storage::url($ndrt->photo_path) }}" alt="Current photo" class="officer-photo-large">
                    </div>
                @endif
                <input type="file" name="photo" class="form-control @error('photo') is-invalid @enderror" accept="image/jpeg,image/jpg,image/png">
                <small class="text-muted">Accepted formats: JPEG, JPG, PNG. Max size: 2MB</small>
                @error('photo')<div class="invalid-feedback">{{ $message }}</div>@enderror
            </div>
        </div>

        <!-- Contact Details -->
        <div class="card mb-4">
            <div class="card-header bg-primary text-white">
                <h5 class="mb-0">Contact Details</h5>
            </div>
            <div class="card-body">
                <div class="row g-3">
                    <div class="col-md-4">
                        <label class="form-label required">Primary Phone</label>
                        <input type="tel" name="phone_1" class="form-control @error('phone_1') is-invalid @enderror" 
                               value="{{ old('phone_1', $ndrt->phone_1 ?? '') }}" required>
                        @error('phone_1')<div class="invalid-feedback">{{ $message }}</div>@enderror
                    </div>

                    <div class="col-md-4">
                        <label class="form-label">Secondary Phone</label>
                        <input type="tel" name="phone_2" class="form-control @error('phone_2') is-invalid @enderror" 
                               value="{{ old('phone_2', $ndrt->phone_2 ?? '') }}">
                        @error('phone_2')<div class="invalid-feedback">{{ $message }}</div>@enderror
                    </div>

                    <div class="col-md-4">
                        <label class="form-label">Email</label>
                        <input type="email" name="email" class="form-control @error('email') is-invalid @enderror" 
                               value="{{ old('email', $ndrt->email ?? '') }}">
                        @error('email')<div class="invalid-feedback">{{ $message }}</div>@enderror
                    </div>
                </div>
            </div>
        </div>

        <!-- Emergency Contact -->
        <div class="card mb-4">
            <div class="card-header bg-primary text-white">
                <h5 class="mb-0">Emergency Contact / Next of Kin</h5>
            </div>
            <div class="card-body">
                <div class="row g-3">
                    <div class="col-md-6">
                        <label class="form-label required">Name</label>
                        <input type="text" name="emergency_contact_name" class="form-control @error('emergency_contact_name') is-invalid @enderror" 
                               value="{{ old('emergency_contact_name', $ndrt->emergency_contact_name ?? '') }}" required>
                        @error('emergency_contact_name')<div class="invalid-feedback">{{ $message }}</div>@enderror
                    </div>

                    <div class="col-md-6">
                        <label class="form-label required">Relation to Kin</label>
                        <input type="text" name="emergency_contact_relation" class="form-control @error('emergency_contact_relation') is-invalid @enderror" 
                               value="{{ old('emergency_contact_relation', $ndrt->emergency_contact_relation ?? '') }}" required>
                        @error('emergency_contact_relation')<div class="invalid-feedback">{{ $message }}</div>@enderror
                    </div>

                    <div class="col-md-6">
                        <label class="form-label required">Primary Phone</label>
                        <input type="tel" name="emergency_contact_phone_1" class="form-control @error('emergency_contact_phone_1') is-invalid @enderror" 
                               value="{{ old('emergency_contact_phone_1', $ndrt->emergency_contact_phone_1 ?? '') }}" required>
                        @error('emergency_contact_phone_1')<div class="invalid-feedback">{{ $message }}</div>@enderror
                    </div>

                    <div class="col-md-6">
                        <label class="form-label">Secondary Phone</label>
                        <input type="tel" name="emergency_contact_phone_2" class="form-control @error('emergency_contact_phone_2') is-invalid @enderror" 
                               value="{{ old('emergency_contact_phone_2', $ndrt->emergency_contact_phone_2 ?? '') }}">
                        @error('emergency_contact_phone_2')<div class="invalid-feedback">{{ $message }}</div>@enderror
                    </div>

                    <div class="col-12">
                        <label class="form-label">Physical Address</label>
                        <textarea name="emergency_contact_address" class="form-control @error('emergency_contact_address') is-invalid @enderror" 
                                  rows="2">{{ old('emergency_contact_address', $ndrt->emergency_contact_address ?? '') }}</textarea>
                        @error('emergency_contact_address')<div class="invalid-feedback">{{ $message }}</div>@enderror
                    </div>
                </div>
            </div>
        </div>

        <!-- Other Details -->
        <div class="card mb-4">
            <div class="card-header bg-primary text-white">
                <h5 class="mb-0">Other Details</h5>
            </div>
            <div class="card-body">
                <div class="row g-3">
                    <div class="col-md-4">
                        <label class="form-label">Blood Group</label>
                        <select name="blood_group" class="form-select @error('blood_group') is-invalid @enderror">
                            <option value="">Select Blood Group</option>
                            @foreach(['A+', 'A-', 'B+', 'B-', 'O+', 'O-', 'AB+', 'AB-'] as $group)
                                <option value="{{ $group }}" 
                                    {{ old('blood_group', $ndrt->blood_group ?? '') == $group ? 'selected' : '' }}>
                                    {{ $group }}
                                </option>
                            @endforeach
                        </select>
                        @error('blood_group')<div class="invalid-feedback">{{ $message }}</div>@enderror
                    </div>

                    <div class="col-md-8">
                        <label class="form-label">Languages Spoken (up to 5)</label>
                        <input type="text" id="languages_input" class="form-control" placeholder="Enter languages separated by commas">
                        <div id="languages_tags" class="mt-2"></div>
                        <input type="hidden" name="languages_spoken" id="languages_hidden">
                    </div>

                    <div class="col-12">
                        <label class="form-label">Preexisting Health Conditions</label>
                        <textarea name="health_conditions" class="form-control @error('health_conditions') is-invalid @enderror" 
                                  rows="2">{{ old('health_conditions', $ndrt->health_conditions ?? '') }}</textarea>
                        @error('health_conditions')<div class="invalid-feedback">{{ $message }}</div>@enderror
                    </div>

                    <div class="col-md-6">
                        <div class="form-check">
                            <input type="checkbox" name="has_disability" id="has_disability" class="form-check-input" 
                                   value="1" {{ old('has_disability', $ndrt->has_disability ?? false) ? 'checked' : '' }}>
                            <label class="form-check-label" for="has_disability">
                                Living with a disability
                            </label>
                        </div>
                    </div>

                    <div class="col-12" id="disability_details_field" style="display: none;">
                        <label class="form-label">Disability Details</label>
                        <textarea name="disability_details" class="form-control @error('disability_details') is-invalid @enderror" 
                                  rows="2">{{ old('disability_details', $ndrt->disability_details ?? '') }}</textarea>
                        @error('disability_details')<div class="invalid-feedback">{{ $message }}</div>@enderror
                    </div>
                </div>
            </div>
        </div>

        <!-- Education -->
        <div class="card mb-4">
            <div class="card-header bg-primary text-white">
                <h5 class="mb-0">Education</h5>
            </div>
            <div class="card-body">
                <div class="row g-3">
                    <div class="col-md-6">
                        <label class="form-label">Education Level</label>
                        <select name="education_level" class="form-select @error('education_level') is-invalid @enderror">
                            <option value="">Select Level</option>
                            @foreach(['No formal education', 'Primary School', 'Secondary', 'Certificates', 'Diplomas', 'Degrees', 'Masters', 'PhD'] as $level)
                                <option value="{{ $level }}" 
                                    {{ old('education_level', $ndrt->education_level ?? '') == $level ? 'selected' : '' }}>
                                    {{ $level }}
                                </option>
                            @endforeach
                        </select>
                        @error('education_level')<div class="invalid-feedback">{{ $message }}</div>@enderror
                    </div>

                    <div class="col-md-6">
                        <label class="form-label">Area of Study</label>
                        <input type="text" name="area_of_study" class="form-control @error('area_of_study') is-invalid @enderror" 
                               value="{{ old('area_of_study', $ndrt->area_of_study ?? '') }}">
                        @error('area_of_study')<div class="invalid-feedback">{{ $message }}</div>@enderror
                    </div>
                </div>
            </div>
        </div>

        <!-- Work Experience (Dynamic - up to 3) -->
        <div class="card mb-4">
            <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
                <h5 class="mb-0">Work Experience (up to 3)</h5>
                <button type="button" class="btn btn-sm btn-light" id="add_work_exp">Add Experience</button>
            </div>
            <div class="card-body">
                <div id="work_experience_container"></div>
            </div>
        </div>

        <!-- Competencies -->
        <div class="card mb-4">
            <div class="card-header bg-primary text-white">
                <h5 class="mb-0">Competencies / Specialization within SSRC</h5>
            </div>
            <div class="card-body">
                @php
                    $competencies_list = [
                        'Disaster Risk Management',
                        'Cash and Voucher Assistance',
                        'Community engagement and accountability',
                        'Gender Protection and Inclusion',
                        'Food security and livelihoods',
                        'Shelter and settlement',
                        'Water Sanitation and Hygiene',
                        'Health',
                        'Relief',
                        'Planning monitoring, evaluation and report'
                    ];
                @endphp
                <div class="row">
                    @foreach($competencies_list as $comp)
                        <div class="col-md-6 mb-2">
                            <div class="form-check">
                                <input type="checkbox" name="competencies[]" value="{{ $comp }}" 
                                       class="form-check-input" id="comp_{{ $loop->index }}"
                                       {{ in_array($comp, old('competencies', $ndrt->competencies ?? [])) ? 'checked' : '' }}>
                                <label class="form-check-label" for="comp_{{ $loop->index }}">
                                    {{ $comp }}
                                </label>
                            </div>
                        </div>
                    @endforeach
                </div>
            </div>
        </div>

        <!-- Availability -->
        <div class="card mb-4">
            <div class="card-header bg-primary text-white">
                <h5 class="mb-0">Deployment Availability</h5>
            </div>
            <div class="card-body">
                <div class="form-check">
                    <input type="checkbox" name="available_for_deployment" id="available_for_deployment" 
                           class="form-check-input" value="1" 
                           {{ old('available_for_deployment', $ndrt->available_for_deployment ?? true) ? 'checked' : '' }}>
                    <label class="form-check-label" for="available_for_deployment">
                        Available for Deployment
                    </label>
                </div>
            </div>
        </div>

        <!-- Submit Buttons -->
        <div class="card mb-4">
            <div class="card-body text-center">
                <button type="submit" class="btn btn-success btn-lg px-5">
                    <i class="fas fa-save"></i> {{ isset($ndrt) ? 'Update Profile' : 'Register NDRT Officer' }}
                </button>
                <a href="{{ route('ndrt.index') }}" class="btn btn-secondary btn-lg px-5">
                    <i class="fas fa-times"></i> Cancel
                </a>
            </div>
        </div>
    </form>
</div>

<script>
// Location type handling
document.getElementById('location_type').addEventListener('change', function() {
    document.getElementById('branch_field').style.display = this.value === 'Branch' ? 'block' : 'none';
});

// Trigger on page load
if (document.getElementById('location_type').value === 'Branch') {
    document.getElementById('branch_field').style.display = 'block';
}

// Disability checkbox handling
document.getElementById('has_disability').addEventListener('change', function() {
    document.getElementById('disability_details_field').style.display = this.checked ? 'block' : 'none';
});

// Trigger on page load
if (document.getElementById('has_disability').checked) {
    document.getElementById('disability_details_field').style.display = 'block';
}

// Languages handling
let languages = @json(old('languages_spoken', $ndrt->languages_spoken ?? []));
updateLanguagesTags();

document.getElementById('languages_input').addEventListener('keypress', function(e) {
    if (e.key === 'Enter' || e.key === ',') {
        e.preventDefault();
        let value = this.value.trim();
        if (value && languages.length < 5 && !languages.includes(value)) {
            languages.push(value);
            this.value = '';
            updateLanguagesTags();
        }
    }
});

function updateLanguagesTags() {
    let container = document.getElementById('languages_tags');
    container.innerHTML = '';
    languages.forEach((lang, index) => {
        let tag = document.createElement('span');
        tag.className = 'badge bg-primary me-2 mb-2';
        tag.innerHTML = lang + ' <button type="button" class="btn-close btn-close-white btn-sm ms-1" onclick="removeLanguage(' + index + ')"></button>';
        container.appendChild(tag);
    });
    document.getElementById('languages_hidden').value = JSON.stringify(languages);
}

function removeLanguage(index) {
    languages.splice(index, 1);
    updateLanguagesTags();
}

// Work Experience handling
let workExperiences = @json(old('work_experience', $ndrt->work_experience ?? []));
let workExpCount = 0;

function addWorkExperience(data = null) {
    if (workExpCount >= 3) return;
    
    let container = document.getElementById('work_experience_container');
    let div = document.createElement('div');
    div.className = 'work-exp-item mb-4 p-3 border rounded';
    div.innerHTML = `
        <div class="d-flex justify-content-between mb-2">
            <h6>Experience ${workExpCount + 1}</h6>
            <button type="button" class="btn btn-sm btn-danger" onclick="removeWorkExp(this)">Remove</button>
        </div>
        <div class="row g-2">
            <div class="col-md-6">
                <input type="text" name="work_experience[${workExpCount}][position]" class="form-control" 
                       placeholder="Position" value="${data?.position || ''}" required>
            </div>
            <div class="col-md-6">
                <input type="text" name="work_experience[${workExpCount}][year]" class="form-control" 
                       placeholder="Year" value="${data?.year || ''}" required>
            </div>
            <div class="col-12">
                <input type="text" name="work_experience[${workExpCount}][institution]" class="form-control" 
                       placeholder="Name of Institution" value="${data?.institution || ''}" required>
            </div>
            <div class="col-12">
                <textarea name="work_experience[${workExpCount}][description]" class="form-control" 
                          placeholder="Brief description of roles (max 500 characters)" 
                          maxlength="500" rows="2" required>${data?.description || ''}</textarea>
            </div>
        </div>
    `;
    container.appendChild(div);
    workExpCount++;
}

function removeWorkExp(btn) {
    btn.closest('.work-exp-item').remove();
    workExpCount--;
}

document.getElementById('add_work_exp').addEventListener('click', function() {
    addWorkExperience();
});

// Load existing work experiences
workExperiences.forEach(exp => addWorkExperience(exp));
</script>
@endsection