<?php
require_once '../../config/config.php';
require_once '../../config/database.php';
require_once '../../core/helpers.php';
requireLogin();

$pageTitle  = 'Data Sekolah';
$activePage = 'sekolah';

// Filter & Search
$search    = sanitize($_GET['q'] ?? '');
$jenis     = sanitize($_GET['jenis'] ?? '');
$kecamatan = sanitize($_GET['kec'] ?? '');
$page      = max(1, (int)($_GET['page'] ?? 1));
$perPage   = 15;

// Query builder
$where  = ['1=1'];
$params = [];

if (isSekolah() && $_SESSION['sekolah_id']) {
    $where[]  = 's.id = ?';
    $params[] = $_SESSION['sekolah_id'];
}
if ($search) {
    $where[]  = '(s.nama_sekolah LIKE ? OR s.npsn LIKE ? OR s.kepala_sekolah LIKE ?)';
    $params[] = "%{$search}%"; $params[] = "%{$search}%"; $params[] = "%{$search}%";
}
if ($jenis) { $where[] = 's.jenis = ?'; $params[] = $jenis; }
if ($kecamatan) { $where[] = 's.kecamatan = ?'; $params[] = $kecamatan; }

$whereStr = implode(' AND ', $where);
$sql      = "SELECT s.* FROM sekolah s WHERE {$whereStr} ORDER BY s.nama_sekolah";
$pag      = paginate($sql, $params, $perPage, $page);

$kecamatanList = Database::fetchAll("SELECT DISTINCT kecamatan FROM sekolah ORDER BY kecamatan");
$baseUrl = BASE_URL . '/modules/sekolah/index.php?q=' . urlencode($search)
         . '&jenis=' . urlencode($jenis) . '&kec=' . urlencode($kecamatan);

require_once ROOT_PATH . '/views/layouts/header.php';
?>

<div class="page-header">
  <div class="page-header-title">
    <h1><i class="bi bi-building me-2 text-primary"></i>Data Sekolah</h1>
    <nav><ol class="breadcrumb"><li class="breadcrumb-item"><a href="<?= BASE_URL ?>/modules/dashboard/index.php">Dashboard</a></li><li class="breadcrumb-item active">Sekolah</li></ol></nav>
  </div>
  <?php if(isAdmin()): ?>
  <a href="<?= BASE_URL ?>/modules/sekolah/form.php" class="btn btn-primary">
    <i class="bi bi-plus-lg me-1"></i>Tambah Sekolah
  </a>
  <?php endif; ?>
</div>

<!-- FILTER -->
<div class="card mb-3">
  <div class="card-body py-2">
    <form method="GET" class="row g-2 align-items-end">
      <div class="col-sm-5">
        <input type="text" name="q" class="form-control form-control-sm" placeholder="Cari nama sekolah, NPSN, kepala sekolah…" value="<?= e($search) ?>">
      </div>
      <div class="col-sm-3">
        <select name="jenis" class="form-select form-select-sm">
          <option value="">Semua Jenis</option>
          <option value="SMP Negeri" <?= $jenis==='SMP Negeri'?'selected':'' ?>>SMP Negeri</option>
          <option value="SMP Swasta" <?= $jenis==='SMP Swasta'?'selected':'' ?>>SMP Swasta</option>
        </select>
      </div>
      <div class="col-sm-2">
        <select name="kec" class="form-select form-select-sm">
          <option value="">Semua Kecamatan</option>
          <?php foreach($kecamatanList as $k): ?>
          <option value="<?= e($k['kecamatan']) ?>" <?= $kecamatan===$k['kecamatan']?'selected':'' ?>><?= e($k['kecamatan']) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-auto d-flex gap-2">
        <button type="submit" class="btn btn-primary btn-sm"><i class="bi bi-search me-1"></i>Cari</button>
        <a href="<?= BASE_URL ?>/modules/sekolah/index.php" class="btn btn-outline-secondary btn-sm">Reset</a>
      </div>
    </form>
  </div>
</div>

<!-- TABLE -->
<div class="card">
  <div class="card-header">
    <span class="card-header-title"><i class="bi bi-table me-2"></i>Daftar Sekolah</span>
    <span class="badge bg-primary-subtle text-primary"><?= $pag['total'] ?> sekolah</span>
  </div>
  <div class="table-responsive">
    <table class="table table-hover mb-0">
      <thead>
        <tr>
          <th width="40">#</th>
          <th>NPSN</th>
          <th>Nama Sekolah</th>
          <th>Jenis</th>
          <th>Kecamatan</th>
          <th>Kepala Sekolah</th>
          <th>Akreditasi</th>
          <th width="100">Aksi</th>
        </tr>
      </thead>
      <tbody>
        <?php if(empty($pag['data'])): ?>
        <tr><td colspan="8" class="text-center py-4 text-muted">Tidak ada data sekolah</td></tr>
        <?php else: ?>
        <?php $no = ($pag['current']-1)*$pag['per_page']+1; ?>
        <?php foreach($pag['data'] as $row): ?>
        <tr>
          <td class="text-muted"><?= $no++ ?></td>
          <td><code><?= e($row['npsn']) ?></code></td>
          <td>
            <a href="<?= BASE_URL ?>/modules/sekolah/detail.php?id=<?= $row['id'] ?>" class="fw-600 text-decoration-none text-primary">
              <?= e($row['nama_sekolah']) ?>
            </a>
          </td>
          <td>
            <span class="badge <?= $row['jenis']==='SMP Negeri' ? 'bg-primary-subtle text-primary' : 'bg-danger-subtle text-danger' ?>">
              <?= e($row['jenis']) ?>
            </span>
          </td>
          <td><?= e($row['kecamatan']) ?></td>
          <td><?= e($row['kepala_sekolah']) ?></td>
          <td>
            <?php if($row['akreditasi']): ?>
            <span class="badge bg-success-subtle text-success"><?= e($row['akreditasi']) ?></span>
            <?php else: ?>
            <span class="text-muted">—</span>
            <?php endif; ?>
          </td>
          <td>
            <div class="d-flex gap-1">
              <a href="<?= BASE_URL ?>/modules/sekolah/detail.php?id=<?= $row['id'] ?>" class="btn btn-sm btn-outline-info" data-bs-toggle="tooltip" title="Detail">
                <i class="bi bi-eye"></i>
              </a>
              <?php if(isAdmin()): ?>
              <a href="<?= BASE_URL ?>/modules/sekolah/form.php?id=<?= $row['id'] ?>" class="btn btn-sm btn-outline-warning" data-bs-toggle="tooltip" title="Edit">
                <i class="bi bi-pencil"></i>
              </a>
              <a href="<?= BASE_URL ?>/modules/sekolah/delete.php?id=<?= $row['id'] ?>"
                 class="btn btn-sm btn-outline-danger"
                 data-confirm="Hapus sekolah <?= e($row['nama_sekolah']) ?>?"
                 data-bs-toggle="tooltip" title="Hapus">
                <i class="bi bi-trash"></i>
              </a>
              <?php endif; ?>
            </div>
          </td>
        </tr>
        <?php endforeach; ?>
        <?php endif; ?>
      </tbody>
    </table>
  </div>
  <?php if($pag['pages'] > 1): ?>
  <div class="card-footer d-flex justify-content-between align-items-center flex-wrap gap-2">
    <span class="text-muted small">Menampilkan <?= count($pag['data']) ?> dari <?= $pag['total'] ?> data</span>
    <?= renderPagination($pag, $baseUrl) ?>
  </div>
  <?php endif; ?>
</div>

<?php require_once ROOT_PATH . '/views/layouts/footer.php'; ?>
