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

<div class="row justify-content-center">
    <div class="col-12 col-xl-10">
        
        <div class="card border-0 shadow-sm mb-4" style="border-radius: 12px;">
            <div class="card-body p-4 bg-light bg-gradient" style="border-radius: 12px 12px 0 0;">
                <div class="d-flex align-items-center gap-3">
                    <div class="bg-primary bg-opacity-10 p-3 rounded-circle text-primary" style="font-size: 1.8rem; line-height: 1;">
                        <i class="bi bi-shield-check"></i>
                    </div>
                    <div>
                        <h5 class="fw-bold mb-0 text-dark">Pusat Verifikasi Data Mandiri</h5>
                        <small class="text-muted">Periksa kembali data Anda. Data yang dikunci hanya bisa diubah melalui Wali Kelas/Operator TU.</small>
                    </div>
                </div>
            </div>

            <div class="card-body p-4">
                <form action="/siswa/profile/update" method="post" id="profileForm">
                    <?= csrf_field() ?>

                    <!-- Nav Tabs -->
                    <ul class="nav nav-tabs mb-4" id="studentEditTabs" role="tablist">
                        <li class="nav-item">
                            <button class="nav-link active" id="identitas-tab" data-bs-toggle="tab" data-bs-target="#identitas" type="button" role="tab">
                                <i class="bi bi-person me-1"></i>Identitas Siswa
                            </button>
                        </li>
                        <li class="nav-item">
                            <button class="nav-link" id="akademik-tab" data-bs-toggle="tab" data-bs-target="#akademik" type="button" role="tab">
                                <i class="bi bi-mortarboard me-1"></i>Akademik
                            </button>
                        </li>
                        <li class="nav-item">
                            <button class="nav-link" id="orangtua-tab" data-bs-toggle="tab" data-bs-target="#orangtua" type="button" role="tab">
                                <i class="bi bi-people me-1"></i>Keluarga / Orang Tua
                            </button>
                        </li>
                        <li class="nav-item">
                            <button class="nav-link" id="alamat-tab" data-bs-toggle="tab" data-bs-target="#alamat" type="button" role="tab">
                                <i class="bi bi-geo-alt me-1"></i>Alamat & Kontak
                            </button>
                        </li>
                    </ul>

                    <div class="tab-content" id="studentEditTabsContent">

                        <!-- Tab Identitas -->
                        <div class="tab-pane fade show active" id="identitas" role="tabpanel">
                            <div class="row g-3">
                                <div class="col-md-3">
                                    <label class="form-label">NIS (Nomor Induk Siswa) 🔒</label>
                                    <input type="text" class="form-control bg-light text-muted" value="<?= esc($student['nis']) ?>" readonly>
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">NISN 🔒</label>
                                    <input type="text" class="form-control bg-light text-muted" value="<?= esc($student['nisn'] ?? '-') ?>" readonly>
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">NIK (No. KTP/KIA)</label>
                                    <?php if (in_array('nik', $editableFields)): ?>
                                        <input type="text" name="nik" id="nik" class="form-control border-primary" value="<?= esc(old('nik', $student['nik'] ?? '')) ?>" placeholder="16 digit NIK">
                                    <?php else: ?>
                                        <input type="text" class="form-control bg-light text-muted" value="<?= esc($student['nik'] ?? '-') ?> 🔒" readonly>
                                    <?php endif; ?>
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">No. KIP (Kartu Indonesia Pintar)</label>
                                    <?php if (in_array('kip_no', $editableFields)): ?>
                                        <input type="text" name="kip_no" id="kip_no" class="form-control border-primary" value="<?= esc(old('kip_no', $student['kip_no'] ?? '')) ?>" placeholder="Masukkan nomor KIP jika ada">
                                    <?php else: ?>
                                        <input type="text" class="form-control bg-light text-muted" value="<?= esc($student['kip_no'] ?? '-') ?> 🔒" readonly>
                                    <?php endif; ?>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">Nama Lengkap 🔒</label>
                                    <input type="text" class="form-control bg-light text-muted" value="<?= esc($student['full_name']) ?>" readonly>
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">Jenis Kelamin</label>
                                    <?php if (in_array('gender', $editableFields)): ?>
                                        <select name="gender" class="form-select border-primary">
                                            <option value="L" <?= ($student['gender'] ?? '') === 'L' ? 'selected' : '' ?>>Laki-laki</option>
                                            <option value="P" <?= ($student['gender'] ?? '') === 'P' ? 'selected' : '' ?>>Perempuan</option>
                                        </select>
                                    <?php else: ?>
                                        <input type="text" class="form-control bg-light text-muted" value="<?= $student['gender'] === 'L' ? 'Laki-laki' : 'Perempuan' ?> 🔒" readonly>
                                    <?php endif; ?>
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">Agama</label>
                                    <?php if (in_array('religion', $editableFields)): ?>
                                        <select name="religion" class="form-select border-primary">
                                            <?php foreach (['Islam', 'Kristen', 'Katolik', 'Hindu', 'Budha', 'Konghucu'] as $rel): ?>
                                                <option value="<?= $rel ?>" <?= ($student['religion'] ?? 'Islam') === $rel ? 'selected' : '' ?>><?= $rel ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    <?php else: ?>
                                        <input type="text" class="form-control bg-light text-muted" value="<?= esc($student['religion'] ?? 'Islam') ?> 🔒" readonly>
                                    <?php endif; ?>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">Tempat Lahir 🔒</label>
                                    <input type="text" class="form-control bg-light text-muted" value="<?= esc($student['birth_place'] ?? '-') ?>" readonly>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">Tanggal Lahir 🔒</label>
                                    <input type="text" class="form-control bg-light text-muted" value="<?= !empty($student['birth_date']) ? date('d-m-Y', strtotime($student['birth_date'])) : '-' ?>" readonly>
                                </div>
                            </div>
                        </div>

                        <!-- Tab Akademik -->
                        <div class="tab-pane fade" id="akademik" role="tabpanel">
                            <div class="row g-3">
                                <div class="col-md-3">
                                    <label class="form-label">Tahun Masuk</label>
                                    <?php if (in_array('entry_year', $editableFields)): ?>
                                        <input type="number" name="entry_year" class="form-control border-primary" value="<?= esc(old('entry_year', $student['entry_year'] ?? '')) ?>" placeholder="Cth: 2023">
                                    <?php else: ?>
                                        <input type="text" class="form-control bg-light text-muted" value="<?= esc($student['entry_year']) ?> 🔒" readonly>
                                    <?php endif; ?>
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">Tanggal Masuk</label>
                                    <?php if (in_array('entry_date', $editableFields)): ?>
                                        <input type="date" name="entry_date" class="form-control border-primary" value="<?= esc(old('entry_date', $student['entry_date'] ?? '')) ?>">
                                    <?php else: ?>
                                        <input type="text" class="form-control bg-light text-muted" value="<?= !empty($student['entry_date']) ? date('d-m-Y', strtotime($student['entry_date'])) : '-' ?> 🔒" readonly>
                                    <?php endif; ?>
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">Asal Sekolah</label>
                                    <?php if (in_array('origin_school', $editableFields)): ?>
                                        <input type="text" name="origin_school" id="origin_school" class="form-control border-primary" value="<?= esc(old('origin_school', $student['origin_school'] ?? '')) ?>" placeholder="Nama sekolah asal">
                                    <?php else: ?>
                                        <input type="text" class="form-control bg-light text-muted" value="<?= esc($student['origin_school'] ?? '-') ?> 🔒" readonly>
                                    <?php endif; ?>
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">No. Seri Ijazah Kelulusan</label>
                                    <?php if (in_array('graduation_certificate_no', $editableFields)): ?>
                                        <input type="text" name="graduation_certificate_no" id="graduation_certificate_no" class="form-control border-primary" value="<?= esc(old('graduation_certificate_no', $student['graduation_certificate_no'] ?? '')) ?>" placeholder="No. Seri Ijazah SD/MI asal">
                                    <?php else: ?>
                                        <input type="text" class="form-control bg-light text-muted" value="<?= esc($student['graduation_certificate_no'] ?? '-') ?> 🔒" readonly>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>

                        <!-- Tab Orang Tua -->
                        <div class="tab-pane fade" id="orangtua" role="tabpanel">
                            <div class="row g-3">
                                <div class="col-12">
                                    <h6 class="fw-semibold text-primary"><i class="bi bi-file-earmark-person me-1"></i>Data Kartu Keluarga (KK)</h6>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">No. Kartu Keluarga (KK)</label>
                                    <?php if (in_array('family_card_no', $editableFields)): ?>
                                        <input type="text" name="family_card_no" id="family_card_no" class="form-control border-primary" value="<?= esc(old('family_card_no', $student['family_card_no'] ?? '')) ?>" placeholder="16 digit Nomor KK">
                                    <?php else: ?>
                                        <input type="text" class="form-control bg-light text-muted" value="<?= esc($student['family_card_no'] ?? '-') ?> 🔒" readonly>
                                    <?php endif; ?>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">Nama Kepala Keluarga</label>
                                    <?php if (in_array('family_head_name', $editableFields)): ?>
                                        <input type="text" name="family_head_name" id="family_head_name" class="form-control border-primary" value="<?= esc(old('family_head_name', $student['family_head_name'] ?? '')) ?>" placeholder="Nama kepala keluarga di KK">
                                    <?php else: ?>
                                        <input type="text" class="form-control bg-light text-muted" value="<?= esc($student['family_head_name'] ?? '-') ?> 🔒" readonly>
                                    <?php endif; ?>
                                </div>
                                <div class="col-12 mt-3">
                                    <div class="alert alert-light border-0 py-2 small text-muted mb-2">
                                         <i class="bi bi-info-circle me-1"></i>Lengkapi data Ayah dan Ibu sesuai dengan Kartu Keluarga Anda.
                                    </div>
                                </div>

                                <!-- DATA AYAH -->
                                <div class="col-12 mt-3">
                                    <h6 class="fw-semibold text-primary pb-2 border-bottom">
                                        <i class="bi bi-gender-male me-1"></i>Data Ayah
                                    </h6>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">Nama Ayah</label>
                                    <?php if (in_array('father_name', $editableFields)): ?>
                                         <input type="text" name="father_name" id="father_name" class="form-control border-primary" value="<?= esc(old('father_name', $student['father_name'] ?? '')) ?>" placeholder="Nama lengkap Ayah">
                                    <?php else: ?>
                                         <input type="text" class="form-control bg-light text-muted" value="<?= esc($student['father_name'] ?? '-') ?> 🔒" readonly>
                                    <?php endif; ?>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">NIK Ayah</label>
                                    <?php if (in_array('father_nik', $editableFields)): ?>
                                         <input type="text" name="father_nik" id="father_nik" class="form-control border-primary" value="<?= esc(old('father_nik', $student['father_nik'] ?? '')) ?>" placeholder="NIK Ayah">
                                    <?php else: ?>
                                         <input type="text" class="form-control bg-light text-muted" value="<?= esc($student['father_nik'] ?? '-') ?> 🔒" readonly>
                                    <?php endif; ?>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">Tempat Lahir Ayah</label>
                                    <?php if (in_array('father_birth_place', $editableFields)): ?>
                                        <input type="text" name="father_birth_place" id="father_birth_place" class="form-control border-primary" value="<?= esc(old('father_birth_place', $student['father_birth_place'] ?? '')) ?>" placeholder="Tempat Lahir Ayah">
                                    <?php else: ?>
                                        <input type="text" class="form-control bg-light text-muted" value="<?= esc($student['father_birth_place'] ?? '-') ?> 🔒" readonly>
                                    <?php endif; ?>
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">Tahun Lahir Ayah</label>
                                    <?php if (in_array('father_birth', $editableFields)): ?>
                                         <input type="number" name="father_birth" id="father_birth" class="form-control border-primary" value="<?= esc(old('father_birth', $student['father_birth'] ?? '')) ?>" placeholder="Cth: 1980">
                                    <?php else: ?>
                                         <input type="text" class="form-control bg-light text-muted" value="<?= esc($student['father_birth'] ?? '-') ?> 🔒" readonly>
                                    <?php endif; ?>
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">Pendidikan Ayah</label>
                                    <?php if (in_array('father_edu', $editableFields)): ?>
                                         <input type="text" name="father_edu" id="father_edu" class="form-control border-primary" value="<?= esc(old('father_edu', $student['father_edu'] ?? '')) ?>" placeholder="Cth: SMA/S1">
                                    <?php else: ?>
                                         <input type="text" class="form-control bg-light text-muted" value="<?= esc($student['father_edu'] ?? '-') ?> 🔒" readonly>
                                    <?php endif; ?>
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">Pekerjaan Ayah</label>
                                    <?php if (in_array('father_job', $editableFields)): ?>
                                         <input type="text" name="father_job" id="father_job" class="form-control border-primary" value="<?= esc(old('father_job', $student['father_job'] ?? '')) ?>" placeholder="Pekerjaan Ayah">
                                    <?php else: ?>
                                         <input type="text" class="form-control bg-light text-muted" value="<?= esc($student['father_job'] ?? '-') ?> 🔒" readonly>
                                    <?php endif; ?>
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">No. HP Ayah</label>
                                    <?php if (in_array('father_phone', $editableFields)): ?>
                                         <input type="text" name="father_phone" id="father_phone" class="form-control border-primary" value="<?= esc(old('father_phone', $student['father_phone'] ?? '')) ?>" placeholder="No. HP Ayah">
                                    <?php else: ?>
                                         <input type="text" class="form-control bg-light text-muted" value="<?= esc($student['father_phone'] ?? '-') ?> 🔒" readonly>
                                    <?php endif; ?>
                                </div>

                                <!-- DATA IBU -->
                                <div class="col-12 mt-4">
                                    <h6 class="fw-semibold text-danger pb-2 border-bottom">
                                        <i class="bi bi-gender-female me-1"></i>Data Ibu
                                    </h6>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">Nama Ibu</label>
                                    <?php if (in_array('mother_name', $editableFields)): ?>
                                         <input type="text" name="mother_name" id="mother_name" class="form-control border-primary" value="<?= esc(old('mother_name', $student['mother_name'] ?? '')) ?>" placeholder="Nama lengkap Ibu">
                                    <?php else: ?>
                                         <input type="text" class="form-control bg-light text-muted" value="<?= esc($student['mother_name'] ?? '-') ?> 🔒" readonly>
                                    <?php endif; ?>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">NIK Ibu</label>
                                    <?php if (in_array('mother_nik', $editableFields)): ?>
                                         <input type="text" name="mother_nik" id="mother_nik" class="form-control border-primary" value="<?= esc(old('mother_nik', $student['mother_nik'] ?? '')) ?>" placeholder="NIK Ibu">
                                    <?php else: ?>
                                         <input type="text" class="form-control bg-light text-muted" value="<?= esc($student['mother_nik'] ?? '-') ?> 🔒" readonly>
                                    <?php endif; ?>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">Tempat Lahir Ibu</label>
                                    <?php if (in_array('mother_birth_place', $editableFields)): ?>
                                        <input type="text" name="mother_birth_place" id="mother_birth_place" class="form-control border-primary" value="<?= esc(old('mother_birth_place', $student['mother_birth_place'] ?? '')) ?>" placeholder="Tempat Lahir Ibu">
                                    <?php else: ?>
                                        <input type="text" class="form-control bg-light text-muted" value="<?= esc($student['mother_birth_place'] ?? '-') ?> 🔒" readonly>
                                    <?php endif; ?>
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">Tahun Lahir Ibu</label>
                                    <?php if (in_array('mother_birth', $editableFields)): ?>
                                         <input type="number" name="mother_birth" id="mother_birth" class="form-control border-primary" value="<?= esc(old('mother_birth', $student['mother_birth'] ?? '')) ?>" placeholder="Cth: 1983">
                                    <?php else: ?>
                                         <input type="text" class="form-control bg-light text-muted" value="<?= esc($student['mother_birth'] ?? '-') ?> 🔒" readonly>
                                    <?php endif; ?>
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">Pendidikan Ibu</label>
                                    <?php if (in_array('mother_edu', $editableFields)): ?>
                                         <input type="text" name="mother_edu" id="mother_edu" class="form-control border-primary" value="<?= esc(old('mother_edu', $student['mother_edu'] ?? '')) ?>" placeholder="Cth: SMP/SMA/D3">
                                    <?php else: ?>
                                         <input type="text" class="form-control bg-light text-muted" value="<?= esc($student['mother_edu'] ?? '-') ?> 🔒" readonly>
                                    <?php endif; ?>
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">Pekerjaan Ibu</label>
                                    <?php if (in_array('mother_job', $editableFields)): ?>
                                         <input type="text" name="mother_job" id="mother_job" class="form-control border-primary" value="<?= esc(old('mother_job', $student['mother_job'] ?? '')) ?>" placeholder="Pekerjaan Ibu">
                                    <?php else: ?>
                                         <input type="text" class="form-control bg-light text-muted" value="<?= esc($student['mother_job'] ?? '-') ?> 🔒" readonly>
                                    <?php endif; ?>
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">No. HP Ibu</label>
                                    <?php if (in_array('mother_phone', $editableFields)): ?>
                                         <input type="text" name="mother_phone" id="mother_phone" class="form-control border-primary" value="<?= esc(old('mother_phone', $student['mother_phone'] ?? '')) ?>" placeholder="No. HP Ibu">
                                    <?php else: ?>
                                         <input type="text" class="form-control bg-light text-muted" value="<?= esc($student['mother_phone'] ?? '-') ?> 🔒" readonly>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>

                        <!-- Tab Alamat -->
                        <div class="tab-pane fade" id="alamat" role="tabpanel">
                            <div class="row g-3">
                                <div class="col-md-6">
                                    <label class="form-label">Alamat / Jalan / Dusun</label>
                                    <?php if (in_array('address', $editableFields)): ?>
                                        <input type="text" name="address" id="address" class="form-control border-primary" value="<?= esc(old('address', $student['address'] ?? '')) ?>" placeholder="Nama jalan, gang, atau RT/RW">
                                    <?php else: ?>
                                        <input type="text" class="form-control bg-light text-muted" value="<?= esc($student['address'] ?? '-') ?> 🔒" readonly>
                                    <?php endif; ?>
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">RT</label>
                                    <?php if (in_array('rt', $editableFields)): ?>
                                        <input type="text" name="rt" id="rt" class="form-control border-primary" value="<?= esc(old('rt', $student['rt'] ?? '')) ?>" placeholder="RT">
                                    <?php else: ?>
                                        <input type="text" class="form-control bg-light text-muted" value="<?= esc($student['rt'] ?? '-') ?> 🔒" readonly>
                                    <?php endif; ?>
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">RW</label>
                                    <?php if (in_array('rw', $editableFields)): ?>
                                        <input type="text" name="rw" id="rw" class="form-control border-primary" value="<?= esc(old('rw', $student['rw'] ?? '')) ?>" placeholder="RW">
                                    <?php else: ?>
                                        <input type="text" class="form-control bg-light text-muted" value="<?= esc($student['rw'] ?? '-') ?> 🔒" readonly>
                                    <?php endif; ?>
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">Desa / Kelurahan</label>
                                    <?php if (in_array('village', $editableFields)): ?>
                                        <input type="text" name="village" id="village" class="form-control border-primary" value="<?= esc(old('village', $student['village'] ?? '')) ?>" placeholder="Desa/Kelurahan">
                                    <?php else: ?>
                                        <input type="text" class="form-control bg-light text-muted" value="<?= esc($student['village'] ?? '-') ?> 🔒" readonly>
                                    <?php endif; ?>
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">Kecamatan</label>
                                    <?php if (in_array('district', $editableFields)): ?>
                                        <input type="text" name="district" id="district" class="form-control border-primary" value="<?= esc(old('district', $student['district'] ?? '')) ?>" placeholder="Kecamatan">
                                    <?php else: ?>
                                        <input type="text" class="form-control bg-light text-muted" value="<?= esc($student['district'] ?? '-') ?> 🔒" readonly>
                                    <?php endif; ?>
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">Kota / Kabupaten</label>
                                    <?php if (in_array('city', $editableFields)): ?>
                                        <input type="text" name="city" id="city" class="form-control border-primary" value="<?= esc(old('city', $student['city'] ?? '')) ?>" placeholder="Kabupaten/Kota">
                                    <?php else: ?>
                                        <input type="text" class="form-control bg-light text-muted" value="<?= esc($student['city'] ?? '-') ?> 🔒" readonly>
                                    <?php endif; ?>
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">Provinsi</label>
                                    <?php if (in_array('province', $editableFields)): ?>
                                        <input type="text" name="province" id="province" class="form-control border-primary" value="<?= esc(old('province', $student['province'] ?? '')) ?>" placeholder="Provinsi">
                                    <?php else: ?>
                                        <input type="text" class="form-control bg-light text-muted" value="<?= esc($student['province'] ?? '-') ?> 🔒" readonly>
                                    <?php endif; ?>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">Kode Pos</label>
                                    <?php if (in_array('postal_code', $editableFields)): ?>
                                        <input type="text" name="postal_code" id="postal_code" class="form-control border-primary" value="<?= esc(old('postal_code', $student['postal_code'] ?? '')) ?>" placeholder="Kode Pos">
                                    <?php else: ?>
                                        <input type="text" class="form-control bg-light text-muted" value="<?= esc($student['postal_code'] ?? '-') ?> 🔒" readonly>
                                    <?php endif; ?>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">No. HP Siswa / Wali</label>
                                    <?php if (in_array('phone', $editableFields)): ?>
                                        <input type="text" name="phone" id="phone" class="form-control border-primary" value="<?= esc(old('phone', $student['phone'] ?? '')) ?>" placeholder="Nomor HP aktif">
                                    <?php else: ?>
                                        <input type="text" class="form-control bg-light text-muted" value="<?= esc($student['phone'] ?? '-') ?> 🔒" readonly>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>

                    </div>

                    <!-- Action and Declaration -->
                    <?php
                    $allowedFieldsList = [
                        'nik', 'gender', 'religion', 'kip_no', 'graduation_certificate_no', 'origin_school', 'entry_year', 'entry_date',
                        'phone', 'address', 'rt', 'rw', 'village', 'district', 'city', 'province', 'postal_code',
                        'family_card_no', 'family_head_name',
                        'father_name', 'father_nik', 'father_birth_place', 'father_birth', 'father_edu', 'father_job', 'father_phone',
                        'mother_name', 'mother_nik', 'mother_birth_place', 'mother_birth', 'mother_edu', 'mother_job', 'mother_phone'
                    ];
                    // Hitung jumlah field yang diizinkan untuk diedit
                    $hasEditable = false;
                    foreach ($allowedFieldsList as $f) {
                        if (in_array($f, $editableFields)) {
                            $hasEditable = true;
                            break;
                        }
                    }
                    ?>
                    <?php if ($hasEditable): ?>
                    <div class="mt-5 pt-3 border-top">
                        <div class="form-check mb-3">
                            <input class="form-check-input border-primary" type="checkbox" id="declareCheck" required>
                            <label class="form-check-label text-dark small" for="declareCheck">
                                Saya dengan sadar menyatakan bahwa seluruh data mandiri yang saya masukkan di atas adalah benar sesuai dokumen asli, dan siap bertanggung jawab jika di kemudian hari ditemukan kesalahan data.
                            </label>
                        </div>
                        <div class="d-flex justify-content-end">
                            <button type="submit" class="btn btn-primary px-4 rounded-pill" id="submitBtn" disabled>
                                <i class="bi bi-save me-2"></i>Simpan Perubahan
                            </button>
                        </div>
                    </div>
                    <?php endif; ?>

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

<script>
document.addEventListener('DOMContentLoaded', function() {
    // 1. Logika Checkbox Deklarasi
    const check = document.getElementById('declareCheck');
    const btn = document.getElementById('submitBtn');
    if (check && btn) {
        check.addEventListener('change', function() {
            btn.disabled = !this.checked;
        });
    }

    // Helper function untuk alert
    const showAlert = (title, text) => {
        if (typeof Swal !== 'undefined') {
            Swal.fire({
                icon: 'error',
                title: title,
                text: text,
                confirmButtonColor: '#dc3545'
            });
        } else {
            alert(title + "\n" + text);
        }
    };

    // 2. Konfigurasi Petunjuk Dinamis (Floating Tooltip Bubble)
    const helperConfigs = {
        'nik': 'ℹ️ Masukkan 16 digit NIK Anda sesuai yang tertera pada Kartu Keluarga (KK) asli.',
        'kip_no': 'ℹ️ Opsional. Silakan isi nomor KIP jika Anda memiliki kartu KIP fisik.',
        'origin_school': 'ℹ️ Pastikan penulisan asal sekolah sesuai dokumen rapor atau ijazah.',
        'graduation_certificate_no': 'ℹ️ Harus sesuai dengan ijazah asli kelulusan. Letak nomor seri biasanya di bagian paling bawah tengah lembar ijazah.\nContoh SD: DN-20/D-SD/06/0016744\nMI: MI-13 130000001.',
        'phone': 'ℹ️ Tulis nomor HP diawali dengan 628... (Contoh: 628123456789). Jangan gunakan awalan angka 0.',
        'father_phone': 'ℹ️ Tulis nomor HP diawali dengan 628... (Contoh: 628123456789). Jangan gunakan awalan angka 0.',
        'mother_phone': 'ℹ️ Tulis nomor HP diawali dengan 628... (Contoh: 628123456789). Jangan gunakan awalan angka 0.',
        'address': 'ℹ️ Tuliskan alamat jalan/dusun tepat sesuai Kartu Keluarga (KK).',
        'rt': 'ℹ️ Tuliskan nomor RT tepat sesuai Kartu Keluarga (KK).',
        'rw': 'ℹ️ Tuliskan nomor RW tepat sesuai Kartu Keluarga (KK).',
        'village': 'ℹ️ Tuliskan nama desa/kelurahan tepat sesuai Kartu Keluarga (KK).',
        'district': 'ℹ️ Tuliskan nama kecamatan tepat sesuai Kartu Keluarga (KK).',
        'city': 'ℹ️ Tuliskan nama kota/kabupaten tepat sesuai Kartu Keluarga (KK).',
        'province': 'ℹ️ Tuliskan nama provinsi tepat sesuai Kartu Keluarga (KK).',
        'postal_code': 'ℹ️ Tuliskan kode pos tepat sesuai Kartu Keluarga (KK).',
        // Data Orang Tua
        'family_card_no': 'ℹ️ Masukkan 16 digit Nomor Kartu Keluarga (KK) Anda.',
        'family_head_name': 'ℹ️ Tuliskan nama lengkap Kepala Keluarga sesuai yang tertera pada baris atas KK.',
        'father_name': 'ℹ️ Tuliskan nama lengkap Ayah kandung sesuai dengan dokumen KK.',
        'father_nik': 'ℹ️ Masukkan 16 digit NIK Ayah sesuai dengan dokumen KK.',
        'father_birth_place': 'ℹ️ Tuliskan kota tempat lahir Ayah sesuai dokumen KK.',
        'father_birth': 'ℹ️ Tuliskan tahun lahir Ayah berupa 4 digit angka (Contoh: 1980).',
        'father_edu': 'ℹ️ Isi dengan jenjang pendidikan terakhir Ayah (Contoh: SD, SMP, SMA, S1, S2).',
        'father_job': 'ℹ️ Tuliskan pekerjaan Ayah saat ini (Contoh: Karyawan Swasta, PNS, Wiraswasta, Petani).',
        'mother_name': 'ℹ️ Tuliskan nama lengkap Ibu kandung sesuai dengan dokumen KK.',
        'mother_nik': 'ℹ️ Masukkan 16 digit NIK Ibu sesuai dengan dokumen KK.',
        'mother_birth_place': 'ℹ️ Tuliskan kota tempat lahir Ibu sesuai dokumen KK.',
        'mother_birth': 'ℹ️ Tuliskan tahun lahir Ibu berupa 4 digit angka (Contoh: 1983).',
        'mother_edu': 'ℹ️ Isi dengan jenjang pendidikan terakhir Ibu (Contoh: SD, SMP, SMA, S1, S2).',
        'mother_job': 'ℹ️ Tuliskan pekerjaan Ibu saat ini (Contoh: Ibu Rumah Tangga, Wiraswasta, PNS, Guru).'
    };

    // Buat elemen tooltip global
    const tooltip = document.createElement('div');
    tooltip.style.position = 'absolute';
    tooltip.style.background = '#1e293b';
    tooltip.style.color = '#f8fafc';
    tooltip.style.padding = '10px 14px';
    tooltip.style.borderRadius = '8px';
    tooltip.style.fontSize = '0.8rem';
    tooltip.style.lineHeight = '1.4';
    tooltip.style.boxShadow = '0 10px 25px -5px rgba(0, 0, 0, 0.15), 0 8px 10px -6px rgba(0, 0, 0, 0.15)';
    tooltip.style.zIndex = '99999';
    tooltip.style.pointerEvents = 'none';
    tooltip.style.maxWidth = '300px';
    tooltip.style.whiteSpace = 'pre-line';
    tooltip.style.display = 'none';
    tooltip.style.opacity = '0';
    tooltip.style.transform = 'translateY(8px)';
    tooltip.style.transition = 'opacity 0.2s ease, transform 0.2s ease';

    // Membuat segitiga arrow penunjuk di bawah balon
    const arrow = document.createElement('div');
    arrow.style.position = 'absolute';
    arrow.style.bottom = '-6px';
    arrow.style.left = '20px';
    arrow.style.width = '0';
    arrow.style.height = '0';
    arrow.style.borderWidth = '6px 6px 0';
    arrow.style.borderStyle = 'solid';
    arrow.style.borderColor = '#1e293b transparent transparent transparent';
    tooltip.appendChild(arrow);
    document.body.appendChild(tooltip);

    // Registrasi Event Listener Focus/Blur untuk floating effect
    Object.keys(helperConfigs).forEach(id => {
        const inputEl = document.getElementById(id);
        if (inputEl) {
            inputEl.addEventListener('focus', () => {
                // Bersihkan teks sebelumnya dan isi teks baru
                const nodes = Array.from(tooltip.childNodes);
                nodes.forEach(node => {
                    if (node !== arrow) tooltip.removeChild(node);
                });
                tooltip.insertBefore(document.createTextNode(helperConfigs[id]), arrow);

                // Tampilkan tooltip secara instan agar offsetHeight dapat dihitung
                tooltip.style.display = 'block';

                // Hitung koordinat presisi elemen input di layar
                const rect = inputEl.getBoundingClientRect();
                const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
                const scrollLeft = window.pageXOffset || document.documentElement.scrollLeft;

                // Hitung posisi horizontal & vertikal agar balon melayang pas di atas input
                const tooltipHeight = tooltip.offsetHeight;
                tooltip.style.top = (rect.top + scrollTop - tooltipHeight - 12) + 'px';
                tooltip.style.left = (rect.left + scrollLeft) + 'px';

                // Trigger efek transisi halus (fade & slide up)
                setTimeout(() => {
                    tooltip.style.opacity = '1';
                    tooltip.style.transform = 'translateY(0)';
                }, 20);
            });

            inputEl.addEventListener('blur', () => {
                // Sembunyikan dengan efek transisi keluar
                tooltip.style.opacity = '0';
                tooltip.style.transform = 'translateY(8px)';
                setTimeout(() => {
                    if (tooltip.style.opacity === '0') {
                        tooltip.style.display = 'none';
                    }
                }, 200);
            });
        }
    });

    // 3. Logika UX Auto-Convert Nomor HP (08xx -> 628xx)
    const phoneFields = ['phone', 'father_phone', 'mother_phone'];
    phoneFields.forEach(id => {
        const el = document.getElementById(id);
        if (el) {
            el.addEventListener('input', function() {
                let val = this.value.trim().replace(/\D/g, ''); // bersihkan non-angka
                if (val.startsWith('08')) {
                    val = '628' + val.substring(2);
                } else if (val.startsWith('8')) {
                    val = '628' + val.substring(1);
                }
                this.value = val;
            });
        }
    });

    // 4. Validasi Form saat Submit
    const form = document.getElementById('profileForm');
    if (form) {
        form.addEventListener('submit', function(e) {
            // A. Validasi NIK / KK (Harus 16 Digit Angka)
            const sixteenDigitFields = ['nik', 'family_card_no', 'father_nik', 'mother_nik'];
            for (const fId of sixteenDigitFields) {
                const el = document.getElementById(fId);
                if (el && !el.readOnly) {
                    const val = el.value.trim();
                    if (val.length > 0) {
                        if (val.length !== 16 || /\D/.test(val)) {
                            e.preventDefault();
                            el.focus();
                            el.classList.add('is-invalid');
                            const label = el.closest('.col-md-3, .col-md-4, .col-md-6')?.querySelector('label')?.textContent.replace(/🔒/g, '').trim() || fId.toUpperCase();
                            showAlert('Format ' + label + ' Salah', label + ' harus terdiri dari tepat 16 digit angka.');
                            return;
                        } else {
                            el.classList.remove('is-invalid');
                        }
                    }
                }
            }

            // B. Validasi Tahun Lahir Orang Tua (Harus 4 Digit Angka)
            const yearFields = ['father_birth', 'mother_birth'];
            const currentYear = new Date().getFullYear();
            for (const fId of yearFields) {
                const el = document.getElementById(fId);
                if (el && !el.readOnly) {
                    const val = el.value.trim();
                    if (val.length > 0) {
                        const yearNum = parseInt(val, 10);
                        if (val.length !== 4 || /\D/.test(val) || yearNum < 1900 || yearNum > currentYear) {
                            e.preventDefault();
                            el.focus();
                            el.classList.add('is-invalid');
                            const label = el.closest('.col-md-3, .col-md-4')?.querySelector('label')?.textContent.replace(/🔒/g, '').trim() || fId.toUpperCase();
                            showAlert('Format ' + label + ' Salah', label + ' harus berupa 4 digit tahun yang valid (antara 1900 s.d ' + currentYear + ').');
                            return;
                        } else {
                            el.classList.remove('is-invalid');
                        }
                    }
                }
            }

            // C. Validasi Nomor HP
            for (const phoneId of phoneFields) {
                const el = document.getElementById(phoneId);
                if (el && !el.readOnly) {
                    const val = el.value.trim();
                    if (val.length > 0) {
                        if (!val.startsWith('628') || val.length < 10 || val.length > 15) {
                            e.preventDefault();
                            el.focus();
                            el.classList.add('is-invalid');
                            showAlert('Format No. HP Salah', 'Nomor HP harus diawali dengan 628 dan terdiri dari 10 s.d. 15 digit.');
                            return;
                        } else {
                            el.classList.remove('is-invalid');
                        }
                    }
                }
            }
        });
    }
});
</script>

<?= $this->endSection() ?>
