<?php
include '../../koneksi.php';

$kelas   = $_GET['kelas']   ?? '';
$tanggal = $_GET['tanggal'] ?? '';
$status  = $_GET['status']  ?? '';
$limit   = $_GET['limit']   ?? 10;
$search  = $_GET['search']  ?? '';

$where = "WHERE 1=1";

/* FILTER KELAS */
if ($kelas != '') {
  if ($kelas == 'Guru') {
    $where .= " AND u.role = 'guru'";
  } else {
    $where .= " AND s.kelas = '$kelas'";
  }
}

/* FILTER TANGGAL */
if ($tanggal != '') {
  $where .= " AND f.tanggal = '$tanggal'";
}

/* FILTER STATUS */
if ($status != '') {
  $where .= " AND f.status = '$status'";
}

/* SEARCH */
if ($search != '') {
  $where .= " AND (
    s.nama_lengkap LIKE '%$search%'
    OR s.nisn LIKE '%$search%'
    OR g.nama_lengkap LIKE '%$search%'
    OR g.nip LIKE '%$search%'
  )";
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<title>Kelola Form Izin</title>

<link href="../../bootstrap-5.3.8-dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css" rel="stylesheet">

<style>
body { background:#f4f6f9; }
.card {
  border-radius:18px;
  box-shadow:0 12px 35px rgba(0,0,0,.12);
}
.filter-bar {
  position: sticky;
  top: 0;
  z-index: 10;
  background:#fff;
  padding:15px;
  border-radius:14px;
  box-shadow:0 6px 15px rgba(0,0,0,.08);
}
.table-wrapper {
  max-height:55vh;
  overflow-y:auto;
}
.table thead {
  position: sticky;
  top: 0;
  z-index: 5;
  background:linear-gradient(90deg,#1e6f91,#2a8fbd);
  color:#fff;
}
.badge-status {
  padding:6px 12px;
  border-radius:20px;
}
</style>
</head>

<body>

<div class="container-fluid mt-3">
<div class="card p-4">

<h4 class="fw-bold mb-3">
  <i class="bi bi-file-earmark-text"></i> Data Pengajuan Izin
</h4>

<!-- FILTER -->
<form method="get" class="filter-bar mb-3">
<div class="row g-2 align-items-end">

  <div class="col-md-2">
    <label class="form-label">Kelas</label>
    <select name="kelas" class="form-select">
      <option value="">Semua</option>
      <?php
      $kelasList = ['X IPA','X IPS','XI IPA','XI IPS','XII IPA','XII IPS','Guru'];
      foreach ($kelasList as $k) {
        $sel = ($kelas==$k)?'selected':'';
        echo "<option $sel>$k</option>";
      }
      ?>
    </select>
  </div>

  <div class="col-md-2">
    <label class="form-label">Tanggal</label>
    <input type="date" name="tanggal" value="<?= $tanggal ?>" class="form-control">
  </div>

  <div class="col-md-2">
    <label class="form-label">Status</label>
    <select name="status" class="form-select">
      <option value="">Semua</option>
      <?php foreach (['Menunggu','Disetujui','Ditolak'] as $s): ?>
        <option value="<?= $s ?>" <?= $status==$s?'selected':'' ?>><?= $s ?></option>
      <?php endforeach; ?>
    </select>
  </div>

  <div class="col-md-2">
    <label class="form-label">Tampilkan</label>
    <select name="limit" class="form-select">
      <?php foreach ([10,25,50,100] as $l): ?>
        <option value="<?= $l ?>" <?= $limit==$l?'selected':'' ?>><?= $l ?></option>
      <?php endforeach; ?>
    </select>
  </div>

  <div class="col-md-2">
    <label class="form-label">Cari</label>
    <input type="text" name="search" value="<?= $search ?>" class="form-control"
      placeholder="Nama / NISN / NIP">
  </div>

  <div class="col-md-2 d-flex gap-2">
    <button class="btn btn-info text-white rounded-pill btn-sm w-100">
      <i class="bi bi-funnel"></i>
    </button>
    <a href="form.php" class="btn btn-secondary rounded-pill btn-sm w-100">
      Reset
    </a>
  </div>

</div>
</form>

<!-- TABLE -->
<div class="table-wrapper">
<table class="table table-hover align-middle">
<thead>
<tr>
  <th>No</th>
  <th>Identitas</th>
  <th>Nama</th>
  <th>Kelas</th>
  <th>Tanggal</th>
  <th>Jenis</th>
  <th>Keterangan</th>
  <th>Surat</th>
  <th>Status</th>
  <th class="text-center">Aksi</th>
</tr>
</thead>
<tbody>

<?php
$no = 1;

$query = "
SELECT 
  f.*,
  u.role,
  s.nisn,
  s.kelas,
  s.nama_lengkap AS nama_siswa,
  g.nip,
  g.nama_lengkap AS nama_guru
FROM form_izin f
JOIN users u ON f.user_id = u.id
LEFT JOIN siswa s ON u.id = s.user_id
LEFT JOIN guru g ON u.id = g.user_id   -- 🔥 INI YANG DIPERBAIKI
$where
ORDER BY f.id DESC
LIMIT $limit
";

$result = mysqli_query($koneksi, $query);

if ($result && mysqli_num_rows($result) > 0) {
  while ($d = mysqli_fetch_assoc($result)) {

    $nama = ($d['role']=='siswa') ? $d['nama_siswa'] : $d['nama_guru'];
    $identitas = ($d['role']=='siswa') ? $d['nisn'] : $d['nip'];
    $kelasView = ($d['role']=='siswa')
      ? "<span class='badge bg-primary'>{$d['kelas']}</span>"
      : "<span class='badge bg-dark'>Guru</span>";

    $fileLink = !empty($d['file_surat'])
      ? "<a class='btn btn-info btn-sm' target='_blank' href='../../uploads/{$d['file_surat']}'>Lihat</a>"
      : "-";

    $statusClass = match($d['status']) {
      'Disetujui'=>'bg-success',
      'Ditolak'=>'bg-danger',
      default=>'bg-warning text-dark'
    };

    echo "
    <tr>
      <td>{$no}</td>
      <td>{$identitas}</td>
      <td>{$nama}</td>
      <td>{$kelasView}</td>
      <td>{$d['tanggal']}</td>
      <td>{$d['jenis']}</td>
      <td>{$d['keterangan']}</td>
      <td>{$fileLink}</td>
      <td><span class='badge badge-status {$statusClass}'>{$d['status']}</span></td>
      <td class='text-center'>
        <button class='btn btn-warning btn-sm rounded-pill'
          onclick=\"openInParent('kelola_form/edit.php?id={$d['id']}')\">
          <i class='bi bi-gear'></i>
        </button>
        <button class='btn btn-danger btn-sm rounded-pill'
          onclick=\"hapusForm({$d['id']})\">
          <i class='bi bi-trash'></i>
        </button>
      </td>
    </tr>";
    $no++;
  }
} else {
  echo "<tr><td colspan='10' class='text-center text-muted'>Data tidak ditemukan</td></tr>";
}
?>

</tbody>
</table>
</div>

</div>
</div>

<script src="../../bootstrap-5.3.8-dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
function openInParent(path) {
  try {
    parent.document.getElementById('iframeContent').src = path;
  } catch {
    window.location.href = path;
  }
}

function hapusForm(id) {
  Swal.fire({
    title: 'Hapus Data?',
    text: 'Data tidak bisa dikembalikan!',
    icon: 'warning',
    showCancelButton: true,
    confirmButtonColor: '#dc3545',
    cancelButtonColor: '#0d6efd',
    confirmButtonText: 'Ya, hapus'
  }).then((res) => {
    if (res.isConfirmed) {
      fetch('hapus.php?id=' + id).then(() => location.reload());
    }
  });
}
</script>

</body>
</html>
