<?php
// exports/laporan.php — Laporan Rekapitulasi Kegiatan
require_once '../config/config.php';
require_once '../config/database.php';
require_once '../core/helpers.php';
requireLogin();

$type     = sanitize($_GET['type'] ?? 'kegiatan');
$sekolahF = (int)($_GET['sekolah'] ?? 0);
$bulan    = sanitize($_GET['bulan'] ?? '');
$tahun    = sanitize($_GET['tahun'] ?? date('Y'));
$status   = sanitize($_GET['status'] ?? '');

// Build query
$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 ($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);
$kegiatan = Database::fetchAll(
    "SELECT k.*, s.nama_sekolah, s.jenis, s.kecamatan
     FROM kegiatan_pendampingan k
     JOIN sekolah s ON s.id=k.sekolah_id
     WHERE {$whereStr}
     ORDER BY k.tanggal_kegiatan ASC",
    $params
);

$profil = Database::fetchOne("SELECT * FROM profil_pendamping LIMIT 1");

// Rekap per sekolah
$rekapSekolah = [];
foreach ($kegiatan as $k) {
    $sn = $k['nama_sekolah'];
    if (!isset($rekapSekolah[$sn])) $rekapSekolah[$sn] = ['jml' => 0, 'jenis' => $k['jenis'], 'kecamatan' => $k['kecamatan']];
    $rekapSekolah[$sn]['jml']++;
}

$judulLaporan = 'Rekapitulasi Kegiatan Pendampingan Sekolah';
$periodeLabel = ($bulan ? 'Bulan ' . $bulan . ' ' : '') . 'Tahun ' . $tahun;
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<title><?= $judulLaporan ?></title>
<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
<style>
  * { box-sizing:border-box; margin:0; padding:0; }
  body { font-family:'Plus Jakarta Sans',sans-serif; font-size:10.5pt; color:#1a1a2e; background:#fff; }
  @page { size:A4 portrait; margin:18mm 15mm 18mm 20mm; }
  @media print { .no-print{display:none!important} }

  /* KOP */
  .kop { display:flex; align-items:center; gap:12px; border-bottom:3px solid #1a3a6b; padding-bottom:8px; margin-bottom:10px; }
  .kop-logo { width:54px; height:54px; background:#1a3a6b; border-radius:10px; display:flex; align-items:center; justify-content:center; flex-shrink:0; }
  .kop-logo svg { width:30px; height:30px; fill:#fff; }
  .kop-info h1 { font-size:13pt; font-weight:800; color:#1a3a6b; }
  .kop-info p { font-size:8.5pt; color:#555; margin-top:2px; }

  /* Judul */
  .title-block { text-align:center; margin:10px 0 14px; }
  .title-block h2 { font-size:12.5pt; font-weight:800; text-transform:uppercase; color:#1a3a6b; }
  .title-block h3 { font-size:10pt; font-weight:600; color:#333; margin-top:4px; }
  .title-block .garis { width:80px; height:3px; background:#c0392b; margin:6px auto; border-radius:2px; }

  /* Info Pendamping */
  .info-box { border:1px solid #d0d8e8; border-radius:6px; padding:8px 12px; margin-bottom:12px; display:grid; grid-template-columns:1fr 1fr; gap:4px 24px; font-size:9.5pt; }
  .info-box .row-item { display:flex; gap:6px; }
  .info-box .label { color:#555; min-width:90px; font-weight:600; }

  /* Ringkasan */
  .summary-row { display:grid; grid-template-columns:repeat(4,1fr); gap:8px; margin-bottom:12px; }
  .summary-box { border:1px solid #d0d8e8; border-radius:6px; text-align:center; padding:8px 4px; }
  .summary-box .val { font-size:18pt; font-weight:800; color:#1a3a6b; line-height:1; }
  .summary-box .lbl { font-size:8pt; color:#666; margin-top:3px; }

  /* Tabel */
  table { width:100%; border-collapse:collapse; font-size:9.5pt; margin-bottom:14px; }
  thead th { background:#1a3a6b; color:#fff; padding:6px 8px; text-align:left; font-weight:600; }
  tbody td { padding:5px 8px; border-bottom:1px solid #e8edf5; vertical-align:top; }
  tbody tr:nth-child(even) td { background:#f5f8ff; }
  tbody tr:last-child td { border-bottom:none; }

  /* Rekap sekolah tabel */
  .rekap-title { font-size:10pt; font-weight:700; color:#1a3a6b; border-left:3px solid #c0392b; padding-left:8px; margin:14px 0 8px; }

  /* Status badge */
  .badge { display:inline-block; padding:1px 7px; border-radius:20px; font-size:8pt; font-weight:600; }
  .badge-draft { background:#e2e8f0; color:#475569; }
  .badge-terkirim { background:#e0f2fe; color:#0369a1; }
  .badge-disetujui { background:#dcfce7; color:#15803d; }

  /* TTD */
  .ttd-section { display:flex; justify-content:flex-end; margin-top:24px; }
  .ttd-box { text-align:center; font-size:10pt; }
  .ttd-box .space { height:56px; }
  .ttd-box .name { font-weight:700; border-top:1px solid #333; padding-top:4px; min-width:180px; display:inline-block; }

  /* Footer */
  .doc-footer { text-align:center; font-size:8pt; color:#999; border-top:1px solid #e0e0e0; padding-top:6px; margin-top:16px; }

  /* Print controls */
  .ctrl-bar { position:fixed; bottom:0; left:0; right:0; background:#1a3a6b; padding:10px 20px; display:flex; justify-content:space-between; align-items:center; z-index:999; }
  .ctrl-bar span { color:rgba(255,255,255,.75); font-size:.85rem; }
  .ctrl-bar .btns { display:flex; gap:10px; }
  .btn-ctrl { padding:8px 20px; border-radius:6px; border:none; font-family:inherit; font-weight:700; font-size:.85rem; cursor:pointer; }
  .btn-print { background:#c0392b; color:#fff; }
  .btn-back  { background:rgba(255,255,255,.15); color:#fff; border:1px solid rgba(255,255,255,.3); }
</style>
</head>
<body>

<!-- KOP SURAT -->
<div class="kop">
  <div class="kop-logo">
    <svg viewBox="0 0 24 24"><path d="M12 3L1 9l11 6 9-4.91V17h2V9L12 3zM5 13.18v4L12 21l7-3.82v-4L12 17l-7-3.82z"/></svg>
  </div>
  <div class="kop-info">
    <h1><?= APP_INSTANSI ?></h1>
    <p>Jl. Ki Ageng Gribig No. 45, Malang, Jawa Timur &nbsp;|&nbsp; Telp. (0341) 123456 &nbsp;|&nbsp; Email: disdik@malangkab.go.id</p>
  </div>
</div>

<!-- JUDUL -->
<div class="title-block">
  <h2><?= $judulLaporan ?></h2>
  <h3>Periode: <?= $periodeLabel ?></h3>
  <div class="garis"></div>
</div>

<!-- INFO PENDAMPING -->
<div class="info-box">
  <div class="row-item"><span class="label">Nama</span><span><?= e($profil['nama_lengkap'] ?? '—') ?></span></div>
  <div class="row-item"><span class="label">NIP</span><span><?= e($profil['nip'] ?? '—') ?></span></div>
  <div class="row-item"><span class="label">Jabatan</span><span><?= e($profil['jabatan'] ?? '—') ?></span></div>
  <div class="row-item"><span class="label">Instansi</span><span><?= e($profil['unit_kerja'] ?? APP_INSTANSI) ?></span></div>
</div>

<!-- RINGKASAN -->
<?php
$totalKeg   = count($kegiatan);
$totalSek   = count($rekapSekolah);
$totalDraft = count(array_filter($kegiatan, fn($k) => $k['status']==='Draft'));
$totalDisetujui = count(array_filter($kegiatan, fn($k) => $k['status']==='Disetujui'));
?>
<div class="summary-row">
  <div class="summary-box"><div class="val"><?= $totalKeg ?></div><div class="lbl">Total Kegiatan</div></div>
  <div class="summary-box"><div class="val"><?= $totalSek ?></div><div class="lbl">Sekolah Terdampingi</div></div>
  <div class="summary-box"><div class="val"><?= $totalDisetujui ?></div><div class="lbl">Sudah Disetujui</div></div>
  <div class="summary-box"><div class="val"><?= $totalDraft ?></div><div class="lbl">Masih Draft</div></div>
</div>

<!-- TABEL KEGIATAN -->
<div class="rekap-title">Daftar Kegiatan Pendampingan</div>
<table>
  <thead>
    <tr>
      <th width="28">No</th>
      <th width="68">Tanggal</th>
      <th>Nama Kegiatan</th>
      <th>Sekolah</th>
      <th width="70">Kecamatan</th>
      <th>Sasaran</th>
      <th width="60">Status</th>
    </tr>
  </thead>
  <tbody>
    <?php if(empty($kegiatan)): ?>
    <tr><td colspan="7" style="text-align:center;padding:20px;color:#999">Tidak ada data kegiatan</td></tr>
    <?php else: ?>
    <?php $no=1; foreach($kegiatan as $k):
      $badgeClass = ['Draft'=>'badge-draft','Terkirim'=>'badge-terkirim','Disetujui'=>'badge-disetujui'][$k['status']] ?? 'badge-draft';
    ?>
    <tr>
      <td><?= $no++ ?></td>
      <td style="white-space:nowrap"><?= formatTanggal($k['tanggal_kegiatan'],'d M Y') ?></td>
      <td><?= e($k['nama_kegiatan']) ?></td>
      <td><?= e($k['nama_sekolah']) ?></td>
      <td><?= e($k['kecamatan']) ?></td>
      <td><?= e($k['sasaran']) ?></td>
      <td><span class="badge <?= $badgeClass ?>"><?= e($k['status']) ?></span></td>
    </tr>
    <?php endforeach; ?>
    <?php endif; ?>
  </tbody>
</table>

<!-- REKAP PER SEKOLAH -->
<?php if($rekapSekolah): ?>
<div class="rekap-title">Rekapitulasi Kegiatan per Sekolah</div>
<table>
  <thead>
    <tr>
      <th width="28">No</th>
      <th>Nama Sekolah</th>
      <th width="80">Jenis</th>
      <th width="90">Kecamatan</th>
      <th width="70" style="text-align:center">Jml Kegiatan</th>
    </tr>
  </thead>
  <tbody>
    <?php $no=1; arsort($rekapSekolah); foreach($rekapSekolah as $nama => $info): ?>
    <tr>
      <td><?= $no++ ?></td>
      <td><?= e($nama) ?></td>
      <td><?= e($info['jenis']) ?></td>
      <td><?= e($info['kecamatan']) ?></td>
      <td style="text-align:center;font-weight:700"><?= $info['jml'] ?></td>
    </tr>
    <?php endforeach; ?>
  </tbody>
</table>
<?php endif; ?>

<!-- TTD -->
<div class="ttd-section">
  <div class="ttd-box">
    <p>Malang, <?= formatTanggal(date('Y-m-d'), 'd F Y') ?></p>
    <p>Pendamping Sekolah,</p>
    <div class="space"></div>
    <span class="name"><?= e($profil['nama_lengkap'] ?? 'Nama Pendamping') ?></span>
    <p style="font-size:8.5pt;color:#555;margin-top:2px">NIP. <?= e($profil['nip'] ?? '—') ?></p>
  </div>
</div>

<!-- FOOTER -->
<div class="doc-footer">
  Dicetak oleh: <?= e($_SESSION['nama'] ?? '') ?> &nbsp;|&nbsp; <?= date('d/m/Y H:i') ?> &nbsp;|&nbsp; <?= APP_NAME ?> v<?= APP_VERSION ?>
</div>

<!-- Control Bar -->
<div class="ctrl-bar no-print">
  <span><?= $totalKeg ?> kegiatan &bull; <?= $totalSek ?> sekolah &bull; <?= $periodeLabel ?></span>
  <div class="btns">
    <button class="btn-ctrl btn-back" onclick="window.history.back()">← Kembali</button>
    <button class="btn-ctrl btn-print" onclick="window.print()">🖨 Cetak / Simpan PDF</button>
  </div>
</div>

</body>
</html>
