<?php include_once __DIR__ . '/../layouts/head.php'; ?>
<div class="container py-4" style="max-width: 1350px; width: 100%;">
  <div class="row">
    <div class="col-lg-12">
      <div class="shadow-sm bg-white rounded overflow-hidden border">
        <div class="p-0">
          <div class="row px-0 m-0">

            <?php include_once __DIR__ . '/../layouts/menu_body.php'; ?>

            <div class="col-12 col-md-9 px-0">
              <div class="tab-content" id="v-pills-tabContent">

                <!-- Konten Utama -->
                <div class="tab-pane fade show active" id="v-pills-home" role="tabpanel">
                  <div class="p-4">
                    
                    <div class="mb-4">
                      <h5 class="mb-0 fw-bold">Daftar Data Mahasiswa Baru</h5>
                    </div>

                    <!-- Form Pencarian dan Filter Tahun Masuk -->
                    <form method="GET" class="mb-4">
                      <div class="row">
                        <div class="col-md-6 mb-3 mb-md-0">
                          <label for="search" class="form-label">Cari Mahasiswa</label>
                          <input type="text" id="search" name="search" class="form-control" placeholder="Nama atau NISN" value="<?= htmlspecialchars($search ?? '') ?>">
                        </div>
                        <div class="col-md-2 d-flex align-items-end">
                          <button type="submit" class="btn btn-primary w-100">Filter</button>
                        </div>
                      </div>
                    </form>

                    <!-- Tombol Clear dan Download -->
                    <div class="d-flex align-items-center mb-4 gap-2">
                      
                      <!-- Tombol Clear -->
                      <form method="GET" action="/dashboard/pegawai-data-maba" class="m-0">
                        <button type="submit" class="btn btn-warning">Clear</button>
                      </form>
                    
                      <!-- Form Download -->
                      <form method="GET" action="/dashboard/pegawai-download-maba" class="d-flex align-items-center gap-2 m-0">
                        <input type="text" name="tahun_masuk" class="form-control" placeholder="Tahun Angkatan" style="max-width: 200px;" required>
                        <button type="submit" class="btn btn-info">Download Data</button>
                      </form>
                    
                    </div>

                    <!-- Tabel Data Mahasiswa -->
                    <div class="table-responsive">
                        <table class="table table-striped">
                          <thead>
                            <tr>
                              <th>No</th>
                              <th>Nama</th>
                              <th>NISN</th>
                              <th>Aksi</th>
                            </tr>
                          </thead>
                          <tbody>
                            <?php if (!empty($data)): ?>
                              <?php foreach ($data as $index => $row): ?>
                                <tr class="<?= (($row['status_check'] ?? '') === 'Check') ? 'table-checked' : '' ?>">
                                    <td><?= $offset + $index + 1 ?></td>
                                    <td><?= htmlspecialchars($row['nama']) ?></td>
                                    <td><?= htmlspecialchars($row['nisn']) ?></td>
                                    <td>
                                      <button 
                                        class="btn btn-sm <?= (($row['status_check'] ?? '') === 'Check') ? 'btn-info' : 'btn-warning' ?> btn-update"
                                        data-nim="<?= htmlspecialchars($row['nim']) ?>"
                                      >
                                        <?php if (($row['status_check'] ?? '') === 'Check'): ?>
                                          <i class="bi bi-check2-all"></i>
                                        <?php else: ?>
                                          <i class="bi bi-check2"></i>
                                        <?php endif; ?>
                                      </button>
                                    </td>
                                </tr>
                              <?php endforeach; ?>
                            <?php else: ?>
                              <tr>
                                <td colspan="4" class="text-center">Tidak ada data</td>
                              </tr>
                            <?php endif; ?>
                          </tbody>
                        </table>
                        
<!-- Modal Update -->
<div class="modal fade" id="updateModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-xl modal-dialog-scrollable">
    <div class="modal-content">
      <form id="updateForm">

        <!-- Header dengan tombol Simpan (sticky) -->
        <div class="modal-header d-flex justify-content-between align-items-center"
             style="position: sticky; top: 0; z-index: 1055; background: white;">
          <h5 class="modal-title">Update Data Mahasiswa</h5>
          <div class="d-flex gap-2">
            <button type="submit" class="btn btn-primary">Simpan Perubahan</button>
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Tutup</button>
          </div>
        </div>

        <!-- Body -->
        <div class="modal-body" style="max-height: calc(100vh - 200px); overflow-y: auto;">
          <!-- Nav Tabs -->
          <ul class="nav nav-tabs mb-3" id="updateTab" role="tablist">
            <li class="nav-item" role="presentation">
              <button class="nav-link active" id="biodata-tab"
                data-bs-toggle="tab" data-bs-target="#tabBiodata" type="button" role="tab">
                Biodata
              </button>
            </li>
            <li class="nav-item" role="presentation">
              <button class="nav-link" id="ortu-tab"
                data-bs-toggle="tab" data-bs-target="#tabOrtu" type="button" role="tab">
                Orang Tua / Wali
              </button>
            </li>
            <li class="nav-item" role="presentation">
              <button class="nav-link" id="biaya-tab"
                data-bs-toggle="tab" data-bs-target="#tabBiaya" type="button" role="tab">
                Pembiayaan
              </button>
            </li>
          </ul>

          <!-- Tab Content -->
          <div class="tab-content">
            <!-- Biodata -->
            <div class="tab-pane fade show active" id="tabBiodata" role="tabpanel">
              <div class="row g-3">
                <div class="col-12 col-md-6" id="biodataLeft"></div>
                <div class="col-12 col-md-6" id="biodataRight"></div>
              </div>
            </div>

            <!-- Orang Tua / Wali -->
            <div class="tab-pane fade" id="tabOrtu" role="tabpanel">
              <div class="row g-3">
                <div class="col-12 col-md-6" id="ortuLeft"></div>
                <div class="col-12 col-md-6" id="ortuRight"></div>
              </div>
              <hr>
              <div class="row g-3" id="waliRow"></div>
            </div>

            <!-- Pembiayaan -->
            <div class="tab-pane fade" id="tabBiaya" role="tabpanel">
              <div class="row g-3">
                <div class="col-12 col-md-6" id="asalLeft"></div>
                <div class="col-12 col-md-6" id="asalRight"></div>
              </div>
            </div>
          </div>
        </div>

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

<!-- Script Bootstrap Tab Fix -->
<script>
document.getElementById('updateModal').addEventListener('shown.bs.modal', function () {
  let firstTab = document.querySelector('#updateTab button[data-bs-target="#tabBiodata"]');
  if (firstTab) {
    let tab = new bootstrap.Tab(firstTab);
    tab.show();
  }
});
</script>

<script>
document.addEventListener("DOMContentLoaded", function () {
  const updateModal = new bootstrap.Modal(document.getElementById('updateModal'));
  const updateForm = document.getElementById('updateForm');
  let currentNim = null;

  const labelMap = {
    // --- Biodata ---
    nama: "Nama Lengkap", nik: "NIK", nisn: "NISN",
    jenis_kelamin: "Jenis Kelamin", tmpt_lahir: "Tempat Lahir", tgl_lahir: "Tanggal Lahir",
    agama: "Agama", tahun_masuk: "Tahun Masuk", jalur_pendaftaran: "Jalur Pendaftaran",
    npwp: "NPWP", kewarganegaraan: "Kewarganegaraan", jenis_pendaftaran: "Jenis Pendaftaran",
    tgl_masuk_kuliah: "Tanggal Masuk Kuliah", mulai_semester: "Mulai Semester",
    jalan: "Jalan", rt: "RT", rw: "RW", nama_dusun: "Dusun", kelurahan: "Kelurahan",
    kecamatan: "Kecamatan", kode_pos: "Kode Pos", jenis_tinggal: "Jenis Tinggal",
    alat_transportasi: "Alat Transportasi", telp_rumah: "Telepon Rumah",
    no_hp: "Nomor HP", email: "Email", terima_kps: "Penerima KPS", no_kps: "Nomor KPS",

    // --- Orang Tua ---
    nama_ayah: "Nama Ayah", nik_ayah: "NIK Ayah", tgl_lahir_ayah: "Tanggal Lahir Ayah",
    pendidikan_ayah: "Pendidikan Ayah", pekerjaan_ayah: "Pekerjaan Ayah", penghasilan_ayah: "Penghasilan Ayah",
    nama_ibu: "Nama Ibu", nik_ibu: "NIK Ibu", tgl_lahir_ibu: "Tanggal Lahir Ibu",
    pendidikan_ibu: "Pendidikan Ibu", pekerjaan_ibu: "Pekerjaan Ibu", penghasilan_ibu: "Penghasilan Ibu",

    // --- Wali ---
    nama_wali: "Nama Wali", tgl_lahir_wali: "Tanggal Lahir Wali",
    pendidikan_wali: "Pendidikan Wali", pekerjaan_wali: "Pekerjaan Wali", penghasilan_wali: "Penghasilan Wali",

    // --- Biaya ---
    jenis_pembiayaan: "Jenis Pembiayaan", jumlah_biaya_masuk: "Jumlah Biaya Masuk"
  };

  // === Options map (semua dropdown) ===
  const optionsMap = {
    jenis_kelamin: { L: "Laki-laki", P: "Perempuan" },
    agama: {
      1: "Islam", 2: "Kristen", 3: "Katholik", 4: "Hindu", 5: "Budha", 6: "Konghuchu", 99: "Lainnya"
    },
    jalur_pendaftaran: {
      3: "PMDK", 4: "Prestasi", 9: "Program Internasional",
      11: "Kerjasama", 12: "Seleksi Mandiri", 13: "Ujian Bersama",
      14: "SNBT", 15: "SNBP"
    },
    jenis_pendaftaran: {
      1: "Peserta didik baru", 2: "Pindahan", 13: "RPL SKS", 14: "Non Gelar",
      15: "Fast Track", 16: "RPL Transfer"
    },
    jenis_tinggal: {
      1: "Bersama orang tua", 2: "Wali", 3: "Kost", 4: "Asrama", 5: "Panti asuhan", 99: "Lainnya"
    },
    alat_transportasi: {
      1: "Jalan kaki", 3: "Angkutan umum", 4: "Mobil jemputan", 5: "Kereta api",
      6: "Ojek", 7: "Becak/Delman", 8: "Perahu", 11: "Kuda", 12: "Sepeda",
      13: "Sepeda motor", 14: "Mobil pribadi", 99: "Lainnya"
    },
    terima_kps: { 1: "Ya", 0: "Tidak" },
    pendidikan_ayah: {
      0: "Tidak sekolah", 4: "SD", 5: "SMP", 6: "SMA", 20: "D1", 21: "D2",
      22: "D3", 23: "D4", 30: "S1", 35: "S2", 40: "S3", 99: "Lainnya"
    },
    pendidikan_ibu: {
      0: "Tidak sekolah", 4: "SD", 5: "SMP", 6: "SMA", 20: "D1", 21: "D2",
      22: "D3", 23: "D4", 30: "S1", 35: "S2", 40: "S3", 99: "Lainnya"
    },
    pendidikan_wali: {
      0: "Tidak sekolah", 4: "SD", 5: "SMP", 6: "SMA", 20: "D1", 21: "D2",
      22: "D3", 23: "D4", 30: "S1", 35: "S2", 40: "S3", 99: "Lainnya"
    },
    pekerjaan_ayah: {
      1: "Tidak bekerja", 3: "Petani", 5: "PNS/TNI/Polri", 6: "Karyawan Swasta",
      7: "Pedagang Kecil", 9: "Wiraswasta", 10: "Wirausaha", 11: "Buruh", 98: "Meninggal", 99: "Lainnya"
    },
    pekerjaan_ibu: {
      1: "Tidak bekerja", 3: "Petani", 5: "PNS/TNI/Polri", 6: "Karyawan Swasta",
      7: "Pedagang Kecil", 9: "Wiraswasta", 10: "Wirausaha", 11: "Buruh", 98: "Meninggal", 99: "Lainnya"
    },
    pekerjaan_wali: {
      1: "Tidak bekerja", 3: "Petani", 5: "PNS/TNI/Polri", 6: "Karyawan Swasta",
      7: "Pedagang Kecil", 9: "Wiraswasta", 10: "Wirausaha", 11: "Buruh", 98: "Meninggal", 99: "Lainnya"
    },
    penghasilan_ayah: {
      0: "", 11: "< Rp. 500rb", 12: "Rp. 500rb - 1jt",
      13: "Rp. 1jt - 2jt", 14: "Rp. 2jt - 5jt",
      15: "Rp. 5jt - 20jt", 16: "> Rp. 20jt"
    },
    penghasilan_ibu: {
      0: "", 11: "< Rp. 500rb", 12: "Rp. 500rb - 1jt",
      13: "Rp. 1jt - 2jt", 14: "Rp. 2jt - 5jt",
      15: "Rp. 5jt - 20jt", 16: "> Rp. 20jt"
    },
    penghasilan_wali: {
      0: "", 11: "< Rp. 500rb", 12: "Rp. 500rb - 1jt",
      13: "Rp. 1jt - 2jt", 14: "Rp. 2jt - 5jt",
      15: "Rp. 5jt - 20jt", 16: "> Rp. 20jt"
    },
    jenis_pembiayaan: { 1: "Mandiri", 2: "Beasiswa Tidak Penuh", 3: "Beasiswa Penuh" }
  };

  const biodataFields = [
    "nama","nik","nisn","tahun_masuk","jalur_pendaftaran","npwp","kewarganegaraan",
    "jenis_pendaftaran","tgl_masuk_kuliah","mulai_semester","jalan","rt","rw","nama_dusun",
    "jenis_kelamin","tmpt_lahir","tgl_lahir","agama",
    "kelurahan","kecamatan","kode_pos","jenis_tinggal","alat_transportasi",
    "telp_rumah","no_hp","email","terima_kps","no_kps"
  ];
  const ortuAyahFields = ["nama_ayah","nik_ayah","tgl_lahir_ayah","pendidikan_ayah","pekerjaan_ayah","penghasilan_ayah"];
  const ortuIbuFields  = ["nama_ibu","nik_ibu","tgl_lahir_ibu","pendidikan_ibu","pekerjaan_ibu","penghasilan_ibu"];
  const waliFields     = ["nama_wali","tgl_lahir_wali","pendidikan_wali","pekerjaan_wali","penghasilan_wali"];
  const biayaFields    = ["jenis_pembiayaan","jumlah_biaya_masuk"];

  function renderFields(container, keys, data) {
    container.innerHTML = keys.map(k => fieldHtml(k, data[k])).join("");
  }
  function renderSplit(containerLeft, containerRight, keys, data) {
    const total = keys.length;
    const leftCount = Math.ceil(total/2);
    containerLeft.innerHTML = keys.slice(0,leftCount).map(k => fieldHtml(k, data[k])).join("");
    containerRight.innerHTML= keys.slice(leftCount).map(k => fieldHtml(k, data[k])).join("");
  }

  function initKecamatanSearch() {
    const input = document.getElementById("kecamatan_input");
    const hidden = document.getElementById("kecamatan_hidden");
    const suggestions = document.getElementById("suggestions");
    if (!input) return;

    input.addEventListener("keyup", function() {
      const q = this.value;
      if (q.length < 2) {
        suggestions.innerHTML = "";
        return;
      }
      fetch("/dashboard/maba-search-kecamatan?q=" + encodeURIComponent(q))
        .then(res => res.json())
        .then(data => {
          suggestions.innerHTML = "";
          data.forEach(item => {
            const div = document.createElement("div");
            div.classList.add("list-group-item","list-group-item-action");
            div.textContent = item.kecamatan + " - " + item.kabupaten;
            div.addEventListener("click", function() {
              input.value = item.kecamatan + " - " + item.kabupaten;
              hidden.value = item.id_wil;
              suggestions.innerHTML = "";
            });
            suggestions.appendChild(div);
          });
        });
    });
  }

  function fieldHtml(key, value) {
    if (key === "kecamatan") {
      let displayText = "";
    
      if (value) {
        fetch("/dashboard/maba-get-kecamatan?id=" + value)
          .then(res => res.json())
          .then(item => {
            if (item && item.kecamatan) {
              document.getElementById("kecamatan_input").value = item.kecamatan + " - " + item.kabupaten;
            }
          });
      }
    
      return `
        <div class="mb-3 position-relative">
          <label class="form-label">${labelMap[key] ?? key}</label>
          <input type="text" id="kecamatan_input" class="form-control" 
            value="${displayText}" autocomplete="off">
          <input type="hidden" name="kecamatan" id="kecamatan_hidden" value="${value ?? ""}">
          <div id="suggestions" class="list-group position-absolute w-100" style="z-index:1056;"></div>
          <small class="text-muted" style="font-size:0.65rem">
            Ketik minimal 2 huruf, pilih kecamatan dari daftar. Yang tersimpan adalah kode wilayah.
          </small>
        </div>`;
    }

    if (optionsMap[key]) {
      let optionsHtml = `<option value="">-- Pilih --</option>`;
      Object.entries(optionsMap[key]).forEach(([val,text])=>{
        optionsHtml += `<option value="${val}" ${value==val?"selected":""}>${text}</option>`;
      });
      return `
        <div class="mb-3">
          <label class="form-label">${labelMap[key] ?? key}</label>
          <select name="${key}" class="form-control">${optionsHtml}</select>
        </div>`;
    }

    if (key==="jalan") {
      return `<div class="mb-3">
        <label class="form-label">${labelMap[key]}</label>
        <textarea class="form-control" name="${key}">${value??""}</textarea>
      </div>`;
    }

    let type="text";
    if (key.includes("tgl")) type="date";
    if (key==="email") type="email";
    if (["nik","nisn","rt","rw","kode_pos","telp_rumah","no_hp","npwp","no_kps","jumlah_biaya_masuk"].includes(key)) type="number";

    return `<div class="mb-3">
      <label class="form-label">${labelMap[key] ?? key}</label>
      <input type="${type}" name="${key}" value="${value??""}" class="form-control">
    </div>`;
  }

  // === tombol update ===
  document.querySelectorAll(".btn-update").forEach(btn=>{
    btn.addEventListener("click", function(){
      currentNim=this.dataset.nim;
      fetch(`/dashboard/pegawai-maba-detail?nim=${currentNim}`)
        .then(res=>res.json())
        .then(data=>{
          renderSplit(document.getElementById("biodataLeft"),document.getElementById("biodataRight"),biodataFields,data);
          renderFields(document.getElementById("ortuLeft"),ortuAyahFields,data);
          renderFields(document.getElementById("ortuRight"),ortuIbuFields,data);
          renderFields(document.getElementById("waliRow"),waliFields,data);
          renderSplit(document.getElementById("asalLeft"),document.getElementById("asalRight"),biayaFields,data);
          initKecamatanSearch();
          updateModal.show();
        });
    });
  });

  // === submit form ===
  updateForm.addEventListener("submit", function(e){
    e.preventDefault();
    const formData = new FormData(updateForm);
    formData.append("nim", currentNim);
    fetch("/dashboard/pegawai-maba-check",{method:"POST",body:formData})
      .then(res=>res.json())
      .then(resp=>{
        if(resp.success){ location.reload(); }
        else{ alert("Gagal update: "+resp.message); }
      });
  });
});
</script>



<style>
.table-checked {
  background-color: #28a745 !important; /* hijau solid */
  color: #fff !important;
}
</style>
              
                    </div>

					<!-- Paging Controls -->
					<?php if ($totalPages > 1): ?>
					  <div class="d-flex justify-content-end">
						<nav aria-label="Page navigation">
						  <ul class="pagination">

							<!-- First -->
							<li class="page-item <?= ($page <= 1) ? 'disabled' : '' ?>">
							  <a class="page-link" href="/dashboard/pegawai-data-maba?page=1&tahun_masuk=<?= urlencode($tahun_masuk ?? '') ?>&search=<?= urlencode($search ?? '') ?>"><<</a>
							</li>

							<!-- Previous -->
							<li class="page-item <?= ($page <= 1) ? 'disabled' : '' ?>">
							  <a class="page-link" href="/dashboard/pegawai-data-maba?page=<?= $page - 1 ?>&tahun_masuk=<?= urlencode($tahun_masuk ?? '') ?>&search=<?= urlencode($search ?? '') ?>"><</a>
							</li>

							<?php
							  $visiblePages = 5;
							  $startPage = max(1, $page - floor($visiblePages / 2));
							  $endPage = min($totalPages, $startPage + $visiblePages - 1);

							  if ($endPage - $startPage < $visiblePages - 1) {
								  $startPage = max(1, $endPage - $visiblePages + 1);
							  }
							?>

							<?php for ($i = $startPage; $i <= $endPage; $i++): ?>
							  <li class="page-item <?= ($i == $page) ? 'active' : '' ?>">
								<a class="page-link" href="/dashboard/pegawai-data-maba?page=<?= $i ?>&tahun_masuk=<?= urlencode($tahun_masuk ?? '') ?>&search=<?= urlencode($search ?? '') ?>"><?= $i ?></a>
							  </li>
							<?php endfor; ?>

							<!-- Next -->
							<li class="page-item <?= ($page >= $totalPages) ? 'disabled' : '' ?>">
							  <a class="page-link" href="/dashboard/pegawai-data-maba?page=<?= $page + 1 ?>&tahun_masuk=<?= urlencode($tahun_masuk ?? '') ?>&search=<?= urlencode($search ?? '') ?>">></a>
							</li>

							<!-- Last -->
							<li class="page-item <?= ($page >= $totalPages) ? 'disabled' : '' ?>">
							  <a class="page-link" href="/dashboard/pegawai-data-maba?page=<?= $totalPages ?>&tahun_masuk=<?= urlencode($tahun_masuk ?? '') ?>&search=<?= urlencode($search ?? '') ?>">>></a>
							</li>

						  </ul>
						</nav>
					  </div>
					<?php endif; ?>


                  </div>
                </div>

              </div>
            </div>

          </div>
        </div>
      </div>
    </div>
  </div>
</div>
<?php include_once __DIR__ . '/../layouts/footer.php'; ?>
