<div class="container-fluid">

    <!-- Page Title -->
    <div class="row mb-4">
        <div class="col-12">
            <h4 class="mb-0"><i class="bi bi-person-circle me-2"></i>Profil Saya</h4>
            <small class="text-muted">Kelola informasi akun dan data diri Anda</small>
        </div>
    </div>

    <!-- Flash Message -->
    <?php if($this->session->flashdata('success')): ?>
    <div class="alert alert-success alert-dismissible fade show border-0 border-start border-success border-4">
        <i class="bi bi-check-circle-fill me-2"></i><?php echo $this->session->flashdata('success'); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    <?php endif; ?>
    <?php if($this->session->flashdata('error')): ?>
    <div class="alert alert-danger alert-dismissible fade show border-0 border-start border-danger border-4">
        <i class="bi bi-exclamation-circle-fill me-2"></i><?php echo $this->session->flashdata('error'); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    <?php endif; ?>

    <div class="row g-4">

        <!-- ═══ KOLOM KIRI ═══ -->
        <div class="col-lg-4">

            <!-- Card Foto Profil -->
            <div class="card border-0 shadow-sm mb-4" style="border-radius:14px; overflow:hidden;">

                <!-- Banner tanpa SVG -->
                <div style="background:linear-gradient(135deg,#14a897,#0e7b6e); height:90px; position:relative; overflow:hidden;">
                    <div style="position:absolute;top:-20px;right:-20px;width:100px;height:100px;
                                border-radius:50%;background:rgba(255,255,255,0.06);"></div>
                    <div style="position:absolute;bottom:-30px;left:20px;width:80px;height:80px;
                                border-radius:50%;background:rgba(255,255,255,0.05);"></div>
                    <div style="position:absolute;top:10px;left:40%;width:50px;height:50px;
                                border-radius:50%;background:rgba(255,255,255,0.04);"></div>
                </div>

                <div class="card-body text-center px-4 pb-3" style="margin-top:-50px;">

                    <?php
                    $foto_path = 'uploads/foto_profil/' . ($user->foto ?? '');
                    $has_foto  = !empty($user->foto) && file_exists(FCPATH . $foto_path);
                    ?>

                    <!-- Avatar -->
                    <div class="position-relative d-inline-block mb-3">
                        <div id="avatarWrap" style="width:90px;height:90px;border-radius:50%;
                             overflow:hidden;border:4px solid #fff;
                             box-shadow:0 4px 16px rgba(0,0,0,0.15);
                             background:linear-gradient(135deg,#14a897,#0e7b6e);
                             display:flex;align-items:center;justify-content:center;margin:0 auto;">
                            <?php if($has_foto): ?>
                                <img id="avatarImg"
                                     src="<?php echo base_url($foto_path) . '?v=' . time(); ?>"
                                     style="width:100%;height:100%;object-fit:cover;" alt="Foto Profil">
                            <?php else: ?>
                                <i class="bi bi-person-fill text-white" id="avatarIcon" style="font-size:2.5rem;"></i>
                            <?php endif; ?>
                        </div>

                        <!-- Tombol kamera -->
                        <label for="inputFoto" title="Ganti Foto" style="position:absolute;bottom:2px;right:2px;
                               width:28px;height:28px;border-radius:50%;
                               background:#14a897;border:2px solid #fff;
                               display:flex;align-items:center;justify-content:center;
                               cursor:pointer;box-shadow:0 2px 6px rgba(0,0,0,0.2);">
                            <i class="bi bi-camera-fill text-white" style="font-size:0.7rem;"></i>
                        </label>
                    </div>

                    <h5 class="fw-bold mb-1"><?php echo htmlspecialchars($user->nama_lengkap); ?></h5>
                    <span class="badge mb-2" style="background:rgba(20,168,151,0.15);color:#14a897;
                          border-radius:20px;padding:4px 14px;">
                        <?php echo ucfirst(str_replace('_', ' ', $user->role)); ?>
                    </span>
                    <div class="mb-3">
                        <span class="badge bg-success-subtle text-success">
                            <i class="bi bi-circle-fill me-1" style="font-size:0.45rem;"></i>Aktif
                        </span>
                    </div>

                    <!-- Form Upload Foto -->
                    <form action="<?php echo base_url('profil/upload_foto'); ?>" method="POST"
                          enctype="multipart/form-data" id="formFoto">
                        <input type="hidden"
                               name="<?php echo $this->security->get_csrf_token_name(); ?>"
                               value="<?php echo $this->security->get_csrf_hash(); ?>">
                        <input type="file" id="inputFoto" name="foto"
                               accept="image/jpg,image/jpeg,image/png,image/webp"
                               class="d-none" onchange="previewFoto(this)">
                    </form>

                    <!-- Tombol Simpan/Batal foto (muncul saat preview) -->
                    <div id="fotoActions" class="d-none gap-2 justify-content-center mb-2">
                        <button onclick="document.getElementById('formFoto').submit();"
                                class="btn btn-sm text-white px-3"
                                style="background:#14a897;border-radius:8px;">
                            <i class="bi bi-check-lg me-1"></i>Simpan Foto
                        </button>
                        <button onclick="batalFoto()" class="btn btn-sm btn-light border px-3"
                                style="border-radius:8px;">
                            Batal
                        </button>
                    </div>

                    <!-- Info format -->
                    <div class="mb-2">
                        <small class="text-muted">JPG, PNG, WEBP maks. 2MB</small>
                    </div>

                    <!-- Tombol hapus foto -->
                    <?php if($has_foto): ?>
                    <div id="hapusFotoWrap" class="mb-2">
                      <button onclick="konfirmasiHapusFoto()" class="btn btn-link small text-danger text-decoration-none p-0">
    <i class="bi bi-trash me-1"></i>Hapus Foto
</button>
                    </div>
                    <?php endif; ?>

                </div>

                <!-- Info ringkas akun -->
                <div class="px-4 pb-4">
                    <div class="rounded-3 p-3" style="background:#f4fcfb;">
                        <div class="d-flex justify-content-between align-items-center small mb-2">
                            <span class="text-muted"><i class="bi bi-person me-1"></i>Username</span>
                            <strong><?php echo htmlspecialchars($user->username); ?></strong>
                        </div>
                        <?php if(!empty($user->email)): ?>
                        <div class="d-flex justify-content-between align-items-center small mb-2">
                            <span class="text-muted"><i class="bi bi-envelope me-1"></i>Email</span>
                            <strong><?php echo htmlspecialchars($user->email); ?></strong>
                        </div>
                        <?php endif; ?>
                        <?php if(!empty($user->no_hp)): ?>
                        <div class="d-flex justify-content-between align-items-center small">
                            <span class="text-muted"><i class="bi bi-telephone me-1"></i>No HP</span>
                            <strong><?php echo htmlspecialchars($user->no_hp); ?></strong>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Card Ganti Password -->
            <div class="card border-0 shadow-sm" style="border-radius:14px; border-top:4px solid #ef4444 !important;">
                <div class="card-header bg-white border-0 pt-4 px-4">
                    <h6 class="fw-bold mb-0">
                        <i class="bi bi-shield-lock-fill me-2 text-danger"></i>Ganti Password
                    </h6>
                    <small class="text-muted">Minimal 6 karakter</small>
                </div>
                <div class="card-body px-4 pb-4">
                    <form action="<?php echo base_url('profil/ganti_password'); ?>" method="POST" id="formPassword">
                        <input type="hidden"
                               name="<?php echo $this->security->get_csrf_token_name(); ?>"
                               value="<?php echo $this->security->get_csrf_hash(); ?>">

                        <div class="mb-3">
                            <label class="form-label small fw-semibold">Password Lama</label>
                            <div class="input-group">
                                <span class="input-group-text bg-light border-end-0">
                                    <i class="bi bi-lock text-muted"></i>
                                </span>
                                <input type="password" name="password_lama" id="password_lama"
                                       class="form-control border-start-0 ps-0"
                                       placeholder="Password saat ini" required>
                                <button class="btn btn-light border toggle-pass" type="button"
                                        data-target="password_lama">
                                    <i class="bi bi-eye text-muted"></i>
                                </button>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label class="form-label small fw-semibold">Password Baru</label>
                            <div class="input-group">
                                <span class="input-group-text bg-light border-end-0">
                                    <i class="bi bi-key text-muted"></i>
                                </span>
                                <input type="password" name="password_baru" id="password_baru"
                                       class="form-control border-start-0 ps-0"
                                       placeholder="Minimal 6 karakter" required minlength="6">
                                <button class="btn btn-light border toggle-pass" type="button"
                                        data-target="password_baru">
                                    <i class="bi bi-eye text-muted"></i>
                                </button>
                            </div>
                        </div>

                        <div class="mb-4">
                            <label class="form-label small fw-semibold">Konfirmasi Password Baru</label>
                            <div class="input-group">
                                <span class="input-group-text bg-light border-end-0">
                                    <i class="bi bi-key-fill text-muted"></i>
                                </span>
                                <input type="password" name="konfirmasi" id="konfirmasi"
                                       class="form-control border-start-0 ps-0"
                                       placeholder="Ulangi password baru" required>
                                <button class="btn btn-light border toggle-pass" type="button"
                                        data-target="konfirmasi">
                                    <i class="bi bi-eye text-muted"></i>
                                </button>
                            </div>
                            <div id="pass_match" class="small mt-1"></div>
                        </div>

                        <button type="submit" class="btn w-100 text-white fw-semibold"
                                style="background:linear-gradient(135deg,#ef4444,#dc2626);border-radius:8px;">
                            <i class="bi bi-shield-check me-1"></i>Ubah Password
                        </button>
                    </form>
                </div>
            </div>

        </div>

        <!-- ═══ KOLOM KANAN: Edit Profil ═══ -->
        <div class="col-lg-8">
            <div class="card border-0 shadow-sm" style="border-radius:14px; border-top:4px solid #14a897 !important;">
                <div class="card-header bg-white border-0 pt-4 px-4">
                    <h6 class="fw-bold mb-0">
                        <i class="bi bi-pencil-square me-2" style="color:#14a897"></i>Edit Informasi Profil
                    </h6>
                    <small class="text-muted">Data akan diperbarui di akun dan data warga</small>
                </div>
                <div class="card-body px-4 pb-4">
                    <form action="<?php echo base_url('profil/update_profil'); ?>" method="POST">
                        <input type="hidden"
                               name="<?php echo $this->security->get_csrf_token_name(); ?>"
                               value="<?php echo $this->security->get_csrf_hash(); ?>">

                        <!-- Informasi Akun -->
                        <div class="p-3 mb-4 rounded-3" style="background:#f4fcfb;">
                            <p class="small fw-bold text-uppercase mb-3" style="color:#14a897;letter-spacing:1px;">
                                <i class="bi bi-person me-1"></i>Informasi Akun
                            </p>
                            <div class="row g-3">
                                <div class="col-md-6">
                                    <label class="form-label small fw-semibold">
                                        Nama Lengkap <span class="text-danger">*</span>
                                    </label>
                                    <input type="text" name="nama_lengkap" class="form-control"
                                           value="<?php echo htmlspecialchars($user->nama_lengkap); ?>" required>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label small fw-semibold">Username <span class="text-danger">*</span></label>
                                    <div class="position-relative">
                                        <input type="text" name="username" id="usernameInput" class="form-control"
                                               value="<?php echo htmlspecialchars($user->username); ?>" required>
                                        <div id="usernameFeedback" class="position-absolute end-0 top-50 translate-middle-y pe-3"></div>
                                    </div>
                                    <small id="usernameHelp" class="text-muted">Hanya huruf dan angka, tanpa spasi</small>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label small fw-semibold">Email</label>
                                    <div class="input-group">
                                        <span class="input-group-text bg-light border-end-0">
                                            <i class="bi bi-envelope text-muted"></i>
                                        </span>
                                        <input type="email" name="email"
                                               class="form-control border-start-0 ps-0"
                                               value="<?php echo htmlspecialchars($user->email ?? ''); ?>"
                                               placeholder="email@contoh.com">
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label small fw-semibold">No HP / WhatsApp</label>
                                    <div class="input-group">
                                        <span class="input-group-text bg-light border-end-0">
                                            <i class="bi bi-telephone text-muted"></i>
                                        </span>
                                        <input type="text" name="no_hp"
                                               class="form-control border-start-0 ps-0"
                                               value="<?php echo htmlspecialchars($user->no_hp ?? ''); ?>"
                                               placeholder="08xxxxxxxxxx">
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Data Warga -->
                        <?php if($warga): ?>
                        <div class="p-3 mb-4 rounded-3" style="background:#f8f9fa;">
                            <p class="small fw-bold text-uppercase mb-3" style="color:#6b7280;letter-spacing:1px;">
                                <i class="bi bi-house me-1"></i>Data Kependudukan
                            </p>
                            <div class="row g-3">
                                <div class="col-md-6">
                                    <label class="form-label small fw-semibold">NIK</label>
                                    <input type="text" class="form-control bg-light"
                                           value="<?php echo htmlspecialchars($warga->nik ?? ''); ?>" disabled>
                                    <small class="text-muted">Hubungi admin untuk mengubah NIK</small>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label small fw-semibold">No. KK</label>
                                    <input type="text" class="form-control bg-light"
                                           value="<?php echo htmlspecialchars($warga->no_kk ?? ''); ?>" disabled>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label small fw-semibold">Tempat Lahir</label>
                                    <input type="text" name="tempat_lahir" class="form-control"
                                           value="<?php echo htmlspecialchars($warga->tempat_lahir ?? ''); ?>"
                                           placeholder="Kota lahir">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label small fw-semibold">Tanggal Lahir</label>
                                    <input type="date" name="tanggal_lahir" class="form-control"
                                           value="<?php echo $warga->tanggal_lahir ?? ''; ?>">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label small fw-semibold">Pekerjaan</label>
                                    <input type="text" name="pekerjaan" class="form-control"
                                           value="<?php echo htmlspecialchars($warga->pekerjaan ?? ''); ?>"
                                           placeholder="Pekerjaan saat ini">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label small fw-semibold">Agama</label>
                                    <select name="agama" class="form-select">
                                        <?php foreach(['Islam','Kristen','Katolik','Hindu','Buddha','Konghucu'] as $a): ?>
                                        <option value="<?php echo $a; ?>"
                                            <?php echo ($warga->agama ?? '') == $a ? 'selected' : ''; ?>>
                                            <?php echo $a; ?>
                                        </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label small fw-semibold">Jenis Kelamin</label>
                                    <input type="text" class="form-control bg-light"
                                           value="<?php echo ($warga->jenis_kelamin ?? '') == 'L' ? 'Laki-laki' : 'Perempuan'; ?>"
                                           disabled>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label small fw-semibold">Status Perkawinan</label>
                                    <input type="text" class="form-control bg-light"
                                           value="<?php echo ucfirst(str_replace('_', ' ', $warga->status_perkawinan ?? '')); ?>"
                                           disabled>
                                </div>
                                <div class="col-12">
                                    <label class="form-label small fw-semibold">Status Domisili</label>
                                    <input type="text" class="form-control bg-light"
                                           value="<?php echo ucfirst($warga->status_domisili ?? ''); ?>" disabled>
                                </div>
                            </div>
                        </div>
                        <?php else: ?>
                        <!-- Tidak ada data warga terhubung -->
                        <div class="p-3 mb-4 rounded-3 text-center" style="background:#fff8f0;border:1px dashed #f59e0b;">
                            <i class="bi bi-info-circle text-warning fs-4 mb-2 d-block"></i>
                            <p class="small text-muted mb-0">
                                Akun ini belum terhubung dengan data warga.<br>
                                Hubungi admin untuk menghubungkan data.
                            </p>
                        </div>
                        <?php endif; ?>

                        <div class="d-flex gap-2 justify-content-end">
                            <a href="<?php echo base_url('dashboard'); ?>"
                               class="btn btn-light border px-4" style="border-radius:8px;">
                                Batal
                            </a>
                            <button type="submit" class="btn px-4 text-white fw-semibold"
                                    style="background:linear-gradient(135deg,#14a897,#0e7b6e);border-radius:8px;">
                                <i class="bi bi-check-lg me-1"></i>Simpan Perubahan
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

    </div>
</div>
<!-- Modal Konfirmasi Hapus Foto Profil -->
<div class="modal fade" id="modalHapusFoto" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" style="max-width:360px;">
    <div class="modal-content" style="border-radius:16px;border:none;overflow:hidden;">
      <div class="modal-header" style="background:#fef2f2;border-bottom:1.5px solid #fecaca;padding:16px 20px;">
        <div class="d-flex align-items-center gap-2">
          <div style="width:34px;height:34px;background:#fee2e2;border-radius:9px;display:flex;align-items:center;justify-content:center;">
            <i class="bi bi-trash-fill" style="color:#dc2626;"></i>
          </div>
          <h6 class="modal-title mb-0 fw-bold" style="color:#991b1b;font-size:.92rem;">Hapus Foto Profil</h6>
        </div>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body" style="padding:18px 20px;">
        <p style="font-size:.84rem;color:#334155;margin-bottom:10px;">Anda akan menghapus foto profil. Foto akan diganti dengan avatar default.</p>
        <div style="background:#fffbeb;border:1.5px solid #fde68a;border-radius:8px;padding:8px 13px;font-size:.76rem;color:#92400e;">
          <i class="bi bi-exclamation-triangle-fill me-1"></i>Tindakan ini tidak dapat dibatalkan.
        </div>
      </div>
      <div class="modal-footer" style="border:none;padding:0 20px 16px;gap:8px;">
        <button type="button" class="btn" data-bs-dismiss="modal"
          style="border-radius:8px;border:1.5px solid #e5e7eb;font-size:.81rem;font-weight:600;color:#64748b;padding:7px 18px;flex:1;">
          <i class="bi bi-x-lg me-1"></i>Batal
        </button>
        <a href="<?php echo base_url('profil/hapus_foto'); ?>"
          style="border-radius:8px;border:none;font-size:.81rem;font-weight:700;color:#fff;padding:7px 18px;flex:1;background:linear-gradient(135deg,#dc2626,#ef4444);box-shadow:0 4px 12px rgba(220,38,38,.24);cursor:pointer;display:inline-flex;align-items:center;justify-content:center;gap:6px;text-decoration:none;">
          <i class="bi bi-trash-fill"></i>Ya, Hapus
        </a>
      </div>
    </div>
  </div>
</div>

<script>
var _bsModalHapusFoto = null;
function konfirmasiHapusFoto() {
  var modalEl = document.getElementById('modalHapusFoto');
  if(!modalEl) return;
  if(!_bsModalHapusFoto) _bsModalHapusFoto = new bootstrap.Modal(modalEl);
  _bsModalHapusFoto.show();
}
</script>

<script>
// ── Variabel foto awal ──
const _originalSrc = '<?php echo $has_foto ? base_url($foto_path) : ""; ?>';
const _hasFoto     = <?php echo $has_foto ? 'true' : 'false'; ?>;

// ── Preview foto sebelum upload ──
function previewFoto(input) {
    if (!input.files || !input.files[0]) return;

    const file = input.files[0];

    // Validasi ukuran maks 2MB
    if (file.size > 2 * 1024 * 1024) {
        alert('Ukuran file terlalu besar! Maksimal 2MB.');
        input.value = '';
        return;
    }

    // Validasi tipe file
    const allowed = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp'];
    if (!allowed.includes(file.type)) {
        alert('Format tidak didukung! Gunakan JPG, PNG, atau WEBP.');
        input.value = '';
        return;
    }

    const reader = new FileReader();
    reader.onload = function(e) {
        const wrap = document.getElementById('avatarWrap');
        wrap.innerHTML = '<img src="' + e.target.result + '" style="width:100%;height:100%;object-fit:cover;" alt="Preview">';

        // Tampilkan tombol simpan/batal
        const actions = document.getElementById('fotoActions');
        actions.classList.remove('d-none');
        actions.classList.add('d-flex');

        // Sembunyikan tombol hapus sementara
        const hapus = document.getElementById('hapusFotoWrap');
        if (hapus) hapus.classList.add('d-none');
    };
    reader.readAsDataURL(file);
}

// ── Batal preview, kembalikan foto asal ──
function batalFoto() {
    const wrap = document.getElementById('avatarWrap');
    if (_hasFoto) {
        wrap.innerHTML = '<img src="' + _originalSrc + '" style="width:100%;height:100%;object-fit:cover;" alt="Foto Profil">';
    } else {
        wrap.innerHTML = '<i class="bi bi-person-fill text-white" style="font-size:2.5rem;"></i>';
    }

    // Reset input file
    document.getElementById('inputFoto').value = '';

    // Sembunyikan tombol aksi
    const actions = document.getElementById('fotoActions');
    actions.classList.add('d-none');
    actions.classList.remove('d-flex');

    // Tampilkan kembali tombol hapus
    const hapus = document.getElementById('hapusFotoWrap');
    if (hapus) hapus.classList.remove('d-none');
}

// ── Toggle show/hide password ──
document.querySelectorAll('.toggle-pass').forEach(function(btn) {
    btn.addEventListener('click', function() {
        const name  = this.dataset.target;
        const input = document.querySelector('[name="' + name + '"]');
        const icon  = this.querySelector('i');
        if (input.type === 'password') {
            input.type = 'text';
            icon.className = 'bi bi-eye-slash text-muted';
        } else {
            input.type = 'password';
            icon.className = 'bi bi-eye text-muted';
        }
    });
});

// ── Cek password match realtime ──
document.getElementById('konfirmasi').addEventListener('input', function() {
    const baru = document.getElementById('password_baru').value;
    const el   = document.getElementById('pass_match');
    if (!this.value) { el.innerHTML = ''; return; }
    if (this.value === baru) {
        el.innerHTML = '<span class="text-success"><i class="bi bi-check-circle-fill me-1"></i>Password cocok</span>';
    } else {
        el.innerHTML = '<span class="text-danger"><i class="bi bi-x-circle-fill me-1"></i>Password tidak cocok</span>';
    }
});

// ── Cegah submit jika password tidak cocok ──
document.getElementById('formPassword').addEventListener('submit', function(e) {
    const baru    = document.getElementById('password_baru').value;
    const konfirm = document.getElementById('konfirmasi').value;
    if (baru !== konfirm) {
        e.preventDefault();
        alert('Konfirmasi password tidak cocok!');
    }
});

// ── Auto cek username ──
document.addEventListener('DOMContentLoaded', function() {
    let timeout = null;
    const originalUsername = '<?php echo addslashes($user->username); ?>';
    const usernameInput = document.getElementById('usernameInput');
    const formProfil = usernameInput.closest('form');
    const btnSubmitProfil = formProfil.querySelector('button[type="submit"]');
    const feedback = document.getElementById('usernameFeedback');
    const helpText = document.getElementById('usernameHelp');

    usernameInput.addEventListener('input', function() {
        let username = this.value;
        
        clearTimeout(timeout);
        
        if (username.length === 0) {
            feedback.innerHTML = '';
            helpText.innerHTML = 'Hanya huruf dan angka, tanpa spasi';
            helpText.className = 'small text-muted';
            this.classList.remove('is-invalid', 'is-valid');
            btnSubmitProfil.disabled = false;
            return;
        }

        if (username === originalUsername) {
            feedback.innerHTML = '';
            helpText.innerHTML = 'Username Anda saat ini';
            helpText.className = 'small text-success';
            this.classList.remove('is-invalid');
            this.classList.add('is-valid');
            btnSubmitProfil.disabled = false;
            return;
        }
        
        if (!/^[a-zA-Z0-9]+$/.test(username)) {
            feedback.innerHTML = '';
            helpText.innerHTML = 'Hanya huruf dan angka, tanpa spasi';
            helpText.className = 'small text-danger';
            this.classList.remove('is-valid');
            this.classList.add('is-invalid');
            btnSubmitProfil.disabled = true;
            return;
        }
        
        feedback.innerHTML = '<div class="spinner-border spinner-border-sm text-primary" role="status" style="width: 1rem; height: 1rem; border-width: 0.15em;"></div>';
        btnSubmitProfil.disabled = true;

        timeout = setTimeout(function() {
            const formData = new FormData();
            formData.append('username', username);
            formData.append('<?php echo $this->security->get_csrf_token_name(); ?>', '<?php echo $this->security->get_csrf_hash(); ?>');

            fetch('<?php echo base_url("profil/check_username"); ?>', {
                method: 'POST',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: formData
            })
            .then(response => response.json())
            .then(res => {
                if (res.status === 'available') {
                    feedback.innerHTML = '';
                    helpText.innerHTML = res.msg;
                    helpText.className = 'small text-success';
                    usernameInput.classList.remove('is-invalid');
                    usernameInput.classList.add('is-valid');
                    btnSubmitProfil.disabled = false;
                } else {
                    feedback.innerHTML = '';
                    helpText.innerHTML = res.msg;
                    helpText.className = 'small text-danger';
                    usernameInput.classList.remove('is-valid');
                    usernameInput.classList.add('is-invalid');
                    btnSubmitProfil.disabled = true;
                }
            })
            .catch(() => {
                feedback.innerHTML = '';
                helpText.innerHTML = 'Gagal mengecek username';
                helpText.className = 'small text-danger';
                usernameInput.classList.remove('is-valid');
                usernameInput.classList.add('is-invalid');
            });
        }, 600);
    });
});
</script>