@extends('layouts.app')

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

@section('content')
<div class="page-header">
    <h1 class="page-title">Tambah User Baru</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">Tambah 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-person-plus"></i> Form Tambah User</h5>
            </div>
            <div class="card-body">
                <form action="{{ route('superadmin.users.store') }}" method="POST">
                    @csrf

                    <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') == $role->id ? 'selected' : '' }}>
                                    {{ $role->name }}
                                </option>
                            @endforeach
                        </select>
                        @error('role_id')
                            <div class="invalid-feedback d-block">{{ $message }}</div>
                        @enderror
                    </div>

                    <!-- KCD Field for Admin KCD -->
                    <div class="mb-3" id="kcdField" style="display: none;">
                        <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">
                            <option value="">Pilih KCD</option>
                            @foreach($kcds as $kcd)
                                <option value="{{ $kcd->id }}" {{ old('kcd_id') == $kcd->id ? 'selected' : '' }}>
                                    {{ $kcd->code }} - {{ $kcd->name }}
                                </option>
                            @endforeach
                        </select>
                        @error('kcd_id')
                            <div class="invalid-feedback d-block">{{ $message }}</div>
                        @enderror
                        <small class="text-muted">KCD yang akan dikelola oleh user ini</small>
                    </div>

                    <!-- Employee Field for Pengawas -->
                    <div class="mb-3" id="employeeField" style="display: none;">
                        <label for="employee_id" class="form-label">Nama Pengawas <span class="text-danger">*</span></label>
                        <select class="form-select @error('employee_id') is-invalid @enderror" id="employee_id" name="employee_id">
                            <option value="">Pilih Pegawai</option>
                            @foreach($employees as $employee)
                                <option value="{{ $employee->id }}" 
                                    data-name="{{ $employee->name }}"
                                    data-nip="{{ $employee->nip }}"
                                    data-phone="{{ $employee->phone }}"
                                    data-email="{{ $employee->email }}"
                                    {{ old('employee_id') == $employee->id ? 'selected' : '' }}>
                                    {{ $employee->name }} - NIP: {{ $employee->nip }}
                                </option>
                            @endforeach
                        </select>
                        @error('employee_id')
                            <div class="invalid-feedback d-block">{{ $message }}</div>
                        @enderror
                        <small class="text-muted">Pegawai yang akan dijadikan user pengawas</small>
                    </div>

                    <!-- School Field for Admin Sekolah -->
                    <div class="mb-3" id="schoolField" style="display: 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 }}"
                                    data-name="{{ $school->name }}"
                                    {{ old('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"><i class="bi bi-info-circle"></i> NPSN akan otomatis menjadi username untuk login (readonly)</small>
                    </div>

                    <!-- NPSN Field (readonly for admin sekolah) -->
                    <div class="mb-3" id="npsnField" style="display: none;">
                        <label for="npsn" class="form-label">NPSN (Username) <span class="text-danger">*</span></label>
                        <input type="text" class="form-control @error('npsn') is-invalid @enderror" id="npsn" name="npsn" value="{{ old('npsn') }}" readonly>
                        @error('npsn')
                            <div class="invalid-feedback d-block">{{ $message }}</div>
                        @enderror
                        <small class="text-muted"><i class="bi bi-info-circle"></i> NPSN otomatis dari sekolah yang dipilih</small>
                    </div>

                    <!-- NIP Field (hidden for admin sekolah) -->
                    <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 @error('nip') is-invalid @enderror" id="nip" name="nip" value="{{ old('nip') }}" placeholder="NIP 18 digit" pattern="\d{18}">
                        @error('nip')
                            <div class="invalid-feedback d-block">{{ $message }}</div>
                        @enderror
                        <small class="text-muted" id="nipHint" style="display: none;"><i class="bi bi-info-circle"></i> NIP otomatis dari pegawai yang dipilih (readonly)</small>
                    </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') }}" placeholder="Nama lengkap" required>
                        @error('name')
                            <div class="invalid-feedback d-block">{{ $message }}</div>
                        @enderror
                        <small class="text-muted" id="nameHint" style="display: none;"><i class="bi bi-info-circle"></i> Nama otomatis dari pegawai yang dipilih (readonly)</small>
                    </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') }}" 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') }}">
                        @error('email')
                            <div class="invalid-feedback d-block">{{ $message }}</div>
                        @enderror
                        <small class="text-muted" id="emailHint" style="display: none;"><i class="bi bi-info-circle"></i> Untuk admin sekolah, email opsional (akan auto-generate jika kosong)</small>
                        <small class="text-muted" id="emailHintPengawas" style="display: none;"><i class="bi bi-info-circle"></i> Email otomatis dari pegawai yang dipilih (readonly)</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') }}" placeholder="08xxxxxxxxxx">
                        @error('phone')
                            <div class="invalid-feedback d-block">{{ $message }}</div>
                        @enderror
                        <small class="text-muted" id="phoneHint" style="display: none;"><i class="bi bi-info-circle"></i> Telepon otomatis dari pegawai yang dipilih (readonly)</small>
                    </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') }}</textarea>
                        @error('alamat')
                            <div class="invalid-feedback d-block">{{ $message }}</div>
                        @enderror
                    </div>

                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="password" class="form-label">Password <span class="text-danger">*</span></label>
                            <div class="input-group">
                                <input type="text" class="form-control @error('password') is-invalid @enderror" id="password" name="password" required readonly>
                                <button type="button" class="btn btn-outline-secondary" id="generatePassword" title="Generate Password 8 Digit">
                                    <i class="bi bi-key"></i> Generate
                                </button>
                            </div>
                            @error('password')
                                <div class="invalid-feedback d-block">{{ $message }}</div>
                            @enderror
                            <small class="text-muted">Password akan di-generate otomatis (8 digit)</small>
                        </div>

                        <div class="col-md-6 mb-3">
                            <label for="password_confirmation" class="form-label">Konfirmasi Password <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="password_confirmation" name="password_confirmation" required readonly>
                            <small class="text-muted">Otomatis sama dengan password</small>
                        </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', true) ? 'checked' : '' }}>
                            <label class="form-check-label" for="is_active">
                                User 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.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 kcdField = document.getElementById('kcdField');
    const employeeField = document.getElementById('employeeField');
    const employeeSelect = document.getElementById('employee_id');
    const schoolField = document.getElementById('schoolField');
    const schoolSelect = document.getElementById('school_id');
    const npsnField = document.getElementById('npsnField');
    const npsnInput = document.getElementById('npsn');
    const nipField = document.getElementById('nipField');
    const nipInput = document.getElementById('nip');
    const nipRequired = document.getElementById('nipRequired');
    const nipHint = document.getElementById('nipHint');
    const nameInput = document.getElementById('name');
    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');
    const phoneInput = document.getElementById('phone');
    const phoneHint = document.getElementById('phoneHint');
    const nameHint = document.getElementById('nameHint');
    const emailHintPengawas = document.getElementById('emailHintPengawas');
    const passwordInput = document.getElementById('password');
    const passwordConfirmation = document.getElementById('password_confirmation');
    const generateBtn = document.getElementById('generatePassword');

    // Generate random 8 digit password
    function generatePassword() {
        const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        let password = '';
        for (let i = 0; i < 8; i++) {
            password += chars.charAt(Math.floor(Math.random() * chars.length));
        }
        return password;
    }

    // Auto-generate password on page load
    function autoGeneratePassword() {
        const newPassword = generatePassword();
        passwordInput.value = newPassword;
        passwordConfirmation.value = newPassword;
    }

    // Generate password button click
    generateBtn.addEventListener('click', autoGeneratePassword);

    // Auto-generate on page load
    autoGeneratePassword();

    // Auto-fill fields when employee selected
    employeeSelect.addEventListener('change', function() {
        const selectedOption = this.options[this.selectedIndex];
        if (selectedOption.value) {
            nameInput.value = selectedOption.getAttribute('data-name');
            nipInput.value = selectedOption.getAttribute('data-nip');
            const phone = selectedOption.getAttribute('data-phone');
            const email = selectedOption.getAttribute('data-email');
            if (phone) {
                phoneInput.value = phone;
                phoneInput.setAttribute('readonly', 'readonly');
            }
            if (email) {
                emailInput.value = email;
                emailInput.setAttribute('readonly', 'readonly');
            }
            
            // Make fields readonly
            nameInput.setAttribute('readonly', 'readonly');
            nipInput.setAttribute('readonly', 'readonly');
        } else {
            // Remove readonly if no employee selected
            nameInput.removeAttribute('readonly');
            nipInput.removeAttribute('readonly');
            phoneInput.removeAttribute('readonly');
            emailInput.removeAttribute('readonly');
            nameInput.value = '';
            nipInput.value = '';
            phoneInput.value = '';
            emailInput.value = '';
        }
    });

    // Auto-fill NPSN when school selected for admin sekolah
    schoolSelect.addEventListener('change', function() {
        const selectedOption = this.options[this.selectedIndex];
        if (selectedOption.value) {
            const npsn = selectedOption.getAttribute('data-npsn');
            npsnInput.value = npsn;
        } else {
            npsnInput.value = '';
        }
    });

    function toggleFieldsByRole() {
        const selectedOption = roleSelect.options[roleSelect.selectedIndex];
        const roleSlug = selectedOption.getAttribute('data-slug');
        const isPengawas = roleSlug === '{{ $roleConstants['SLUG_PENGAWAS'] }}';
        const isAdminSekolah = roleSlug === '{{ $roleConstants['SLUG_ADMIN_SEKOLAH'] }}';
        const isAdminKcd = roleSlug === '{{ $roleConstants['SLUG_ADMIN_KCD'] }}';

        // Toggle KCD field (only for admin kcd)
        kcdField.style.display = isAdminKcd ? 'block' : 'none';

        // Toggle employee field (only for pengawas)
        employeeField.style.display = isPengawas ? 'block' : 'none';

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

        // Toggle hints for pengawas
        nameHint.style.display = isPengawas ? 'block' : 'none';
        nipHint.style.display = isPengawas ? 'block' : 'none';
        phoneHint.style.display = isPengawas ? 'block' : 'none';
        emailHintPengawas.style.display = isPengawas ? 'block' : 'none';

        // Toggle name and NIP readonly for pengawas
        if (isPengawas) {
            nameInput.setAttribute('readonly', 'readonly');
            nipInput.setAttribute('readonly', 'readonly');
        } else {
            nameInput.removeAttribute('readonly');
            nipInput.removeAttribute('readonly');
        }

        // Toggle NIP required
        if (isAdminSekolah || isPengawas) {
            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 and hints
        if (isAdminSekolah) {
            emailInput.removeAttribute('required');
            emailRequired.style.display = 'none';
            emailHint.style.display = 'block';
            emailHintPengawas.style.display = 'none';
        } else if (isPengawas) {
            emailInput.setAttribute('required', 'required');
            emailRequired.style.display = 'inline';
            emailHint.style.display = 'none';
            emailHintPengawas.style.display = 'block';
        } else {
            emailInput.setAttribute('required', 'required');
            emailRequired.style.display = 'inline';
            emailHint.style.display = 'none';
            emailHintPengawas.style.display = 'none';
        }
    }

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