<?php
require_once __DIR__ . '/../includes/header_admin.php';
require_once __DIR__ . '/../config/db.php';

/* =========================
   REQUEST / CONTEXT
========================= */
$action = $_GET['action'] ?? '';
$edit   = null;

/* =========================
   LOAD DATA FOR EDIT
========================= */
if ($action === 'edit' && isset($_GET['id'])) {
    $stmt = $pdo->prepare("SELECT * FROM siswa WHERE id = :id LIMIT 1");
    $stmt->execute([':id' => (int)$_GET['id']]);
    $edit = $stmt->fetch();
}

/* =========================
   FILTERING / SEARCH / PAGINATION
========================= */
$search      = trim($_GET['search'] ?? '');
$kelas_combo = trim($_GET['kelas_combo'] ?? '');

$per_page_options = [10,25,50];
$per_page = (isset($_GET['per_page']) && in_array((int)$_GET['per_page'], $per_page_options))
            ? (int)$_GET['per_page'] : 10;

$page   = (isset($_GET['page']) && (int)$_GET['page'] > 0) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $per_page;

$where  = " WHERE 1 ";
$params = [];

if ($search !== '') {
    $where .= " AND (nama LIKE :src OR nis LIKE :src OR kelas LIKE :src OR jurusan LIKE :src OR rombel LIKE :src)";
    $params[':src'] = "%$search%";
}

if ($kelas_combo !== '') {
    $parts = explode('-', $kelas_combo);
    if (count($parts) === 3) {
        $where .= " AND kelas = :kls AND jurusan = :jrs AND rombel = :rmbl";
        $params[':kls']  = $parts[0];
        $params[':jrs']  = $parts[1];
        $params[':rmbl'] = $parts[2];
    }
}

/* COUNT */
$stmt = $pdo->prepare("SELECT COUNT(*) FROM siswa $where");
$stmt->execute($params);
$total = (int)$stmt->fetchColumn();
$total_pages = max(1, (int)ceil($total / $per_page));

/* FETCH ROWS */
$sql = "SELECT id, nis, nama, kelas, jurusan, rombel, foto, uid
        FROM siswa
        $where
        ORDER BY nama
        LIMIT :limit OFFSET :offset";

$stmt = $pdo->prepare($sql);
foreach ($params as $k => $v) $stmt->bindValue($k, $v);
$stmt->bindValue(':limit',  (int)$per_page, PDO::PARAM_INT);
$stmt->bindValue(':offset', (int)$offset, PDO::PARAM_INT);
$stmt->execute();
$rows = $stmt->fetchAll();

/* CREATE CLASS COMBO DROPDOWN */
$comboStmt = $pdo->query("
    SELECT DISTINCT kelas, jurusan, rombel
    FROM siswa
    ORDER BY kelas, jurusan, rombel
");
$combos = $comboStmt->fetchAll();

/* HELPERS */
function qs_keep($overrides = []) {
    return http_build_query(array_merge($_GET, $overrides));
}

function friendly_msg($code) {
    $map = [
        'import_ok' => 'Import berhasil.',
        'added'     => 'Siswa berhasil ditambahkan.',
        'updated'   => 'Perubahan siswa disimpan.',
    ];
    return $map[$code] ?? $code;
}

?>

<!-- ALERTS -->
<?php if (!empty($_GET['msg'])): ?>
<div class="alert alert-success alert-dismissible fade show" role="alert">
  <strong>Sukses:</strong> <?= htmlspecialchars(friendly_msg($_GET['msg'])) ?>
  <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<?php if (!empty($_GET['err'])): ?>
<div class="alert alert-danger alert-dismissible fade show" role="alert">
  <strong>Error:</strong> <?= htmlspecialchars($_GET['err']) ?>
  <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<!-- ============================
     CARD WRAPPER
============================ -->
<div class="card shadow-sm mb-4">

  <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
    <strong>Daftar Siswa</strong>

    <div class="d-flex gap-2">
      <button class="btn btn-light btn-sm" data-bs-toggle="modal" data-bs-target="#modalAddSiswa">+ Tambah</button>
      <button class="btn btn-success btn-sm" data-bs-toggle="modal" data-bs-target="#modalImport">Import</button>
    </div>
  </div>

  <div class="card-body p-3">
    <form method="GET" class="row g-2 align-items-end">

      <div class="col-md-4">
        <input name="search" class="form-control" value="<?= htmlspecialchars($search) ?>" placeholder="Cari nama / NIS / jurusan">
      </div>

      <div class="col-md-4">
        <select name="kelas_combo" class="form-select">
          <option value="">Semua Kelas</option>
          <?php foreach ($combos as $c): 
            $val = $c['kelas'].'-'.$c['jurusan'].'-'.$c['rombel'];
            $sel = ($val === $kelas_combo) ? 'selected' : '';
          ?>
            <option value="<?= htmlspecialchars($val) ?>" <?= $sel ?>>
              <?= htmlspecialchars($c['kelas'].' '.$c['jurusan'].' - '.$c['rombel']) ?>
            </option>
          <?php endforeach; ?>
        </select>
      </div>

      <div class="col-md-2">
        <select name="per_page" class="form-select">
          <?php foreach ($per_page_options as $opt): ?>
            <option value="<?= $opt ?>" <?= $per_page == $opt ? 'selected' : '' ?>><?= $opt ?></option>
          <?php endforeach; ?>
        </select>
      </div>

      <div class="col-md-2 d-grid">
        <button class="btn btn-primary">Terapkan</button>
      </div>

    </form>
  </div>

  <div class="px-3 pb-2">
    <button id="btnBulkDelete" class="btn btn-danger btn-sm d-none">
      <i class="bi bi-trash"></i> Hapus Terpilih
    </button>
  </div>

  <!-- =========================================
       TABLE
  ========================================== -->
  <div class="table-responsive px-3 pb-3">

    <table class="table table-hover table-striped align-middle mb-0"
           style="background:#fff;border-radius:10px;overflow:hidden;">

      <thead class="table-light">
        <tr>
          <th style="width:50px;"><input type="checkbox" id="checkAll"></th>
          <th style="width:60px;">No</th>
          <th>NIS</th>
          <th>Nama</th>
          <th>Kelas</th>

          <!-- 🔥 Kolom Baru — Status UID -->
          <th style="width:80px;">UID</th>

          <th style="width:180px;">Aksi</th>
        </tr>
      </thead>

      <tbody>
        <?php $no = $offset + 1; foreach ($rows as $r): ?>
        <tr>
          <td class="text-center">
            <input type="checkbox" class="row-check" value="<?= (int)$r['id'] ?>">
          </td>

          <td><?= $no++ ?></td>
          <td><?= htmlspecialchars($r['nis']) ?></td>
          <td><?= htmlspecialchars($r['nama']) ?></td>

          <td><?= htmlspecialchars($r['kelas'].' '.$r['jurusan'].' - '.$r['rombel']) ?></td>

          <!-- 🔥 Kolom Check UID -->
          <td class="text-center">
            <?php if (!empty($r['uid'])): ?>
              <span class="badge bg-success rounded-circle" style="font-size:14px;padding:8px;">
                <i class="bi bi-check-lg"></i>
              </span>
            <?php endif; ?>
          </td>

          <td class="text-center">

            <?php if (!empty($r['foto'])): ?>
            <button class="btn btn-info btn-sm btn-foto me-1"
                    data-foto="/presensi_v1/upload/siswa/<?= htmlspecialchars($r['foto']) ?>">
              <i class="bi bi-eye"></i>
            </button>
            <?php endif; ?>

            <button class="btn btn-primary btn-sm btn-edit me-1"
                data-id="<?= (int)$r['id'] ?>"
                data-nis="<?= htmlspecialchars($r['nis']) ?>"
                data-nama="<?= htmlspecialchars($r['nama']) ?>"
                data-kelas="<?= htmlspecialchars($r['kelas']) ?>"
                data-jurusan="<?= htmlspecialchars($r['jurusan']) ?>"
                data-rombel="<?= htmlspecialchars($r['rombel']) ?>"
                data-foto="<?= htmlspecialchars($r['foto']) ?>">
                Edit
            </button>

            <button class="btn btn-danger btn-sm btn-delete" data-id="<?= (int)$r['id'] ?>">
              <i class="bi bi-trash"></i>
            </button>
          </td>
        </tr>
        <?php endforeach; ?>

        <?php if (empty($rows)): ?>
        <tr>
          <td colspan="7" class="text-center text-muted">Tidak ada data</td>
        </tr>
        <?php endif; ?>

      </tbody>
    </table>

  </div>

  <!-- PAGINATION -->
  <div class="p-3">
    <ul class="pagination mb-0">
      <?php for ($p = 1; $p <= $total_pages; $p++): ?>
        <li class="page-item <?= $p == $page ? 'active' : '' ?>">
          <a class="page-link" href="?<?= qs_keep(['page'=>$p]) ?>"><?= $p ?></a>
        </li>
      <?php endfor; ?>
    </ul>
  </div>

</div> <!-- card end -->


<!-- =========================
     MODALS (ADD / EDIT / FOTO / IMPORT)
========================= -->
<!-- ADD SISWA -->
<div class="modal fade" id="modalAddSiswa" tabindex="-1">
  <div class="modal-dialog modal-lg modal-dialog-centered">
    <div class="modal-content p-3">
      <form action="/presensi_v1/process/siswa_save.php" method="post" enctype="multipart/form-data">
        <h5>Tambah Siswa</h5>

        <div class="mb-3">
          <label>NIS</label>
          <input name="nis" class="form-control" placeholder="NIS">
        </div>

        <div class="mb-3">
          <label>Nama</label>
          <input name="nama" class="form-control" required placeholder="Nama Lengkap">
        </div>

        <div class="row">
          <div class="col-md-4 mb-3">
            <label>Kelas</label>
            <select name="kelas" class="form-select" required>
              <option>X</option><option>XI</option><option>XII</option>
            </select>
          </div>

          <div class="col-md-4 mb-3">
            <label>Jurusan</label>
            <select name="jurusan" class="form-select" required>
              <option>TKJ</option><option>TITL</option><option>TP</option>
              <option>TKR</option><option>TKP</option><option>DPIB</option>
            </select>
          </div>

          <div class="col-md-4 mb-3">
            <label>Rombel</label>
            <select name="rombel" class="form-select" required>
              <option>1</option><option>2</option><option>3</option><option>4</option>
            </select>
          </div>
        </div>

        <div class="mb-3">
          <label>Foto (opsional, max 1MB)</label>
          <input type="file" name="foto" accept="image/*" class="form-control">
        </div>

        <div class="d-flex justify-content-end">
          <button type="button" class="btn btn-secondary me-2" data-bs-dismiss="modal">Batal</button>
          <button class="btn btn-primary">Simpan</button>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- EDIT SISWA -->
<div class="modal fade" id="modalEditSiswa" tabindex="-1">
  <div class="modal-dialog modal-lg modal-dialog-centered">
    <div class="modal-content p-3">
      <form action="/presensi_v1/process/siswa_save.php" method="post" enctype="multipart/form-data">
        <h5>Edit Siswa</h5>
        <input type="hidden" name="id" id="edit-id">

        <div class="mb-3">
          <label>NIS</label>
          <input name="nis" id="edit-nis" class="form-control" placeholder="NIS">
        </div>

        <div class="mb-3">
          <label>Nama</label>
          <input name="nama" id="edit-nama" class="form-control" required placeholder="Nama Lengkap">
        </div>

        <div class="row">
          <div class="col-md-4 mb-3">
            <label>Kelas</label>
            <select name="kelas" id="edit-kelas" class="form-select" required>
              <option>X</option><option>XI</option><option>XII</option>
            </select>
          </div>

          <div class="col-md-4 mb-3">
            <label>Jurusan</label>
            <select name="jurusan" id="edit-jurusan" class="form-select" required>
              <option>TKJ</option><option>TITL</option><option>TP</option>
              <option>TKR</option><option>TKP</option><option>DPIB</option>
            </select>
          </div>

          <div class="col-md-4 mb-3">
            <label>Rombel</label>
            <select name="rombel" id="edit-rombel" class="form-select" required>
              <option>1</option><option>2</option><option>3</option><option>4</option>
            </select>
          </div>
        </div>

        <div class="mb-3">
          <label>Foto (opsional, max 1MB)</label>
          <input type="file" name="foto" accept="image/*" class="form-control">
          <div id="edit-foto-preview" class="mt-2" style="display:none;">
            <img id="edit-foto-img" src="" style="max-width:120px;border-radius:8px;">
            <p class="small text-muted mb-0">(Upload foto baru akan mengganti foto lama)</p>
          </div>
        </div>

        <div class="d-flex justify-content-end">
          <button type="button" class="btn btn-secondary me-2" data-bs-dismiss="modal">Batal</button>
          <button class="btn btn-primary">Simpan Perubahan</button>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- IMPORT -->
<div class="modal fade" id="modalImport" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content p-3">
      <h5>Import Siswa (.xlsx)</h5>
      <p class="small text-muted">Format: <b>NIS | Nama | Kelas | Jurusan | Rombel</b>. Header boleh ada.</p>

      <form action="/presensi_v1/process/siswa_import.php" method="post" enctype="multipart/form-data">
        <div class="mb-2">
          <input type="file" name="xlsx" accept=".xlsx,.xls" class="form-control" required>
        </div>

        <div class="d-flex justify-content-end">
          <button type="button" class="btn btn-secondary me-2" data-bs-dismiss="modal">Batal</button>
          <button class="btn btn-primary">Upload & Import</button>
        </div>
      </form>

      <a class="mt-3 d-block" href="/presensi_v1/template_siswa.xlsx" download>📥 Download Template Excel</a>
    </div>
  </div>
</div>

<!-- FOTO PREVIEW -->
<div class="modal fade" id="fotoModal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content p-2">
      <img id="fotoPreview" src="" style="width:100%;border-radius:10px;">
    </div>
  </div>
</div>

<!-- ================= SCRIPTS ================= -->
<script>
document.addEventListener('DOMContentLoaded', function() {

  // preview foto
  document.querySelectorAll('.btn-foto').forEach(function(btn) {
    btn.addEventListener('click', function() {
      const src = this.getAttribute('data-foto') || '';
      if (!src) return;
      document.getElementById('fotoPreview').src = src;
      new bootstrap.Modal(document.getElementById('fotoModal')).show();
    });
  });

  // edit modal fill
  document.querySelectorAll('.btn-edit').forEach(function(btn) {
    btn.addEventListener('click', function() {
      const id = this.dataset.id || '';
      const nis = this.dataset.nis || '';
      const nama = this.dataset.nama || '';
      const kelas = this.dataset.kelas || '';
      const jurusan = this.dataset.jurusan || '';
      const rombel = this.dataset.rombel || '';
      const foto = this.dataset.foto || '';

      document.getElementById('edit-id').value = id;
      document.getElementById('edit-nis').value = nis;
      document.getElementById('edit-nama').value = nama;
      document.getElementById('edit-kelas').value = kelas;
      document.getElementById('edit-jurusan').value = jurusan;
      document.getElementById('edit-rombel').value = rombel;

      if (foto !== '') {
        document.getElementById('edit-foto-img').src = '/presensi_v1/upload/siswa/' + foto;
        document.getElementById('edit-foto-preview').style.display = 'block';
      } else {
        document.getElementById('edit-foto-preview').style.display = 'none';
      }

      new bootstrap.Modal(document.getElementById('modalEditSiswa')).show();
    });
  });

  // delete single
  document.querySelectorAll('.btn-delete').forEach(function(btn) {
    btn.addEventListener('click', function() {
      const id = this.getAttribute('data-id');
      Swal.fire({
        title: 'Hapus siswa?',
        text: 'Data tidak dapat dikembalikan.',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Hapus',
        confirmButtonColor: '#d33'
      }).then((res) => {
        if (res.isConfirmed) {
          window.location.href = '/presensi_v1/process/siswa_delete.php?id=' + id;
        }
      });
    });
  });

  // bulk delete
  const checkAll = document.getElementById('checkAll');
  const btnBulk = document.getElementById('btnBulkDelete');

  function updateBulk() {
    const any = document.querySelectorAll('.row-check:checked').length > 0;
    btnBulk.classList.toggle('d-none', !any);
  }

  if (checkAll) {
    checkAll.addEventListener('change', function() {
      document.querySelectorAll('.row-check').forEach(ch => ch.checked = checkAll.checked);
      updateBulk();
    });
  }

  document.querySelectorAll('.row-check').forEach(ch => ch.addEventListener('change', updateBulk));

  btnBulk.addEventListener('click', function() {
    const ids = [...document.querySelectorAll('.row-check:checked')].map(i => i.value);
    if (ids.length === 0) return;

    Swal.fire({
      title: 'Hapus ' + ids.length + ' siswa terpilih?',
      icon: 'warning',
      showCancelButton: true,
      confirmButtonText: 'Ya, hapus',
      confirmButtonColor: '#d33'
    }).then(res => {
      if (!res.isConfirmed) return;

      const formData = new URLSearchParams();
      ids.forEach(id => formData.append('ids[]', id));

      fetch('/presensi_v1/process/siswa_bulk_delete.php', {
        method: 'POST',
        headers: {'Content-Type':'application/x-www-form-urlencoded'},
        body: formData
      })
      .then(r => r.json())
      .then(resp => {
        if (resp.status === 'ok') {
          Swal.fire('Berhasil','Siswa berhasil dihapus','success').then(()=> location.reload());
        } else {
          Swal.fire('Error','Gagal menghapus','error');
        }
      });
    });
  });

});
</script>

<?php require_once __DIR__ . '/../includes/footer.php'; ?>
