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

$pageTitle  = 'Kegiatan Pendampingan';
$activePage = 'kegiatan';

$search    = sanitize($_GET['q'] ?? '');
$sekolahF  = (int)($_GET['sekolah'] ?? 0);
$bulan     = sanitize($_GET['bulan'] ?? '');
$tahun     = sanitize($_GET['tahun'] ?? '');
$status    = sanitize($_GET['status'] ?? '');
$page      = max(1, (int)($_GET['page'] ?? 1));
$perPage   = 15;

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

if (isSekolah() && $_SESSION['sekolah_id']) {
    $where[]  = 'k.sekolah_id = ?';
    $params[] = $_SESSION['sekolah_id'];
} elseif ($sekolahF) {
    $where[]  = 'k.sekolah_id = ?';
    $params[] = $sekolahF;
}
if ($search) {
    $where[]  = '(k.nama_kegiatan LIKE ? OR k.materi LIKE ? OR s.nama_sekolah LIKE ?)';
    $params[] = "%{$search}%"; $params[] = "%{$search}%"; $params[] = "%{$search}%";
}
if ($bulan) { $where[] = 'MONTH(k.tanggal_kegiatan) = ?'; $params[] = $bulan; }
if ($tahun) { $where[] = 'YEAR(k.tanggal_kegiatan) = ?'; $params[] = $tahun; }
if ($status){ $where[] = 'k.status = ?'; $params[] = $status; }

$whereStr = implode(' AND ', $where);
$sql      = "SELECT k.*, s.nama_sekolah FROM kegiatan_pendampingan k
             JOIN sekolah s ON s.id=k.sekolah_id
             WHERE {$whereStr}
             ORDER BY k.tanggal_kegiatan DESC";
$pag      = paginate($sql, $params, $perPage, $page);

$sekolahList = Database::fetchAll("SELECT id, nama_sekolah FROM sekolah WHERE aktif=1 ORDER BY nama_sekolah");
$baseUrl = BASE_URL . '/modules/kegiatan/index.php?q=' . urlencode($search)
         . '&sekolah=' . $sekolahF . '&bulan=' . urlencode($bulan)
         . '&tahun=' . urlencode($tahun) . '&status=' . urlencode($status);

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

<div class="page-header">
  <div class="page-header-title">
    <h1><i class="bi bi-journal-text me-2 text-primary"></i>Kegiatan Pendampingan</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">Kegiatan</li></ol></nav>
  </div>
  <?php if(isAdmin()): ?>
  <a href="<?= BASE_URL ?>/modules/kegiatan/form.php" class="btn btn-primary">
    <i class="bi bi-plus-lg me-1"></i>Tambah Kegiatan
  </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-4">
        <input type="text" name="q" class="form-control form-control-sm" placeholder="Cari kegiatan, materi, sekolah…" value="<?= e($search) ?>">
      </div>
      <?php if(!isSekolah()): ?>
      <div class="col-sm-3">
        <select name="sekolah" class="form-select form-select-sm">
          <option value="">Semua Sekolah</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-sm-2">
        <select name="bulan" class="form-select form-select-sm">
          <option value="">Semua Bulan</option>
          <?php $bulanNama=['','Jan','Feb','Mar','Apr','Mei','Jun','Jul','Ags','Sep','Okt','Nov','Des'];
          for($m=1;$m<=12;$m++): ?>
          <option value="<?= $m ?>" <?= $bulan==(string)$m?'selected':'' ?>><?= $bulanNama[$m] ?></option>
          <?php endfor; ?>
        </select>
      </div>
      <div class="col-sm-1">
        <input type="number" name="tahun" class="form-control form-control-sm" placeholder="Tahun" value="<?= e($tahun) ?>" min="2020" max="2030">
      </div>
      <div class="col-sm-2">
        <select name="status" class="form-select form-select-sm">
          <option value="">Semua Status</option>
          <?php foreach(['Draft','Terkirim','Disetujui'] as $st): ?>
          <option value="<?= $st ?>" <?= $status===$st?'selected':'' ?>><?= $st ?></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"></i></button>
        <a href="<?= BASE_URL ?>/modules/kegiatan/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 Kegiatan</span>
    <div class="d-flex gap-2 align-items-center">
      <span class="badge bg-primary-subtle text-primary"><?= $pag['total'] ?> kegiatan</span>
      <a href="<?= BASE_URL ?>/exports/laporan.php?type=kegiatan&<?= http_build_query($_GET) ?>"
         class="btn btn-sm btn-outline-danger" target="_blank">
        <i class="bi bi-file-pdf me-1"></i>Export PDF
      </a>
    </div>
  </div>
  <div class="table-responsive">
    <table class="table table-hover mb-0">
      <thead>
        <tr>
          <th>#</th>
          <th>Tanggal</th>
          <th>Sekolah</th>
          <th>Nama Kegiatan</th>
          <th>Sasaran</th>
          <th>Status</th>
          <th width="110">Aksi</th>
        </tr>
      </thead>
      <tbody>
        <?php if(empty($pag['data'])): ?>
        <tr><td colspan="7" class="text-center py-4 text-muted">Tidak ada data kegiatan</td></tr>
        <?php else: ?>
        <?php $no = ($pag['current']-1)*$pag['per_page']+1; ?>
        <?php foreach($pag['data'] as $row):
          $statusColor = ['Draft'=>'secondary','Terkirim'=>'info','Disetujui'=>'success'][$row['status']] ?? 'secondary';
        ?>
        <tr>
          <td class="text-muted"><?= $no++ ?></td>
          <td style="white-space:nowrap"><?= formatTanggal($row['tanggal_kegiatan'],'d M Y') ?></td>
          <td><?= e(mb_strimwidth($row['nama_sekolah'],0,35,'…')) ?></td>
          <td><?= e(mb_strimwidth($row['nama_kegiatan'],0,40,'…')) ?></td>
          <td><?= e(mb_strimwidth($row['sasaran'],0,30,'…')) ?></td>
          <td><span class="badge bg-<?= $statusColor ?>-subtle text-<?= $statusColor ?>"><?= e($row['status']) ?></span></td>
          <td>
            <div class="d-flex gap-1">
              <a href="detail.php?id=<?= $row['id'] ?>" class="btn btn-sm btn-outline-info" title="Detail"><i class="bi bi-eye"></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 kegiatan 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'; ?>
