@extends('layouts.app')

@section('content')
<div class="container-fluid">
    <div class="mb-4">
        <h4 class="mb-1"><i class="bi bi-plus-square"></i> Tambah Mapping Pegawai</h4>
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb mb-0">
                <li class="breadcrumb-item"><a href="{{ route('dashboard') }}">Dashboard</a></li>
                <li class="breadcrumb-item"><a href="{{ route('superadmin.employee-assignments.index') }}">Mapping Pegawai</a></li>
                <li class="breadcrumb-item active">Tambah</li>
            </ol>
        </nav>
    </div>

    <div class="row">
        <div class="col-lg-8">
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-primary text-white">
                    <h6 class="mb-0"><i class="bi bi-diagram-3"></i> Form Mapping Pegawai</h6>
                </div>
                <div class="card-body">
                    <form action="{{ route('superadmin.employee-assignments.store') }}" method="POST">
                        @csrf

                        <div class="mb-3">
                            <label for="employee_id" class="form-label">Pegawai <span class="text-danger">*</span></label>
                            <select class="form-select @error('employee_id') is-invalid @enderror" 
                                    id="employee_id" 
                                    name="employee_id" 
                                    required>
                                <option value="">-- Pilih Pegawai --</option>
                                @foreach($employees as $employee)
                                    <option value="{{ $employee->id }}" {{ old('employee_id') == $employee->id ? 'selected' : '' }}>
                                        {{ $employee->name }} - {{ $employee->nip }}
                                        @if($employee->rank) ({{ $employee->rank }}) @endif
                                    </option>
                                @endforeach
                            </select>
                            @error('employee_id')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>

                        <div class="mb-3">
                            <label for="assignment_type" class="form-label">Tipe Penugasan <span class="text-danger">*</span></label>
                            <select class="form-select @error('assignment_type') is-invalid @enderror" 
                                    id="assignment_type" 
                                    name="assignment_type" 
                                    required>
                                <option value="">-- Pilih Tipe --</option>
                                <option value="{{ $assignmentTypes['TYPE_KCD'] }}" {{ old('assignment_type') == $assignmentTypes['TYPE_KCD'] ? 'selected' : '' }}>Staff KCD</option>
                                <option value="{{ $assignmentTypes['TYPE_SCHOOL'] }}" {{ old('assignment_type') == $assignmentTypes['TYPE_SCHOOL'] ? 'selected' : '' }}>Penugasan ke Sekolah</option>
                            </select>
                            @error('assignment_type')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                            <small class="text-muted">Staff KCD = pegawai ditempatkan di kantor KCD. Penugasan ke Sekolah = pegawai ditempatkan di sekolah tertentu</small>
                        </div>

                        <div class="mb-3">
                            <label for="kcd_id" class="form-label">KCD <span class="text-danger">*</span></label>
                            <select class="form-select @error('kcd_id') is-invalid @enderror" 
                                    id="kcd_id" 
                                    name="kcd_id"
                                    required>
                                <option value="">-- Pilih KCD --</option>
                                @foreach($kcds as $kcd)
                                    <option value="{{ $kcd->id }}" 
                                            data-kcd-code="{{ $kcd->code }}"
                                            {{ old('kcd_id') == $kcd->id ? 'selected' : '' }}>
                                        {{ $kcd->code }} - {{ $kcd->name }}
                                    </option>
                                @endforeach
                            </select>
                            @error('kcd_id')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>

                        <div class="mb-3" id="kabkota-field" style="display: none;">
                            <label for="kab_kota_id" class="form-label">Kab/Kota <span class="text-danger" id="kabkota-required">*</span></label>
                            <select class="form-select @error('kab_kota_id') is-invalid @enderror" 
                                    id="kab_kota_id" 
                                    name="kab_kota_id">
                                <option value="">-- Pilih Kab/Kota --</option>
                                @foreach($kabKotas as $kabKota)
                                    <option value="{{ $kabKota->id }}" 
                                            data-kcd-code="{{ $kabKota->kcd_code }}"
                                            {{ old('kab_kota_id') == $kabKota->id ? 'selected' : '' }}>
                                        {{ $kabKota->name }}
                                    </option>
                                @endforeach
                            </select>
                            @error('kab_kota_id')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                            <small class="text-muted">Hanya menampilkan kab/kota yang sesuai dengan KCD yang dipilih</small>
                        </div>

                        <div class="mb-3" id="school-field" style="display: none;">
                            <label for="school_id" class="form-label">Sekolah <span class="text-danger" id="school-required">*</span></label>
                            <select class="form-select @error('school_id') is-invalid @enderror" 
                                    id="school_id" 
                                    name="school_id">
                                <option value="">-- Pilih Sekolah --</option>
                                @foreach($schools as $school)
                                    <option value="{{ $school->id }}" 
                                            data-kcd-id="{{ $school->kcd_id }}"
                                            data-kabkota-id="{{ $school->kab_kota_id }}"
                                            {{ old('school_id') == $school->id ? 'selected' : '' }}>
                                        {{ $school->name }} ({{ $school->npsn }})
                                    </option>
                                @endforeach
                            </select>
                            @error('school_id')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                            <small class="text-muted">Hanya menampilkan sekolah yang sesuai dengan kab/kota yang dipilih</small>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="start_date" class="form-label">Tanggal Mulai <span class="text-danger">*</span></label>
                                    <input type="date" 
                                           class="form-control @error('start_date') is-invalid @enderror" 
                                           id="start_date" 
                                           name="start_date" 
                                           value="{{ old('start_date') }}" 
                                           required>
                                    @error('start_date')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>

                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="end_date" class="form-label">Tanggal Selesai</label>
                                    <input type="date" 
                                           class="form-control @error('end_date') is-invalid @enderror" 
                                           id="end_date" 
                                           name="end_date" 
                                           value="{{ old('end_date') }}">
                                    @error('end_date')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                    <small class="text-muted">Kosongkan jika masih aktif</small>
                                </div>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label for="notes" class="form-label">Catatan</label>
                            <textarea class="form-control @error('notes') is-invalid @enderror" 
                                      id="notes" 
                                      name="notes" 
                                      rows="3" 
                                      placeholder="Catatan tambahan untuk penugasan ini">{{ old('notes') }}</textarea>
                            @error('notes')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>

                        <div class="mb-3">
                            <div class="form-check form-switch">
                                <input class="form-check-input" 
                                       type="checkbox" 
                                       id="is_active" 
                                       name="is_active" 
                                       value="1" 
                                       {{ old('is_active', true) ? 'checked' : '' }}>
                                <label class="form-check-label" for="is_active">
                                    Status Aktif
                                </label>
                            </div>
                        </div>

                        <div class="d-flex gap-2">
                            <button type="submit" class="btn btn-primary">
                                <i class="bi bi-save"></i> Simpan
                            </button>
                            <a href="{{ route('superadmin.employee-assignments.index') }}" class="btn btn-secondary">
                                <i class="bi bi-arrow-left"></i> Kembali
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <div class="col-lg-4">
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-info text-white">
                    <h6 class="mb-0"><i class="bi bi-info-circle"></i> Informasi</h6>
                </div>
                <div class="card-body">
                    <ul class="small mb-0">
                        <li><strong>Staff KCD:</strong> Pegawai ditempatkan di kantor KCD (tidak ke sekolah tertentu)</li>
                        <li><strong>Penugasan ke Sekolah:</strong> Pegawai ditempatkan di sekolah tertentu</li>
                        <li>Pilih KCD terlebih dahulu</li>
                        <li>Untuk penugasan sekolah: sistem akan memfilter Kab/Kota dan Sekolah secara otomatis</li>
                        <li>Tanggal selesai opsional (kosongkan jika masih aktif)</li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function() {
    const assignmentType = document.getElementById('assignment_type');
    const kcdSelect = document.getElementById('kcd_id');
    const kabKotaField = document.getElementById('kabkota-field');
    const kabKotaSelect = document.getElementById('kab_kota_id');
    const schoolField = document.getElementById('school-field');
    const schoolSelect = document.getElementById('school_id');
    
    // Toggle fields based on assignment type
    function toggleFields() {
        const type = assignmentType.value;
        
        if (type === '{{ $assignmentTypes['TYPE_KCD'] }}') {
            // Staff KCD: show KCD only
            kabKotaField.style.display = 'none';
            schoolField.style.display = 'none';
            kcdSelect.required = true;
            kabKotaSelect.required = false;
            schoolSelect.required = false;
            kabKotaSelect.value = '';
            schoolSelect.value = '';
        } else if (type === '{{ $assignmentTypes['TYPE_SCHOOL'] }}') {
            // Penugasan Sekolah: show all cascading
            kabKotaField.style.display = 'block';
            schoolField.style.display = 'block';
            kcdSelect.required = true;
            kabKotaSelect.required = true;
            schoolSelect.required = true;
            filterKabKota();
        } else {
            // No type selected
            kabKotaField.style.display = 'none';
            schoolField.style.display = 'none';
            kcdSelect.required = false;
            kabKotaSelect.required = false;
            schoolSelect.required = false;
        }
    }
    
    // Filter Kab/Kota based on selected KCD
    function filterKabKota() {
        const selectedKcdOption = kcdSelect.options[kcdSelect.selectedIndex];
        if (!selectedKcdOption || !selectedKcdOption.value) {
            hideAllKabKota();
            return;
        }
        
        const kcdCode = selectedKcdOption.getAttribute('data-kcd-code');
        const kabKotaOptions = kabKotaSelect.querySelectorAll('option');
        
        let visibleCount = 0;
        kabKotaOptions.forEach(option => {
            if (!option.value) {
                option.style.display = '';
                return;
            }
            
            const optionKcdCode = option.getAttribute('data-kcd-code');
            
            if (optionKcdCode === kcdCode) {
                option.style.display = '';
                visibleCount++;
            } else {
                option.style.display = 'none';
            }
        });
        
        // Reset selection if current selection is hidden
        const currentSelection = kabKotaSelect.options[kabKotaSelect.selectedIndex];
        if (currentSelection && currentSelection.style.display === 'none') {
            kabKotaSelect.value = '';
        }
        
        // Trigger school filter
        filterSchools();
    }
    
    function hideAllKabKota() {
        const kabKotaOptions = kabKotaSelect.querySelectorAll('option');
        kabKotaOptions.forEach(option => {
            if (option.value) {
                option.style.display = 'none';
            }
        });
        kabKotaSelect.value = '';
        filterSchools();
    }
    
    // Filter Schools based on selected Kab/Kota
    function filterSchools() {
        const selectedKabKotaId = kabKotaSelect.value;
        const schoolOptions = schoolSelect.querySelectorAll('option');
        
        if (!selectedKabKotaId) {
            schoolOptions.forEach(option => {
                if (option.value) {
                    option.style.display = 'none';
                }
            });
            schoolSelect.value = '';
            return;
        }
        
        let visibleCount = 0;
        schoolOptions.forEach(option => {
            if (!option.value) {
                option.style.display = '';
                return;
            }
            
            const optionKabKotaId = option.getAttribute('data-kabkota-id');
            
            if (optionKabKotaId === selectedKabKotaId) {
                option.style.display = '';
                visibleCount++;
            } else {
                option.style.display = 'none';
            }
        });
        
        // Reset selection if current selection is hidden
        const currentSelection = schoolSelect.options[schoolSelect.selectedIndex];
        if (currentSelection && currentSelection.style.display === 'none') {
            schoolSelect.value = '';
        }
    }
    
    // Event listeners
    assignmentType.addEventListener('change', toggleFields);
    kcdSelect.addEventListener('change', filterKabKota);
    kabKotaSelect.addEventListener('change', filterSchools);
    
    // Initialize on page load
    toggleFields();
});
</script>
@endpush
@endsection
