@extends('layouts.app')

@section('title', 'Edit User - Superadmin')

@section('content')
<div class="page-header">
    <h1 class="page-title">Edit User: {{ $user->name }}</h1>
    <nav aria-label="breadcrumb">
        <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="{{ route('superadmin.users.index') }}">Manajemen User</a></li>
            <li class="breadcrumb-item active">Edit User</li>
        </ol>
    </nav>
</div>

<div class="row">
    <div class="col-lg-8">
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-white border-bottom">
                <h5 class="card-title mb-0"><i class="bi bi-pencil"></i> Form Edit User</h5>
            </div>
            <div class="card-body">
                <form action="{{ route('superadmin.users.update', $user) }}" method="POST">
                    @csrf
                    @method('PUT')

                    <div class="mb-3">
                        <label for="role_id" class="form-label">Role <span class="text-danger">*</span></label>
                        <select class="form-select @error('role_id') is-invalid @enderror" id="role_id" name="role_id" required>
                            <option value="">Pilih Role</option>
                            @foreach($roles as $role)
                                <option value="{{ $role->id }}" data-slug="{{ $role->slug }}" {{ old('role_id', $user->role_id) == $role->id ? 'selected' : '' }}>
                                    {{ $role->name }}
                                </option>
                            @endforeach
                        </select>
                        @error('role_id')
                            <div class="invalid-feedback d-block">{{ $message }}</div>
                        @enderror
                    </div>

                    <!-- School Field for Admin Sekolah -->
                    <div class="mb-3" id="schoolField" style="display: {{ old('school_id', $user->school_id) ? 'block' : 'none' }};">
                        <label for="school_id" class="form-label">Sekolah <span class="text-danger">*</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-npsn="{{ $school->npsn }}" {{ old('school_id', $user->school_id) == $school->id ? 'selected' : '' }}>
                                    {{ $school->npsn }} - {{ $school->name }}
                                </option>
                            @endforeach
                        </select>
                        @error('school_id')
                            <div class="invalid-feedback d-block">{{ $message }}</div>
                        @enderror
                        <small class="text-muted">NPSN: <strong id="npsnDisplay">{{ $user->npsn ?? '-' }}</strong> (otomatis dari sekolah yang dipilih)</small>
                    </div>

                    <!-- NIP Field -->
                    <div class="mb-3" id="nipField">
                        <label for="nip" class="form-label">NIP <span class="text-danger" id="nipRequired">*</span></label>
                        <input type="text" class="form-control" id="nip" name="nip" value="{{ old('nip', $user->nip) }}" placeholder="NIP 18 digit" pattern="\d{18}">
                        <small class="text-muted"><i class="bi bi-info-circle"></i> NIP untuk login (khusus non-admin sekolah)</small>
                        @error('nip')
                            <div class="invalid-feedback d-block">{{ $message }}</div>
                        @enderror
                    </div>

                    <div class="mb-3">
                        <label for="name" class="form-label">Nama <span class="text-danger">*</span></label>
                        <input type="text" class="form-control @error('name') is-invalid @enderror" id="name" name="name" value="{{ old('name', $user->name) }}" required>
                        @error('name')
                            <div class="invalid-feedback d-block">{{ $message }}</div>
                        @enderror
                    </div>

                    <div class="mb-3" id="pangkatField">
                        <label for="pangkat_golongan" class="form-label">Pangkat dan Golongan <span class="text-danger" id="pangkatRequired">*</span></label>
                        <input type="text" class="form-control @error('pangkat_golongan') is-invalid @enderror" id="pangkat_golongan" name="pangkat_golongan" value="{{ old('pangkat_golongan', $user->pangkat_golongan) }}" placeholder="contoh: Pembina / IV b">
                        @error('pangkat_golongan')
                            <div class="invalid-feedback d-block">{{ $message }}</div>
                        @enderror
                    </div>

                    <div class="mb-3" id="emailField">
                        <label for="email" class="form-label">Email <span class="text-danger" id="emailRequired">*</span></label>
                        <input type="email" class="form-control @error('email') is-invalid @enderror" id="email" name="email" value="{{ old('email', $user->email) }}">
                        @error('email')
                            <div class="invalid-feedback d-block">{{ $message }}</div>
                        @enderror
                        <small class="text-muted" id="emailHint" style="display: none;">Untuk admin sekolah, email opsional (akan auto-generate jika kosong)</small>
                    </div>

                    <div class="mb-3">
                        <label for="phone" class="form-label">No. Telepon</label>
                        <input type="text" class="form-control @error('phone') is-invalid @enderror" id="phone" name="phone" value="{{ old('phone', $user->phone) }}" placeholder="08xxxxxxxxxx">
                        @error('phone')
                            <div class="invalid-feedback d-block">{{ $message }}</div>
                        @enderror
                    </div>

                    <div class="mb-3">
                        <label for="alamat" class="form-label">Alamat <span class="text-danger">*</span></label>
                        <textarea class="form-control @error('alamat') is-invalid @enderror" id="alamat" name="alamat" rows="2" placeholder="Jalan, No., Kelurahan, Kecamatan, Kota" required>{{ old('alamat', $user->alamat) }}</textarea>
                        @error('alamat')
                            <div class="invalid-feedback d-block">{{ $message }}</div>
                        @enderror
                    </div>

                    <div class="alert alert-info" role="alert">
                        <i class="bi bi-info-circle"></i> Kosongkan password jika tidak ingin mengubahnya
                    </div>

                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="password" class="form-label">Password Baru</label>
                            <input type="password" class="form-control @error('password') is-invalid @enderror" id="password" name="password">
                            @error('password')
                                <div class="invalid-feedback d-block">{{ $message }}</div>
                            @enderror
                            <small class="text-muted">Minimal 8 karakter</small>
                        </div>

                        <div class="col-md-6 mb-3">
                            <label for="password_confirmation" class="form-label">Konfirmasi Password</label>
                            <input type="password" class="form-control" id="password_confirmation" name="password_confirmation">
                        </div>
                    </div>

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

                    <!-- Pengawas-specific mappings -->
                    <div id="pengawasSection" style="display: none;">
                        <hr class="my-4">
                        <h6 class="border-bottom pb-2 mb-3"><strong><i class="bi bi-diagram-3"></i> Mapping Pengawas</strong></h6>

                        <div class="mb-3">
                            <label for="kcd_ids" class="form-label">Assign ke KCD <span class="text-danger">*</span></label>
                            <select class="form-select" id="kcd_ids" name="kcd_ids[]" multiple>
                                <option value="">-- Pilih KCD (Bisa Multiple) --</option>
                                <option value="1" {{ in_array(1, old('kcd_ids', $user->kcdAssignments->pluck('kcd_id')->toArray())) ? 'selected' : '' }}>KCD 01 - KCD Bandung Raya</option>
                                <option value="2" {{ in_array(2, old('kcd_ids', $user->kcdAssignments->pluck('kcd_id')->toArray())) ? 'selected' : '' }}>KCD 02 - KCD Bogor Raya</option>
                                <option value="3" {{ in_array(3, old('kcd_ids', $user->kcdAssignments->pluck('kcd_id')->toArray())) ? 'selected' : '' }}>KCD 03 - KCD Sukabumi Raya</option>
                                <option value="4" {{ in_array(4, old('kcd_ids', $user->kcdAssignments->pluck('kcd_id')->toArray())) ? 'selected' : '' }}>KCD 04 - KCD Tasikmalaya Raya</option>
                            </select>
                            <small class="text-muted">Tahan Ctrl untuk memilih lebih dari satu KCD</small>
                        </div>

                        <div class="mb-3">
                            <label for="school_ids" class="form-label">Assign ke Sekolah (NPSN)</label>
                            <select class="form-select" id="school_ids" name="school_ids[]" multiple>
                                <option value="">-- Pilih Sekolah (NPSN) (Opsional) --</option>
                                <option value="10101001" {{ in_array('10101001', old('school_ids', $user->schoolAssignments->pluck('school_id')->toArray())) ? 'selected' : '' }}>10101001 - SLB Bina Harapan (Bandung)</option>
                                <option value="10101002" {{ in_array('10101002', old('school_ids', $user->schoolAssignments->pluck('school_id')->toArray())) ? 'selected' : '' }}>10101002 - SD Negeri 1 Bandung</option>
                                <option value="10201001" {{ in_array('10201001', old('school_ids', $user->schoolAssignments->pluck('school_id')->toArray())) ? 'selected' : '' }}>10201001 - SMP Negeri 1 Bogor</option>
                                <option value="10301001" {{ in_array('10301001', old('school_ids', $user->schoolAssignments->pluck('school_id')->toArray())) ? 'selected' : '' }}>10301001 - SMA Negeri 1 Sukabumi</option>
                            </select>
                            <small class="text-muted">Tahan Ctrl untuk memilih lebih dari satu Sekolah (Opsional)</small>
                        </div>
                    </div>

                    <div class="d-flex gap-2">
                        <button type="submit" class="btn btn-primary">
                            <i class="bi bi-save"></i> Update
                        </button>
                        <a href="{{ route('superadmin.users.index') }}" class="btn btn-secondary">
                            <i class="bi bi-x-circle"></i> Batal
                        </a>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function() {
    const roleSelect = document.getElementById('role_id');
    const pengawasSection = document.getElementById('pengawasSection');
    const schoolField = document.getElementById('schoolField');
    const schoolSelect = document.getElementById('school_id');
    const npsnDisplay = document.getElementById('npsnDisplay');
    const nipField = document.getElementById('nipField');
    const nipInput = document.getElementById('nip');
    const nipRequired = document.getElementById('nipRequired');
    const pangkatField = document.getElementById('pangkatField');
    const pangkatInput = document.getElementById('pangkat_golongan');
    const pangkatRequired = document.getElementById('pangkatRequired');
    const emailField = document.getElementById('emailField');
    const emailInput = document.getElementById('email');
    const emailRequired = document.getElementById('emailRequired');
    const emailHint = document.getElementById('emailHint');

    function toggleFieldsByRole() {
        const selectedOption = roleSelect.options[roleSelect.selectedIndex];
        const roleSlug = selectedOption.getAttribute('data-slug');
        const isPengawas = selectedOption.text.toLowerCase().includes('pengawas');
        const isAdminSekolah = roleSlug === '{{ $roleConstants['SLUG_ADMIN_SEKOLAH'] }}';

        // Toggle pengawas section
        pengawasSection.style.display = isPengawas ? 'block' : 'none';

        // Toggle school field (only for admin sekolah)
        schoolField.style.display = isAdminSekolah ? 'block' : 'none';

        // Toggle NIP required
        if (isAdminSekolah) {
            nipInput.removeAttribute('required');
            nipRequired.style.display = 'none';
        } else {
            nipInput.setAttribute('required', 'required');
            nipRequired.style.display = 'inline';
        }

        // Toggle Pangkat required
        if (isAdminSekolah) {
            pangkatInput.removeAttribute('required');
            pangkatRequired.style.display = 'none';
        } else {
            pangkatInput.setAttribute('required', 'required');
            pangkatRequired.style.display = 'inline';
        }

        // Toggle Email required
        if (isAdminSekolah) {
            emailInput.removeAttribute('required');
            emailRequired.style.display = 'none';
            emailHint.style.display = 'block';
        } else {
            emailInput.setAttribute('required', 'required');
            emailRequired.style.display = 'inline';
            emailHint.style.display = 'none';
        }
    }

    // Update NPSN display when school changes
    schoolSelect.addEventListener('change', function() {
        const selectedOption = this.options[this.selectedIndex];
        const npsn = selectedOption.getAttribute('data-npsn');
        npsnDisplay.textContent = npsn || '-';
    });

    roleSelect.addEventListener('change', toggleFieldsByRole);
    // Initial check
    toggleFieldsByRole();
});
</script>
@endpush
@endsection
