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

$pageTitle  = 'Dokumen';
$activePage = 'dokumen';

$search   = sanitize($_GET['q'] ?? '');
$jenis    = sanitize($_GET['jenis'] ?? '');
$sekolahF = (int)($_GET['sekolah'] ?? 0);
$page     = max(1,(int)($_GET['page'] ?? 1));

$where  = ['1=1'];
$params = [];

if (isSekolah() && $_SESSION['sekolah_id']) {
    $where[]  = '(d.sekolah_id = ? OR d.publik = 1)';
    $params[] = $_SESSION['sekolah_id'];
} elseif ($sekolahF) {
    $where[]  = 'd.sekolah_id = ?';
    $params[] = $sekolahF;
}
if ($search) { $where[] = '(d.nama_dokumen LIKE ? OR d.deskripsi LIKE ?)'; $params[] = "%$search%"; $params[] = "%$search%"; }
if ($jenis)  { $where[] = 'd.jenis = ?'; $params[] = $jenis; }

$whereStr = implode(' AND ', $where);
$sql = "SELECT d.*, s.nama_sekolah FROM dokumen d LEFT JOIN sekolah s ON s.id=d.sekolah_id WHERE {$whereStr} ORDER BY d.created_at DESC";
$pag = paginate($sql, $params, 15, $page);
$sekolahList = Database::fetchAll("SELECT id,nama_sekolah FROM sekolah WHERE aktif=1 ORDER BY nama_sekolah");
$baseUrl = BASE_URL.'/modules/dokumen/index.php?q='.urlencode($search).'&jenis='.urlencode($jenis).'&sekolah='.$sekolahF;

$jenisList = ['SK','Surat Edaran','Pedoman','Juknis','Form','Laporan','Lainnya'];

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

<div class="page-header">
  <div class="page-header-title">
    <h1><i class="bi bi-folder2-open me-2 text-primary"></i>Dokumen</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">Dokumen</li></ol></nav>
  </div>
  <?php if(isAdmin()): ?>
  <a href="form.php" class="btn btn-primary"><i class="bi bi-cloud-upload me-1"></i>Upload Dokumen</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, deskripsi dokumen…" value="<?= e($search) ?>"></div>
      <div class="col-sm-2">
        <select name="jenis" class="form-select form-select-sm">
          <option value="">Semua Jenis</option>
          <?php foreach($jenisList as $j): ?>
          <option value="<?= $j ?>" <?= $jenis===$j?'selected':'' ?>><?= $j ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <?php if(!isSekolah()): ?>
      <div class="col-sm-3">
        <select name="sekolah" class="form-select form-select-sm">
          <option value="">Semua Sekolah (+ Umum)</option>
          <?php foreach($sekolahList as $s): ?>
          <option value="<?= $s['id'] ?>" <?= $sekolahF==(int)$s['id']?'selected':'' ?>><?= e($s['nama_sekolah']) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <?php endif; ?>
      <div class="col-auto d-flex gap-2">
        <button type="submit" class="btn btn-primary btn-sm"><i class="bi bi-search"></i></button>
        <a href="<?= BASE_URL ?>/modules/dokumen/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-files me-2"></i>Daftar Dokumen</span>
    <span class="badge bg-primary-subtle text-primary"><?= $pag['total'] ?> dokumen</span>
  </div>
  <div class="table-responsive">
    <table class="table table-hover mb-0">
      <thead>
        <tr><th>#</th><th>Nama Dokumen</th><th>Jenis</th><th>Sekolah/Umum</th><th>Tahun</th><th>Diupload</th><th>Publik</th><th>Aksi</th></tr>
      </thead>
      <tbody>
        <?php if(empty($pag['data'])): ?>
        <tr><td colspan="8" class="text-center py-4 text-muted">Tidak ada dokumen</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>
            <div class="d-flex align-items-center gap-2">
              <i class="bi bi-file-earmark-pdf text-danger fs-5"></i>
              <div>
                <div class="fw-600" style="font-size:.87rem"><?= e($row['nama_dokumen']) ?></div>
                <?php if($row['deskripsi']): ?>
                <div class="text-muted" style="font-size:.74rem"><?= e(mb_strimwidth($row['deskripsi'],0,50,'…')) ?></div>
                <?php endif; ?>
              </div>
            </div>
          </td>
          <td><span class="badge bg-primary-subtle text-primary"><?= e($row['jenis']) ?></span></td>
          <td><?= $row['nama_sekolah'] ? e(mb_strimwidth($row['nama_sekolah'],0,30,'…')) : '<span class="badge bg-secondary-subtle text-secondary">Umum</span>' ?></td>
          <td><?= $row['tahun'] ?? '—' ?></td>
          <td style="font-size:.78rem;white-space:nowrap"><?= formatTanggal($row['created_at'],'d M Y') ?></td>
          <td>
            <?php if($row['publik']): ?>
            <span class="badge bg-success-subtle text-success">Ya</span>
            <?php else: ?>
            <span class="badge bg-secondary-subtle text-secondary">Tidak</span>
            <?php endif; ?>
          </td>
          <td>
            <div class="d-flex gap-1">
              <a href="<?= BASE_URL ?>/uploads/dokumen/<?= e($row['nama_file']) ?>" target="_blank" class="btn btn-sm btn-outline-primary" title="Download"><i class="bi bi-download"></i></a>
              <?php if(isAdmin()): ?>
              <a href="form.php?id=<?= $row['id'] ?>" class="btn btn-sm btn-outline-warning" title="Edit"><i class="bi bi-pencil"></i></a>
              <a href="delete.php?id=<?= $row['id'] ?>" class="btn btn-sm btn-outline-danger" data-confirm="Hapus dokumen ini?" 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'; ?>
