<?= $this->extend('layouts/main') ?>

<?= $this->section('title') ?>
Form Pengajuan Usulan KP
<?= $this->endSection() ?>

<?= $this->section('page_title') ?>
Layanan Mandiri: Pengajuan Usul Kenaikan Pangkat
<?= $this->endSection() ?>

<?= $this->section('styles') ?>
<style>
    .step-number {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        background: rgba(255, 255, 255, 0.1);
        color: rgba(255, 255, 255, 0.5);
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: 700;
        border: 2px solid rgba(255, 255, 255, 0.2);
        transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
        margin-bottom: 0.5rem;
    }

    .step-item.active .step-number {
        background: #4361ee;
        color: white;
        border-color: #4361ee;
        box-shadow: 0 0 20px rgba(67, 97, 238, 0.4);
        transform: scale(1.1);
    }

    .step-connector {
        position: absolute;
        top: 20px;
        left: 10%;
        right: 10%;
        height: 2px;
        background: rgba(255, 255, 255, 0.1);
        z-index: -1;
    }

    .wizard-step {
        display: none;
    }

    .wizard-step.active {
        display: block;
        animation: fadeInSlide 0.5s ease-out;
    }

    @keyframes fadeInSlide {
        from {
            opacity: 0;
            transform: translateY(20px);
        }

        to {
            opacity: 1;
            transform: translateY(0);
        }
    }

    .nav-tabs-custom .nav-link {
        border: none !important;
        color: #495057 !important;
        padding: 0.8rem 1.5rem !important;
        border-radius: 8px !important;
        font-weight: 700 !important;
        font-size: 0.85rem !important;
        transition: all 0.3s !important;
        background: rgba(0, 0, 0, 0.08) !important;
        margin-right: 0.5rem !important;
        display: flex !important;
        align-items: center !important;
        gap: 8px !important;
    }

    .nav-tabs-custom .nav-link:hover {
        background: rgba(0, 0, 0, 0.12) !important;
        color: #000 !important;
    }

    .nav-tabs-custom .nav-link.active {
        background: #4361ee !important;
        color: #ffffff !important;
        box-shadow: 0 4px 15px rgba(67, 97, 238, 0.3) !important;
    }

    .form-group-custom {
        margin-bottom: 1.5rem;
    }

    .form-label-custom {
        font-size: 0.75rem;
        font-weight: 700;
        color: #6c757d;
        text-transform: uppercase;
        letter-spacing: 0.5px;
        margin-bottom: 0.5rem;
        display: block;
    }

    .form-control-custom {
        border-radius: 12px;
        border: 1.5px solid #edf2f7;
        padding: 0.75rem 1rem;
        transition: all 0.3s;
        font-size: 0.9rem;
    }

    .form-control-custom:focus {
        border-color: #4361ee;
        box-shadow: 0 0 0 4px rgba(67, 97, 238, 0.1);
        outline: none;
    }
</style>
<?= $this->endSection() ?>

<?= $this->section('content') ?>
<div class="row justify-content-center">
    <div class="col-lg-11">

        <!-- STEPPER -->
        <div class="glass-card mb-4 border-white border-opacity-10" style="background: rgba(255, 255, 255, 0.05);">
            <div class="d-flex justify-content-around position-relative py-3">
                <div class="step-item text-center active" id="step-1-label">
                    <div class="step-number mx-auto">1</div>
                    <div class="small fw-bold text-white opacity-75">Jenis Prosedur</div>
                </div>
                <div class="step-item text-center" id="step-2-label">
                    <div class="step-number mx-auto">2</div>
                    <div class="small fw-bold text-white opacity-75">Pilih Pegawai</div>
                </div>
                <div class="step-item text-center" id="step-3-label">
                    <div class="step-number mx-auto">3</div>
                    <div class="small fw-bold text-white opacity-75">Detail Berkas</div>
                </div>
                <div class="step-connector"></div>
            </div>
        </div>

        <form action="<?= site_url('user/pengajuan/submit') ?>" method="POST" enctype="multipart/form-data"
            id="wizardForm">
            <?= csrf_field() ?>

            <!-- STEP 1: JENIS PROSEDUR -->
            <div class="wizard-step active" id="step-1">
                <div class="glass-card">
                    <div class="d-flex align-items-center mb-4">
                        <div class="bg-primary bg-opacity-10 p-3 rounded-4 me-3">
                            <i class="bi bi-info-circle-fill text-primary fs-3"></i>
                        </div>
                        <div>
                            <h5 class="fw-bold mb-1">Informasi Awal Usulan</h5>
                            <p class="text-muted small mb-0">Tentukan periode dan jenis kenaikan pangkat yang akan
                                diusulkan.</p>
                        </div>
                    </div>

                    <div class="row g-4 mb-4">
                        <div class="col-md-6">
                            <div class="form-group-custom">
                                <label class="form-label-custom">Periode Kenaikan Pangkat</label>
                                <select class="form-select form-control-custom" name="periode" required>
                                    <option value="">Pilih Bulan</option>
                                    <?php
                                    $months = ['Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni', 'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'];
                                    foreach ($months as $m):
                                        ?>
                                        <option value="<?= $m ?>" <?= ($m == date('F')) ? 'selected' : '' ?>><?= $m ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group-custom">
                                <label class="form-label-custom">Tahun</label>
                                <select class="form-select form-control-custom" name="tahun" required>
                                    <option value="<?= date('Y') - 1 ?>"><?= date('Y') - 1 ?></option>
                                    <option value="<?= date('Y') ?>" selected><?= date('Y') ?></option>
                                    <option value="<?= date('Y') + 1 ?>"><?= date('Y') + 1 ?></option>
                                </select>
                            </div>
                        </div>
                    </div>

                    <div class="form-group-custom">
                        <label class="form-label-custom mb-3">Jenis Prosedur</label>
                        <div class="row g-3">
                            <div class="col-md-4">
                                <div class="border rounded-4 p-3 h-100 position-relative transition-all"
                                    id="proc-card-1">
                                    <div class="form-check h-100">
                                        <input class="form-check-input stretched-link" type="radio"
                                            name="jenis_prosedur" id="p1" value="III/D KE BAWAH" checked>
                                        <label class="form-check-label fw-bold d-block" for="p1">
                                            III/D KE BAWAH
                                            <span class="d-block small text-muted fw-normal mt-1">Usulan kenaikan
                                                pangkat untuk golongan II/a sampai III/d.</span>
                                        </label>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="border rounded-4 p-3 h-100 position-relative transition-all"
                                    id="proc-card-2">
                                    <div class="form-check h-100">
                                        <input class="form-check-input stretched-link" type="radio"
                                            name="jenis_prosedur" id="p2" value="IV/A-IV/B">
                                        <label class="form-check-label fw-bold d-block" for="p2">
                                            IV/A - IV/B
                                            <span class="d-block small text-muted fw-normal mt-1">Usulan kenaikan
                                                pangkat untuk golongan IV/a dan IV/b.</span>
                                        </label>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="border rounded-4 p-3 h-100 position-relative transition-all"
                                    id="proc-card-3">
                                    <div class="form-check h-100">
                                        <input class="form-check-input stretched-link" type="radio"
                                            name="jenis_prosedur" id="p3" value="IV/C KE ATAS NON JENJANG UTAMA">
                                        <label class="form-check-label fw-bold d-block" for="p3">
                                            IV/C KE ATAS
                                            <span class="d-block small text-muted fw-normal mt-1">Non Jenjang Utama.
                                                (IV/c ke atas JPT Madya/Utama melalui SIAPP).</span>
                                        </label>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row g-4 mb-5 mt-2">
                        <div class="col-md-6">
                            <div class="form-group-custom">
                                <label class="form-label-custom">Jenis Kenaikan Pangkat</label>
                                <select class="form-select form-control-custom" name="jenis_kp" id="select_jenis_kp">
                                    <option value="" disabled selected>-- Pilih --</option>
                                    <option value="Kenaikan Pangkat Reguler">Kenaikan Pangkat Reguler</option>
                                    <option value="Kenaikan Pangkat Struktural">Kenaikan Pangkat Struktural</option>
                                    <option value="Kenaikan Pangkat Jabatan Fungsional">Kenaikan Pangkat Jabatan
                                        Fungsional</option>
                                    <option value="Kenaikan Pangkat Memperoleh Ijazah/Penyesuaian Ijazah">Penyelarasan
                                        Ijazah</option>
                                    <option value="Kenaikan Pangkat Prestasi Luar Biasa">Prestasi Luar Biasa</option>
                                    <option value="Tugas Belajar">Sedang/Selesai Tugas Belajar</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group-custom">
                                <label class="form-label-custom">Jenis Jabatan</label>
                                <select class="form-select form-control-custom" name="jenis_jabatan"
                                    id="select_jenis_jabatan">
                                    <option value="" disabled selected>-- Pilih --</option>
                                    <option value="Jabatan Fungsional Umum/Pelaksana">Jabatan Fungsional Umum/Pelaksana
                                    </option>
                                    <option value="Jabatan Fungsional">Jabatan Fungsional</option>
                                    <option value="Jabatan Struktural">Jabatan Struktural</option>
                                </select>
                            </div>
                            <div id="mismatch-warning"
                                class="alert alert-warning py-2 px-3 mt-2 rounded-4 small d-none">
                                <i class="bi bi-exclamation-triangle-fill me-1"></i> <span
                                    id="mismatch-text">Peringatan: Jabatan pilihan tidak sesuai dengan data asli.</span>
                            </div>
                        </div>
                    </div>

                    <div class="text-end">
                        <button type="button" class="btn btn-primary rounded-pill px-5 py-3 fw-bold btn-next">
                            LANGKAH BERIKUTNYA <i class="bi bi-arrow-right ms-2"></i>
                        </button>
                    </div>
                </div>
            </div>

            <!-- STEP 2: PILIH PEGAWAI -->
            <div class="wizard-step" id="step-2">
                <div class="glass-card">
                    <div class="d-flex align-items-center mb-4">
                        <div class="bg-primary bg-opacity-10 p-3 rounded-4 me-3">
                            <i class="bi bi-people-fill text-primary fs-3"></i>
                        </div>
                        <div>
                            <h5 class="fw-bold mb-1">Pilih Pegawai</h5>
                            <p class="text-muted small mb-0">Cari data pegawai yang akan diusulkan kenaikan pangkatnya.
                            </p>
                        </div>
                    </div>

                    <div class="form-group-custom mb-5">
                        <label class="form-label-custom">NIP Baru Pegawai</label>
                        <div class="input-group shadow-sm rounded-4 overflow-hidden"
                            style="border: 1.5px solid #edf2f7;">
                            <input type="text" class="form-control border-0 py-3 px-4" id="nip_search_input"
                                name="target_nip" placeholder="Masukkan 18 digit NIP...">
                            <button type="button" class="btn btn-dark px-4 fw-bold" id="btn-search-nip"><i
                                    class="bi bi-search me-2"></i> CARI</button>
                            <button type="button" class="btn btn-primary px-4 fw-bold" data-bs-toggle="modal"
                                data-bs-target="#modalPilihPegawai"><i class="bi bi-list-ul me-2"></i> DAFTAR
                                PEGAWAI</button>
                        </div>
                        <div id="scan-status-box" class="mt-3 small d-none">
                            <div class="alert alert-light border rounded-4 p-2 mb-0 d-flex align-items-center">
                                <span class="spinner-border spinner-border-sm text-primary me-2" role="status"></span>
                                <span id="scan-status-text">Memindai arsip dokumen...</span>
                            </div>
                        </div>
                    </div>



                    <!-- Profile Result Card -->
                    <div id="pegawai-result" class="d-none border-0 rounded-4 p-4 mb-5 shadow-sm"
                        style="background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);">
                        <div class="row align-items-center">
                            <div class="col-md-auto text-center mb-3 mb-md-0">
                                <div class="position-relative d-inline-block">
                                    <img src="<?= base_url('assets/img/avatar.png') ?>" alt="Foto" id="res-foto"
                                        class="rounded-4 shadow-sm border border-white border-4"
                                        style="width: 120px; height: 120px; object-fit: cover;">
                                    <div class="position-absolute bottom-0 end-0 bg-success rounded-circle border border-white border-3"
                                        style="width: 24px; height: 24px;"></div>
                                </div>
                            </div>
                            <div class="col">
                                <h3 class="fw-bold text-dark mb-1" id="res-nama">-</h3>
                                <div class="d-flex flex-wrap gap-3 mt-2">
                                    <div
                                        class="badge bg-primary bg-opacity-10 text-primary border border-primary border-opacity-10 px-3 py-2 rounded-3">
                                        <i class="bi bi-fingerprint me-2"></i> <span id="res-nip">-</span>
                                    </div>
                                    <div
                                        class="badge bg-secondary bg-opacity-10 text-secondary border border-secondary border-opacity-10 px-3 py-2 rounded-3">
                                        <i class="bi bi-building me-2"></i> <span id="res-unor">-</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <input type="hidden" name="user_id" id="target_user_id">
                    </div>

                    <div class="d-flex justify-content-between mt-4">
                        <button type="button" class="btn btn-link text-decoration-none text-muted fw-bold btn-prev"><i
                                class="bi bi-chevron-left me-2"></i> SEBELUMNYA</button>
                        <button type="button" class="btn btn-primary rounded-pill px-5 py-3 fw-bold"
                            id="btn-step-2-next" disabled>
                            LANJUT INPUT BERKAS <i class="bi bi-arrow-right ms-2"></i>
                        </button>
                    </div>
                </div>
            </div>

            <!-- STEP 3: INPUT DETAIL -->
            <div class="wizard-step" id="step-3">
                <div class="glass-card">
                    <ul class="nav nav-tabs nav-tabs-custom border-0 mb-4 bg-light p-1 rounded-3" id="detailTabs"
                        role="tablist">
                        <li class="nav-item">
                            <button class="nav-link active" data-bs-toggle="tab" data-bs-target="#tab1"
                                type="button">
                                <i class="bi bi-person-fill"></i> DATA PRIBADI & JABATAN
                            </button>
                        </li>
                        <li class="nav-item">
                            <button class="nav-link" data-bs-toggle="tab" data-bs-target="#tab2" type="button">
                                <i class="bi bi-diagram-3-fill"></i> DATA ATASAN
                            </button>
                        </li>
                        <li class="nav-item">
                            <button class="nav-link" data-bs-toggle="tab" data-bs-target="#tabUpload"
                                type="button">
                                <i class="bi bi-cloud-arrow-up-fill"></i> UNGGAH DOKUMEN
                            </button>
                        </li>
                    </ul>

                    <div class="tab-content py-2">
                        <!-- TAB 1: PERSONAL & JABATAN -->
                        <div class="tab-pane fade show active" id="tab1">
                            <h6 class="fw-bold text-primary mb-4 pb-2 border-bottom"><i
                                    class="bi bi-person-vcard me-2"></i> IDENTITAS & GOLONGAN AWAL</h6>
                            <div class="row g-3 mb-5">
                                <div class="col-md-4">
                                    <label class="form-label-custom">Tempat Lahir</label>
                                    <input type="text" class="form-control form-control-custom" name="tempat_lahir"
                                        id="inp-tempat_lahir" placeholder="Contoh: Gorontalo">
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label-custom">Tanggal Lahir</label>
                                    <input type="text" class="form-control form-control-custom" name="tanggal_lahir"
                                        id="inp-tanggal_lahir" placeholder="YYYY-MM-DD">
                                </div>
                                <div class="col-md-2">
                                    <label class="form-label-custom">Gelar Depan</label>
                                    <input type="text" class="form-control form-control-custom" name="gelar_depan"
                                        id="inp-gelar_depan" placeholder="Dr.">
                                </div>
                                <div class="col-md-2">
                                    <label class="form-label-custom">Gelar Belakang</label>
                                    <input type="text" class="form-control form-control-custom" name="gelar_belakang"
                                        id="inp-gelar_belakang" placeholder="S.Kom">
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label-custom">Golongan Saat Ini</label>
                                    <input type="text" class="form-control form-control-custom" name="gol_awal"
                                        id="inp-gol_awal" placeholder="Contoh: III/c">
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label-custom">TMT Golongan</label>
                                    <input type="text" class="form-control form-control-custom" name="tmt_golongan_lama"
                                        id="inp-tmt_golongan_lama" placeholder="HH/BB/TTTT">
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label-custom">Masa Kerja Thn (Lama)</label>
                                    <input type="number" class="form-control form-control-custom" name="mkt_lama"
                                        id="inp-mkt_lama" value="0">
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label-custom">Masa Kerja Bln (Lama)</label>
                                    <input type="number" class="form-control form-control-custom" name="mkb_lama"
                                        id="inp-mkb_lama" value="0">
                                </div>
                            </div>

                            <h6 class="fw-bold text-primary mb-4 pb-2 border-bottom"><i
                                    class="bi bi-briefcase-fill me-2"></i> JABATAN & UNIT KERJA</h6>
                            <div class="row g-3 mb-5">
                                <div class="col-md-12">
                                    <label class="form-label-custom">Unit Kerja / UNOR</label>
                                    <input type="text" class="form-control form-control-custom" name="unor"
                                        id="inp-unor" placeholder="Nama Unit Kerja">
                                </div>
                                <div class="col-md-12">
                                    <label class="form-label-custom">Unit Kerja Induk</label>
                                    <input type="text" class="form-control form-control-custom" name="unit_kerja_induk"
                                        id="inp-unit_kerja_induk" placeholder="Nama Instansi/Induk">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label-custom">Jabatan Saat Ini</label>
                                    <input type="text" class="form-control form-control-custom" name="jabatan_lama"
                                        id="inp-jabatan_lama" placeholder="Nama Jabatan">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label-custom">Jabatan Baru (Usulan)</label>
                                    <input type="text" class="form-control form-control-custom" name="jabatan_baru"
                                        id="inp-jabatan_baru" placeholder="Jabatan Baru">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label-custom">Lokasi Kerja</label>
                                    <input type="text" class="form-control form-control-custom" name="lokasi_kerja"
                                        id="inp-lokasi_kerja" placeholder="Provinsi/Kabupaten">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label-custom">Instansi Kerja</label>
                                    <input type="text" class="form-control form-control-custom" name="instansi_kerja"
                                        id="inp-instansi_kerja" placeholder="Instansi">
                                </div>
                            </div>

                            <h6 class="fw-bold text-primary mb-4 pb-2 border-bottom"><i
                                    class="bi bi-mortarboard-fill me-2"></i> RIWAYAT PENDIDIKAN TERAKHIR (PEGAWAI)</h6>
                            <div class="row g-3 mb-5">
                                <div class="col-md-6">
                                    <label class="form-label-custom">Nama Sekolah/Universitas</label>
                                    <input type="text" class="form-control form-control-custom" name="pendidikan_lama"
                                        id="inp-pendidikan_lama" placeholder="Contoh: Universitas Gadjah Mada">
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label-custom">Tahun Lulus</label>
                                    <input type="number" class="form-control form-control-custom" name="tahun_lulus"
                                        id="inp-tahun_lulus" placeholder="YYYY">
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label-custom">TMT Jabatan</label>
                                    <input type="text" class="form-control form-control-custom" name="tmt_jabatan_lama"
                                        id="inp-tmt_jabatan_lama" placeholder="HH/BB/TTTT">
                                </div>
                            </div>

                            <!-- Angka Kredit Section (Only for Fungsional) -->
                            <div id="section-angka-kredit" class="d-none mt-4">
                                <h6 class="fw-bold text-primary mb-4 pb-2 border-bottom"><i
                                        class="bi bi-calculator me-2"></i> DATA ANGKA KREDIT</h6>
                                <div class="row g-3 mb-5">
                                    <div class="col-md-6">
                                        <label class="form-label-custom">Angka Kredit Lama</label>
                                        <input type="text" class="form-control form-control-custom"
                                            name="angka_kredit_lama" placeholder="Contoh: 48.750">
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label-custom">Angka Kredit Baru</label>
                                        <input type="text" class="form-control form-control-custom"
                                            name="angka_kredit_baru" placeholder="Contoh: 123.750">
                                    </div>
                                </div>
                            </div>

                            <h6 class="fw-bold text-primary mb-4 pb-2 border-bottom"><i
                                    class="bi bi-star-fill me-2"></i> USULAN GOLONGAN BARU</h6>
                            <div class="row g-3">
                                <div class="col-md-4">
                                    <label class="form-label-custom">Golongan Baru</label>
                                    <input type="text" class="form-control form-control-custom bg-light fw-bold"
                                        name="gol_baru" id="inp-gol_baru" placeholder="Contoh: III/d">
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label-custom">TMT Golongan Baru</label>
                                    <input type="text" class="form-control form-control-custom" name="tmt_gol_baru"
                                        placeholder="HH/BB/TTTT">
                                </div>

                                <div class="col-md-3">
                                    <label class="form-label-custom">Masa Kerja Thn (Baru)</label>
                                    <input type="number" class="form-control form-control-custom" name="mkt_baru"
                                        value="0">
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label-custom">Masa Kerja Bln (Baru)</label>
                                    <input type="number" class="form-control form-control-custom" name="mkb_baru"
                                        value="0">
                                </div>
                            </div>
                        </div>

                        <!-- TAB 2: ATASAN -->
                        <div class="tab-pane fade" id="tab2">
                            <h6 class="fw-bold text-primary mb-4 pb-2 border-bottom"><i
                                    class="bi bi-person-badge-fill me-2"></i> DATA ATASAN LANGSUNG</h6>
                            <div class="row g-3 mb-5">
                                <div class="col-md-6">
                                    <label class="form-label-custom">Nama Lengkap Atasan</label>
                                    <input type="text" class="form-control form-control-custom" name="atasan_nama"
                                        id="inp-atasan_nama" placeholder="Nama Tanpa Gelar">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label-custom">NIP Atasan</label>
                                    <div class="input-group">
                                        <input type="text" class="form-control form-control-custom" name="atasan_nip"
                                            id="inp-atasan_nip" placeholder="18 Digit NIP">
                                        <button class="btn btn-primary px-3 rounded-end-4" type="button"
                                            onclick="searchSupervisor()">
                                            <i class="bi bi-search"></i>
                                        </button>
                                    </div>
                                    <small class="text-muted" style="font-size: 0.7rem;">Masukkan NIP lalu klik ikon
                                        cari</small>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label-custom">Jabatan Atasan</label>
                                    <input type="text" class="form-control form-control-custom" name="atasan_jabatan"
                                        id="inp-atasan_jabatan" placeholder="Jabatan Struktural/Fungsional">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label-custom">Golongan Atasan</label>
                                    <input type="text" class="form-control form-control-custom" name="atasan_gol"
                                        id="inp-atasan_gol" placeholder="Contoh: IV/b">
                                </div>
                            </div>

                            <h6 class="fw-bold text-primary mb-4 pb-2 border-bottom"><i
                                    class="bi bi-chat-left-dots-fill me-2"></i> KETERANGAN TAMBAHAN</h6>
                            <div class="row g-3">

                                <div class="col-md-12">
                                    <label class="form-label-custom">Catatan Tambahan Usulan</label>
                                    <textarea class="form-control form-control-custom" name="keterangan_kp" rows="3"
                                        placeholder="Tambahkan informasi pendukung lainnya jika ada..."></textarea>
                                </div>
                            </div>

                        </div>

                        <!-- TAB 3: UPLOAD -->
                        <div class="tab-pane fade" id="tabUpload">
                            <div class="alert alert-info border-0 rounded-4 px-4 py-3 mb-4 d-flex align-items-center">
                                <i class="bi bi-file-earmark-pdf-fill fs-3 me-3"></i>
                                <div>
                                    <div class="fw-bold">Ketentuan Unggah Dokumen</div>
                                    <div class="small opacity-75">Gunakan format <strong>PDF</strong> dengan ukuran
                                        maksimal <strong>1MB</strong> per file.</div>
                                </div>
                            </div>

                            <div id="document-list" class="row g-4">
                                <!-- Dynamic document inputs will be injected here by JS -->
                            </div>

                            <div
                                class="mt-5 p-4 bg-danger bg-opacity-10 rounded-4 border border-danger border-opacity-10">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="conf-check" required>
                                    <label class="form-check-label small fw-bold text-danger" for="conf-check">
                                        SAYA MENYATAKAN BAHWA SELURUH DATA DAN DOKUMEN YANG SAYA UNGGAH ADALAH BENAR DAN
                                        SAH. KESALAHAN DATA DAPAT MENGAKIBATKAN USULAN DIBATALKAN.
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="d-flex justify-content-between mt-5">
                        <button type="button" class="btn btn-link text-decoration-none text-muted fw-bold btn-prev"><i
                                class="bi bi-chevron-left me-2"></i> SEBELUMNYA</button>
                        <button type="submit" class="btn btn-success rounded-pill px-5 py-3 fw-bold shadow-lg"
                            id="btn-submit-wizard" disabled>
                            <i class="bi bi-check-circle-fill me-2"></i> KIRIM USULAN KENAIKAN PANGKAT
                        </button>
                    </div>
                </div>
            </div>

        </form>
    </div>
</div>



<!-- Modal Pilih Pegawai (Moved to root for Z-Index stability) -->
<div class="modal fade" id="modalPilihPegawai" tabindex="-1" aria-hidden="true" style="z-index: 1060;">
    <div class="modal-dialog modal-lg modal-dialog-centered modal-dialog-scrollable">
        <div class="modal-content border-0 shadow-lg rounded-4">
            <div class="modal-header bg-dark text-white p-4 border-0">
                <h5 class="modal-title fw-bold"><i class="bi bi-person-lines-fill me-2"></i> Pilih Data Pegawai</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"
                    aria-label="Close"></button>
            </div>
            <div class="modal-body p-4">
                <div class="input-group mb-4 shadow-sm rounded-pill overflow-hidden border">
                    <span class="input-group-text bg-white border-0 ps-3 text-muted"><i class="bi bi-search"></i></span>
                    <input type="text" class="form-control border-0 py-2" id="searchTable"
                        placeholder="Cari Nama, NIP, atau Unit Kerja...">
                </div>
                <div class="table-responsive">
                    <table class="table table-hover align-middle custom-table" id="pegawaiTable">
                        <thead class="bg-light">
                            <tr class="text-secondary small fw-bold">
                                <th>DATA PEGAWAI</th>
                                <th>UNIT KERJA</th>
                                <th class="text-center">OPSI</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($all_pegawai as $p): ?>
                                <tr>
                                    <td>
                                        <div class="fw-bold mb-0"><?= $p['nama'] ?></div>
                                        <code class="text-muted small"><?= $p['nip_baru'] ?></code>
                                    </td>
                                    <td class="small text-muted line-clamp-1"><?= $p['unor'] ?></td>
                                    <td class="text-center">
                                        <button type="button" class="btn btn-sm btn-primary rounded-pill px-3 fw-bold"
                                            onclick="performSearch('<?= $p['nip_baru'] ?>')">Pilih</button>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<input type="hidden" id="original_jenis_jabatan" value="">
<input type="hidden" id="existing_docs_json" value="{}">

<script>
    // GLOBAL SEARCH FUNCTION
    async function performSearch(nip) {
        if (!nip) return;

        const btn = document.getElementById('btn-search-nip');
        const input = document.getElementById('nip_search_input');
        const resultCard = document.getElementById('pegawai-result');
        const statusBox = document.getElementById('scan-status-box');
        const statusText = document.getElementById('scan-status-text');

        try {
            if (btn) btn.disabled = true;
            if (statusBox) statusBox.classList.remove('d-none');
            if (statusText) statusText.innerHTML = 'Memindai arsip dokumen untuk NIP ' + nip + '...';

            const response = await fetch(`<?= site_url('user/pengajuan/search_pegawai') ?>/${nip}`);
            const data = await response.json();

            if (data.success) {
                // Perform Modal Cleanup
                const modalEl = document.getElementById('modalPilihPegawai');
                const modal = bootstrap.Modal.getInstance(modalEl);
                if (modal) modal.hide();
                setTimeout(() => {
                    document.querySelectorAll('.modal-backdrop').forEach(el => el.remove());
                    document.body.classList.remove('modal-open');
                    document.body.style = "";
                }, 500);

                // Update Profile Labels
                document.getElementById('res-nama').innerText = data.pegawai.nama || '-';
                document.getElementById('res-nip').innerText = data.pegawai.nip_baru || '-';
                document.getElementById('res-unor').innerText = data.pegawai.unor || '-';
                document.getElementById('target_user_id').value = data.pegawai.user_id || '';
                document.getElementById('nip_search_input').value = data.pegawai.nip_baru || '';
                document.getElementById('original_jenis_jabatan').value = data.pegawai.jenis_jabatan || '';

                // Fill Inputs Fast
                const fill = (id, val) => { const el = document.getElementById(id); if (el) el.value = val || (el.type === 'number' ? '0' : ''); };
                fill('inp-tempat_lahir', data.pegawai.tempat_lahir);
                fill('inp-tanggal_lahir', data.pegawai.tanggal_lahir);
                fill('inp-gelar_depan', data.pegawai.gelar_depan);
                fill('inp-gelar_belakang', data.pegawai.gelar_belakang);
                fill('inp-gol_awal', data.pegawai.gol_akhir);
                fill('inp-tmt_golongan_lama', data.pegawai.tmt_golongan);
                fill('inp-mkt_lama', data.pegawai.masa_kerja_tahun);
                fill('inp-mkb_lama', data.pegawai.masa_kerja_bulan);
                fill('inp-unor', data.pegawai.unor);
                fill('inp-unit_kerja_induk', data.pegawai.unit_kerja_induk);
                fill('inp-jabatan_lama', data.pegawai.jabatan);
                fill('inp-pendidikan_lama', data.pegawai.pendidikan);
                fill('inp-tahun_lulus', data.pegawai.tahun_lulus);
                fill('inp-tmt_jabatan_lama', data.pegawai.tmt_jabatan);
                fill('inp-instansi_kerja', data.pegawai.instansi_kerja || 'PEMERINTAH KABUPATEN BOALEMO');
                fill('inp-lokasi_kerja', data.pegawai.lokasi_kerja || 'KAB. BOALEMO');

                if (typeof determineNextGrade === 'function') determineNextGrade(data.pegawai.gol_akhir);

                // BACKGROUND SCAN WITH PERSISTENT STORAGE
                window.detectedDocs = {}; // Reset

                fetch(`<?= site_url('user/pengajuan/check_existing_docs') ?>/${nip}`)
                    .then(res => res.json())
                    .then(docData => {
                        if (docData.success) {
                            window.detectedDocs = docData.documents;

                            if (statusText) {
                                statusBox.querySelector('.spinner-border').classList.add('d-none');
                                statusText.innerHTML = '<span class="text-success fw-bold"><i class="bi bi-check-all"></i> ' + docData.count + ' berkas ditemukan otomatis!</span>';
                            }

                            // Try update UI immediately if already in step 3
                            if (typeof window.updateDocumentList === 'function') window.updateDocumentList();
                        }
                    });

                if (resultCard) resultCard.classList.remove('d-none');
                document.getElementById('btn-step-2-next').disabled = false;
            } else {
                alert(data.message || 'Pegawai tidak ditemukan');
            }
        } catch (error) {
            console.error('Search failed:', error);
            alert('Gagal Memproses Data: ' + error.message + '\n\nAda kemungkinan elemen formulir tidak ditemukan. Mohon refresh halaman.');
        } finally {
            if (btn) {
                btn.innerHTML = '<i class="bi bi-search me-2"></i> CARI';
                btn.disabled = false;
            }
        }
    }

    document.addEventListener('DOMContentLoaded', function () {
        let currentStep = 1;

        function updateStep(step) {
            document.querySelectorAll('.wizard-step').forEach(s => s.classList.remove('active'));
            document.getElementById('step-' + step).classList.add('active');

            document.querySelectorAll('.step-item').forEach((item, idx) => {
                if (idx + 1 <= step) item.classList.add('active');
                else item.classList.remove('active');
            });
            currentStep = step;
            window.scrollTo({ top: 0, behavior: 'smooth' });
        }

        document.querySelectorAll('.btn-next').forEach(btn => {
            btn.addEventListener('click', () => updateStep(currentStep + 1));
        });

        document.querySelectorAll('.btn-prev').forEach(btn => {
            btn.addEventListener('click', () => updateStep(currentStep - 1));
        });

        document.getElementById('btn-step-2-next').addEventListener('click', function (e) {
            // Final Validation before allowing next step
            const original = document.getElementById('original_jenis_jabatan').value;
            const current = document.getElementById('select_jenis_jabatan').value;
            const originalLower = original.toLowerCase();

            let isMismatch = false;
            if (originalLower.includes('struktural') && current !== 'Jabatan Struktural') isMismatch = true;
            else if (originalLower.includes('fungsional') && !originalLower.includes('umum') && current !== 'Jabatan Fungsional') isMismatch = true;
            else if ((originalLower.includes('umum') || originalLower.includes('pelaksana') || originalLower === '') && current !== 'Jabatan Fungsional Umum/Pelaksana') isMismatch = true;

            if (isMismatch) {
                alert(`MAAF, PROSES TIDAK DAPAT DILANJUTKAN.\n\nJenis Jabatan yang dipilih (${current}) tidak sesuai dengan Profil Asli Pegawai (${original}).\n\nSilakan sesuaikan pilihan Jenis Jabatan/KenPangkat dengan profil PNS yang dicari.`);
                return; // Stop processing
            }

            updateStep(3);
        });

        // Checkbox Enable Submit
        document.getElementById('conf-check').addEventListener('change', function () {
            document.getElementById('btn-submit-wizard').disabled = !this.checked;
        });

        // SEARCH IN MODAL
        document.getElementById('searchTable').addEventListener('keyup', function () {
            const val = this.value.toLowerCase();
            document.querySelectorAll('#pegawaiTable tbody tr').forEach(tr => {
                tr.style.display = tr.innerText.toLowerCase().indexOf(val) !== -1 ? '' : 'none';
            });
        });

        // SEARCH NIP LOGIC
        document.getElementById('btn-search-nip').addEventListener('click', function () {
            performSearch(document.getElementById('nip_search_input').value);
        });

        // Elements for Sync Logic
        const selectJab = document.getElementById('select_jenis_jabatan');
        const selectKP = document.getElementById('select_jenis_kp');
        const warnDiv = document.getElementById('mismatch-warning');
        const warnText = document.getElementById('mismatch-text');

        function checkJabatanMismatch() {
            const original = document.getElementById('original_jenis_jabatan').value;
            if (!original) {
                warnDiv.classList.add('d-none');
                return;
            }

            const current = selectJab.value;
            const originalLower = original.toLowerCase();

            let isMismatch = false;
            if (originalLower.includes('struktural') && current !== 'Jabatan Struktural') isMismatch = true;
            else if (originalLower.includes('fungsional') && !originalLower.includes('umum') && current !== 'Jabatan Fungsional') isMismatch = true;
            else if ((originalLower.includes('umum') || originalLower.includes('pelaksana') || originalLower === '') && current !== 'Jabatan Fungsional Umum/Pelaksana') isMismatch = true;

            if (isMismatch) {
                warnText.innerText = `Peringatan: Pilihan tidak sesuai dengan profil asli Pegawai (Data di sistem: ${original})`;
                warnDiv.classList.remove('d-none');
            } else {
                warnDiv.classList.add('d-none');
            }
        }

        // Manual Sync Jenis Jabatan & Jenis KP
        selectJab.addEventListener('change', function () {
            if (this.value === 'Jabatan Struktural') {
                selectKP.value = 'Kenaikan Pangkat Struktural';
            } else if (this.value === 'Jabatan Fungsional') {
                selectKP.value = 'Kenaikan Pangkat Jabatan Fungsional';
            } else if (this.value === 'Jabatan Fungsional Umum/Pelaksana') {
                selectKP.value = 'Kenaikan Pangkat Reguler';
            }
            updateDocumentList();
            checkJabatanMismatch();
        });

        selectKP.addEventListener('change', function () {
            if (this.value === 'Kenaikan Pangkat Struktural') {
                selectJab.value = 'Jabatan Struktural';
            } else if (this.value === 'Kenaikan Pangkat Jabatan Fungsional') {
                selectJab.value = 'Jabatan Fungsional';
            } else if (this.value === 'Kenaikan Pangkat Reguler') {
                selectJab.value = 'Jabatan Fungsional Umum/Pelaksana';
            }
            updateDocumentList();
            checkJabatanMismatch();
        });

        // DOCUMENT LOGIC
        const docListContainer = document.getElementById('document-list');
        const sectionAK = document.getElementById('section-angka-kredit');

        const currentYear = new Date().getFullYear();
        const year1 = currentYear - 1;
        const year2 = currentYear - 2;

        // Initialize docs object in global scope for accessibility
        window.docsConfig = {
            'reguler': [
                `Dok Realisasi SKP tahun pertama (${year1})`,
                `Dok Realisasi SKP tahun kedua (${year2})`,
                'DOK SK KP Perorangan / SK Petikan Terakhir',
                'Dok SK PNS Perorangan / Petikan',
                'Dok SK CPNS Perorangan / Petikan',
                'Surat Tanda Lulus Ujian Dinas',
                'Dok SK Jabatan (Atasan Langsung)',
                'Dok SK Jabatan (terakhir)',
                'Dok Surat Pelantikan (dalam Jabatan Terakhir)',
                'Dok SK Tugas Belajar / Izin Belajar',
                'Ijazah',
                'Transkrip nilai',
                'Surat Pencantuman Gelar',
                'Surat Keputusan Pemberhentian Jabatan Fungsional / Struktural',
                'SK Mutasi / Perpindahan ke unit kerja baru'
            ],
            'fungsional': [
                `Dok Realisasi SKP tahun pertama (${year1})`,
                `Dok Realisasi SKP tahun kedua (${year2})`,
                'Sertifikat Pendidik (Khusus Jabatan Fungsional Guru)',
                'SK Pembagian Tugas 1 Tahun Terakhir (Khusus Jabatan Fungsional Guru)',
                'DOK SK KP Perorangan / SK Petikan Terakhir',
                'SK PAK (Penilaian Angka Kredit)',
                'Asli Klarifikasi PAK',
                'Dok SK Jabatan (Fungsional)',
                'Dok SK PNS Perorangan / Petikan',
                'Dok SK CPNS Perorangan / Petikan',
                'Surat Pencantuman Gelar',
                'SK Pengangkatan Pertama Dalam Jabatan Fungsional',
                'Dok Surat Pelantikan (dalam Jabatan Terakhir)',
                'Surat Keputusan Pemberhentian Jabatan Fungsional',
                'Surat Keputusan Pengangkatan Kembali Jabatan Fungsional',
                'Surat Pernyataan Tanggung Jawab Mutlak Penetapan PAK',
                'SK Alih Jenjang (Pengangkatan Dalam Jenjang Ahli)',
                'Surat Keputusan Kenaikan Jabatan',
                'Sertifikat Diklat / Lulus Uji Kompetensi',
                'Transkrip nilai',
                'Dok SK Jabatan (Atasan Langsung)',
                'Ijazah'
            ],
            'struktural': [
                `Dok Realisasi SKP tahun pertama (${year1})`,
                `Dok Realisasi SKP tahun kedua (${year2})`,
                'DOK SK KP Perorangan / SK Petikan Terakhir',
                'Dok SK Jabatan (Terakhir)',
                'Dok SK PNS Perorangan / Petikan',
                'Dok SK CPNS Perorangan / Petikan',
                'Surat Pencantuman Gelar',
                'Dok Surat Pelantikan (dalam Jabatan Terakhir)',
                'Surat Keputusan Pemberhentian dari Jabatan Fungsional',
                'Surat Keputusan Kenaikan Jabatan',
                'Sertifikat Diklat Kepemimpinan',
                'Transkrip nilai',
                'Dok SK Jabatan (Atasan Langsung)',
                'Ijazah'
            ],
            'iv_up': [
                `Dok Realisasi SKP tahun pertama (${year1})`,
                `Dok Realisasi SKP tahun kedua (${year2})`,
                'DOK SK KP Perorangan / SK Petikan Terakhir',
                'Dok SK Jabatan (terakhir)',
                'Dok Surat Pelantikan (dalam Jabatan Terakhir)',
                'Surat Tanda Lulus Ujian Dinas',
                'Ijazah',
                'Transkrip nilai',
                'Surat Pencantuman Gelar',
                'Sertifikat Diklat Kepemimpinan (DIKLATPIM)',
                'Surat Keputusan Pemberhentian Jabatan Fungsional',
                'Dok SK Jabatan (Atasan Langsung)'
            ]
        };

        window.updateDocumentList = function() {
            const docs = window.docsConfig;
            const types = selectKP.value;
            const existingDocs = window.detectedDocs || {};
            const curYear = new Date().getFullYear();
            const prevYear = curYear - 1;


            let selectedDocs = docs.reguler;
            sectionAK.classList.add('d-none');

            if (types === 'Kenaikan Pangkat Jabatan Fungsional') {
                sectionAK.classList.remove('d-none');
                selectedDocs = docs.fungsional;
            } else if (types === 'Kenaikan Pangkat Struktural') {
                selectedDocs = docs.struktural;
            } else {
                selectedDocs = docs.reguler;
            }

            docListContainer.innerHTML = '';


            selectedDocs.forEach(docName => {
                const upper = docName.toUpperCase();
                let fuzzyKey = null;

                // Even broader matching for better success rate
                if (upper.includes('SKP')) {
                    if (upper.includes('PERTAMA') || upper.includes(curYear.toString())) fuzzyKey = 'FUZZY_SKP1';
                    else if (upper.includes('KEDUA') || upper.includes(prevYear.toString())) fuzzyKey = 'FUZZY_SKP2';
                }
                else if (upper.includes('KP') || upper.includes('PETIKAN')) fuzzyKey = 'FUZZY_SKKP';
                else if (upper.includes('PNS') && !upper.includes('CPNS')) fuzzyKey = 'FUZZY_SKPNS';
                else if (upper.includes('CPNS')) fuzzyKey = 'FUZZY_SKCPNS';
                else if (upper.includes('UJIAN') && upper.includes('DINAS')) fuzzyKey = 'FUZZY_UJIAN_DINAS';
                else if (upper.includes('JABATAN') && (upper.includes('ATASAN') || upper.includes('LANGSUNG'))) fuzzyKey = 'FUZZY_SK_JABATAN_ATASAN';
                else if (upper.includes('JABATAN') && (upper.includes('TERAKHIR') || upper.includes('SAAT INI'))) fuzzyKey = 'FUZZY_SK_JABATAN_TERAKHIR';
                else if (upper.includes('PELANTIKAN')) fuzzyKey = 'FUZZY_PELANTIKAN';
                else if (upper.includes('IJAZAH')) fuzzyKey = 'FUZZY_IJAZAH';
                else if (upper.includes('TRANSKRIP')) fuzzyKey = 'FUZZY_TRANSKRIP';
                else if (upper.includes('GELAR')) fuzzyKey = 'FUZZY_GELAR';
                else if (upper.includes('PEMBERHENTIAN')) fuzzyKey = 'FUZZY_PEMBERHENTIAN';
                else if (upper.includes('MUTASI') || upper.includes('PINDAH')) fuzzyKey = 'FUZZY_MUTASI';

                // CHECK BOTH FUZZY AND EXACT NORM
                const lookupKey = docName.toUpperCase().replace(/[^A-Z0-9]/g, '');
                const isExisting = (fuzzyKey && existingDocs[fuzzyKey]) ? existingDocs[fuzzyKey] : existingDocs[lookupKey];
                const slug = docName.toLowerCase().replace(/[\/\(\)\-]/g, ' ').trim().replace(/\s+/g, '_');

                const col = document.createElement('div');
                col.className = 'col-md-6';
                col.innerHTML = `
                    <div class="p-4 border ${isExisting ? 'border-success bg-success bg-opacity-10' : 'border-dashed bg-white'} rounded-4 h-100 shadow-sm transition-all" 
                         style="${isExisting ? 'border-width: 2px !important;' : ''}">
                        <div class="d-flex justify-content-between align-items-start mb-2">
                            <label class="form-label fw-bold mb-0 small text-uppercase">${docName}</label>
                            ${isExisting ? `
                                <span class="badge bg-success text-white rounded-pill px-2 py-1" style="font-size: 0.7rem;">
                                    <i class="bi bi-check-circle-fill me-1"></i> BERKAS TERSEDIA
                                </span>
                            ` : `
                                <span class="badge bg-secondary bg-opacity-10 text-secondary rounded-pill px-2 py-1" style="font-size: 0.65rem;">
                                    BELUM ADA
                                </span>
                            `}
                        </div>
                        <input type="file" class="form-control form-control-custom" name="dokumen[${slug}]" ${isExisting ? '' : 'required'}>
                        <div class="form-text mt-2 d-flex justify-content-between align-items-center">
                            <span class="text-muted x-small">${isExisting ? '<span class="text-success fw-bold">Terdeteksi: ' + isExisting.file_path.split('_').pop() + '</span>' : 'Format: PDF (Max 1MB)'}</span>
                            ${isExisting ? `
                                <div class="btn-group">
                                    <input type="hidden" name="reuse[${slug}]" value="${isExisting.file_path}">
                                    <input type="hidden" name="reuse_name[${slug}]" value="${docName}">
                                    <a href="<?= base_url('uploads/dokumen') ?>/${isExisting.file_path}" target="_blank" class="btn btn-sm btn-outline-primary py-0 px-2 x-small">Lihat <i class="bi bi-eye"></i></a>
                                </div>
                            ` : ''}
                        </div>
                    </div>
                `;
                docListContainer.appendChild(col);
            });
        }

        // Event listeners for changes
        selectKP.addEventListener('change', window.updateDocumentList);
        document.querySelectorAll('input[name="jenis_prosedur"]').forEach(radio => {
            radio.addEventListener('change', window.updateDocumentList);
        });

        // File Size Validation
        docListContainer.addEventListener('change', function (e) {
            if (e.target.type === 'file') {
                const file = e.target.files[0];
                if (file && file.size > 1024 * 1024) {
                    alert('⚠️ FILE TERLALU BESAR\n\nFile "' + file.name + '" berukuran ' + (file.size / 1024 / 1024).toFixed(2) + ' MB.\nBatas maksimal adalah 1.00 MB.\n\nSilakan gunakan file yang lebih kecil atau kompres PDF Anda.');
                    e.target.value = ''; // Clear the input
                }
            }
        });

        // Initialize on start
        window.updateDocumentList();

        // Listen for Jenis KP changes to toggle grade editability
        selectKP.addEventListener('change', handleManualGradeEdit);
    });

    // Grade Logic (Moved to global scope)
    const gradeSequence = [
        'I/a', 'I/b', 'I/c', 'I/d',
        'II/a', 'II/b', 'II/c', 'II/d',
        'III/a', 'III/b', 'III/c', 'III/d',
        'IV/a', 'IV/b', 'IV/c', 'IV/d', 'IV/e'
    ];

    function determineNextGrade(currentGrade) {
        if (!currentGrade) return;

        let cleanCurrent = currentGrade.trim();
        let index = gradeSequence.indexOf(cleanCurrent);

        const golBaruInp = document.getElementById('inp-gol_baru');
        if (golBaruInp && index !== -1 && index < gradeSequence.length - 1) {
            golBaruInp.value = gradeSequence[index + 1];
        }

        handleManualGradeEdit();
    }

    function handleManualGradeEdit() {
        const selectKP = document.getElementById('select_jenis_kp');
        const golBaruInp = document.getElementById('inp-gol_baru');
        if (!selectKP || !golBaruInp) return;

        // Allow manual edit if Penyesuaian Ijazah
        if (selectKP.value === 'Kenaikan Pangkat Memperoleh Ijazah/Penyesuaian Ijazah') {
            golBaruInp.classList.remove('bg-light');
            golBaruInp.readOnly = false;
        } else {
            golBaruInp.classList.add('bg-light');
            golBaruInp.readOnly = true;
        }
    }

    // Supervisor Search Logic
    function searchSupervisor() {
        const nip = document.getElementById('inp-atasan_nip').value;
        if (!nip || nip.length < 9) {
            alert('Silakan masukkan NIP yang valid (minimal 9 digit).');
            return;
        }

        const btn = document.querySelector('button[onclick="searchSupervisor()"]');
        const originalContent = btn.innerHTML;
        btn.innerHTML = '<span class="spinner-border spinner-border-sm"></span>';
        btn.disabled = true;

        fetch(`<?= site_url('api/pegawai') ?>/${nip}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const p = data.pegawai;
                    let fullName = '';
                    if (p.gelar_depan) fullName += p.gelar_depan + ' ';
                    fullName += p.nama;
                    if (p.gelar_belakang) fullName += ', ' + p.gelar_belakang;

                    document.getElementById('inp-atasan_nama').value = fullName;
                    document.getElementById('inp-atasan_jabatan').value = p.jabatan;
                    document.getElementById('inp-atasan_gol').value = p.gol_akhir;
                } else {
                    alert('NIP Atasan tidak ditemukan di database.');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Terjadi kesalahan saat mencari data.');
            })
            .finally(() => {
                btn.innerHTML = originalContent;
                btn.disabled = false;
            });
    }
</script>
<?= $this->endSection() ?>