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

$pageTitle  = 'Dashboard';
$activePage = 'dashboard';

// === STATISTIK ===
$sekolahId = $_SESSION['sekolah_id'] ?? null;

if (isSekolah() && $sekolahId) {
    $totalSekolah   = 1;
    $totalKegiatan  = Database::count("SELECT COUNT(*) FROM kegiatan_pendampingan WHERE sekolah_id=?", [$sekolahId]);
    $totalDokumen   = Database::count("SELECT COUNT(*) FROM dokumen WHERE sekolah_id=?", [$sekolahId]);
    $totalAgenda    = Database::count("SELECT COUNT(*) FROM agenda_kegiatan WHERE tanggal >= CURDATE()");
} else {
    $totalSekolah   = Database::count("SELECT COUNT(*) FROM sekolah WHERE aktif=1");
    $totalKegiatan  = Database::count("SELECT COUNT(*) FROM kegiatan_pendampingan");
    $totalDokumen   = Database::count("SELECT COUNT(*) FROM dokumen");
    $totalAgenda    = Database::count("SELECT COUNT(*) FROM agenda_kegiatan WHERE tanggal >= CURDATE()");
}

$totalPengembangan = Database::count("SELECT COUNT(*) FROM pengembangan_diri");
$totalProgram      = Database::count("SELECT COUNT(*) FROM program_kerja");

// Kegiatan 6 bulan terakhir (untuk chart)
$kegiatanBulan = Database::fetchAll(
    "SELECT DATE_FORMAT(tanggal_kegiatan,'%b %Y') AS bulan,
            DATE_FORMAT(tanggal_kegiatan,'%Y-%m') AS ym,
            COUNT(*) AS jml
     FROM kegiatan_pendampingan
     WHERE tanggal_kegiatan >= DATE_SUB(CURDATE(), INTERVAL 6 MONTH)
     GROUP BY ym ORDER BY ym"
);

// Agenda mendatang
$agendaMendatang = Database::fetchAll(
    "SELECT * FROM agenda_kegiatan
     WHERE tanggal >= CURDATE() AND status='Terjadwal'
     ORDER BY tanggal ASC LIMIT 5"
);

// Kegiatan terbaru
if (isSekolah() && $sekolahId) {
    $kegiatanTerbaru = Database::fetchAll(
        "SELECT k.*, s.nama_sekolah FROM kegiatan_pendampingan k
         JOIN sekolah s ON s.id=k.sekolah_id
         WHERE k.sekolah_id=? ORDER BY k.tanggal_kegiatan DESC LIMIT 5",
        [$sekolahId]
    );
} else {
    $kegiatanTerbaru = Database::fetchAll(
        "SELECT k.*, s.nama_sekolah FROM kegiatan_pendampingan k
         JOIN sekolah s ON s.id=k.sekolah_id
         ORDER BY k.tanggal_kegiatan DESC LIMIT 5"
    );
}

// Sekolah per jenis untuk pie chart
$sekolahJenis = Database::fetchAll(
    "SELECT jenis, COUNT(*) AS jml FROM sekolah WHERE aktif=1 GROUP BY jenis"
);

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

<!-- PAGE HEADER -->
<div class="page-header">
  <div class="page-header-title">
    <h1><i class="bi bi-speedometer2 me-2 text-danger"></i>Dashboard</h1>
    <nav aria-label="breadcrumb">
      <ol class="breadcrumb">
        <li class="breadcrumb-item active">Beranda</li>
      </ol>
    </nav>
  </div>
  <div class="d-flex align-items-center gap-2 text-muted" style="font-size:.82rem">
    <i class="bi bi-calendar3"></i>
    <span><?= formatTanggal(date('Y-m-d'), 'l, d F Y') ?></span>
  </div>
</div>

<!-- STAT CARDS -->
<div class="row g-3 mb-4">
  <!-- Sekolah -->
  <div class="col-6 col-md-4 col-xl-2">
    <div class="stat-card h-100" style="--card-accent:#1a3a6b;--icon-bg:rgba(26,58,107,.08)">
      <div class="d-flex align-items-start justify-content-between mb-3">
        <div class="stat-card-icon"><i class="bi bi-building"></i></div>
      </div>
      <div class="stat-card-value"><?= $totalSekolah ?></div>
      <div class="stat-card-label">Sekolah</div>
    </div>
  </div>

  <!-- Kegiatan -->
  <div class="col-6 col-md-4 col-xl-2">
    <div class="stat-card h-100" style="--card-accent:#c0392b;--icon-bg:rgba(192,57,43,.08)">
      <div class="d-flex align-items-start justify-content-between mb-3">
        <div class="stat-card-icon" style="color:#c0392b"><i class="bi bi-journal-text"></i></div>
      </div>
      <div class="stat-card-value"><?= $totalKegiatan ?></div>
      <div class="stat-card-label">Kegiatan</div>
    </div>
  </div>

  <!-- Agenda -->
  <div class="col-6 col-md-4 col-xl-2">
    <div class="stat-card h-100" style="--card-accent:#0284c7;--icon-bg:rgba(2,132,199,.08)">
      <div class="d-flex align-items-start justify-content-between mb-3">
        <div class="stat-card-icon" style="color:#0284c7"><i class="bi bi-calendar-event"></i></div>
      </div>
      <div class="stat-card-value"><?= $totalAgenda ?></div>
      <div class="stat-card-label">Agenda</div>
    </div>
  </div>

  <!-- Dokumen -->
  <div class="col-6 col-md-4 col-xl-2">
    <div class="stat-card h-100" style="--card-accent:#d97706;--icon-bg:rgba(217,119,6,.08)">
      <div class="d-flex align-items-start justify-content-between mb-3">
        <div class="stat-card-icon" style="color:#d97706"><i class="bi bi-folder2-open"></i></div>
      </div>
      <div class="stat-card-value"><?= $totalDokumen ?></div>
      <div class="stat-card-label">Dokumen</div>
    </div>
  </div>

  <!-- Program Kerja -->
  <div class="col-6 col-md-4 col-xl-2">
    <div class="stat-card h-100" style="--card-accent:#16a34a;--icon-bg:rgba(22,163,74,.08)">
      <div class="d-flex align-items-start justify-content-between mb-3">
        <div class="stat-card-icon" style="color:#16a34a"><i class="bi bi-clipboard2-check"></i></div>
      </div>
      <div class="stat-card-value"><?= $totalProgram ?></div>
      <div class="stat-card-label">Program</div>
    </div>
  </div>

  <!-- Pengembangan Diri -->
  <div class="col-6 col-md-4 col-xl-2">
    <div class="stat-card h-100" style="--card-accent:#7c3aed;--icon-bg:rgba(124,58,237,.08)">
      <div class="d-flex align-items-start justify-content-between mb-3">
        <div class="stat-card-icon" style="color:#7c3aed"><i class="bi bi-award"></i></div>
      </div>
      <div class="stat-card-value"><?= $totalPengembangan ?></div>
      <div class="stat-card-label">Pengembangan</div>
    </div>
  </div>
</div>

<!-- CHARTS ROW -->
<div class="row g-3 mb-4">
  <!-- Bar chart kegiatan -->
  <div class="col-lg-8">
    <div class="card h-100">
      <div class="card-header">
        <span class="card-header-title">
          <i class="bi bi-bar-chart-fill text-primary"></i>
          Kegiatan Pendampingan (6 Bulan Terakhir)
        </span>
      </div>
      <div class="card-body">
        <canvas id="chartKegiatan" style="max-height:260px"></canvas>
      </div>
    </div>
  </div>

  <!-- Pie chart sekolah -->
  <div class="col-lg-4">
    <div class="card h-100">
      <div class="card-header">
        <span class="card-header-title">
          <i class="bi bi-pie-chart-fill text-danger"></i>
          Jenis Sekolah
        </span>
      </div>
      <div class="card-body d-flex flex-column align-items-center justify-content-center">
        <canvas id="chartSekolah" style="max-height:200px;max-width:200px"></canvas>
        <div class="d-flex gap-3 mt-3 flex-wrap justify-content-center">
          <?php foreach($sekolahJenis as $sj): ?>
          <div class="d-flex align-items-center gap-2" style="font-size:.8rem">
            <div style="width:10px;height:10px;border-radius:50%;background:<?= $sj['jenis']==='SMP Negeri' ? '#1a3a6b' : '#c0392b' ?>"></div>
            <span><?= e($sj['jenis']) ?> (<?= $sj['jml'] ?>)</span>
          </div>
          <?php endforeach; ?>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- TABEL ROW -->
<div class="row g-3">
  <!-- Agenda mendatang -->
  <div class="col-lg-5">
    <div class="card">
      <div class="card-header">
        <span class="card-header-title">
          <i class="bi bi-calendar-check text-info"></i>
          Agenda Mendatang
        </span>
        <a href="<?= BASE_URL ?>/modules/agenda/index.php" class="btn btn-sm btn-outline-primary">Lihat Semua</a>
      </div>
      <div class="card-body p-0">
        <?php if (empty($agendaMendatang)): ?>
        <div class="text-center py-4 text-muted"><i class="bi bi-calendar-x fs-3 d-block mb-2"></i>Tidak ada agenda mendatang</div>
        <?php else: ?>
        <div class="list-group list-group-flush">
          <?php foreach($agendaMendatang as $ag): ?>
          <div class="list-group-item border-0 py-2 px-3">
            <div class="d-flex justify-content-between align-items-start gap-2">
              <div>
                <div class="fw-600 mb-1" style="font-size:.87rem"><?= e($ag['nama_kegiatan']) ?></div>
                <div class="text-muted" style="font-size:.76rem">
                  <i class="bi bi-geo-alt me-1"></i><?= e($ag['tempat']) ?>
                </div>
              </div>
              <div class="text-end flex-shrink-0">
                <span class="badge bg-primary-subtle text-primary" style="font-size:.7rem">
                  <?= formatTanggal($ag['tanggal'], 'd M') ?>
                </span>
              </div>
            </div>
          </div>
          <?php endforeach; ?>
        </div>
        <?php endif; ?>
      </div>
    </div>
  </div>

  <!-- Kegiatan terbaru -->
  <div class="col-lg-7">
    <div class="card">
      <div class="card-header">
        <span class="card-header-title">
          <i class="bi bi-journal-check text-success"></i>
          Kegiatan Pendampingan Terbaru
        </span>
        <a href="<?= BASE_URL ?>/modules/kegiatan/index.php" class="btn btn-sm btn-outline-primary">Lihat Semua</a>
      </div>
      <div class="table-responsive">
        <table class="table table-hover mb-0">
          <thead>
            <tr>
              <th>Tanggal</th>
              <th>Sekolah</th>
              <th>Kegiatan</th>
              <th>Status</th>
            </tr>
          </thead>
          <tbody>
            <?php if(empty($kegiatanTerbaru)): ?>
            <tr><td colspan="4" class="text-center text-muted py-4">Belum ada kegiatan</td></tr>
            <?php else: ?>
            <?php foreach($kegiatanTerbaru as $k): ?>
            <tr>
              <td style="white-space:nowrap"><?= formatTanggal($k['tanggal_kegiatan'],'d M Y') ?></td>
              <td><?= e(mb_strimwidth($k['nama_sekolah'],0,30,'…')) ?></td>
              <td><?= e(mb_strimwidth($k['nama_kegiatan'],0,35,'…')) ?></td>
              <td>
                <?php
                $statusClass = ['Draft'=>'secondary','Terkirim'=>'info','Disetujui'=>'success'];
                $sc = $statusClass[$k['status']] ?? 'secondary';
                ?>
                <span class="badge bg-<?= $sc ?>-subtle text-<?= $sc ?>"><?= e($k['status']) ?></span>
              </td>
            </tr>
            <?php endforeach; ?>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>

<?php
// Siapkan data chart JS
$chartLabels  = json_encode(array_column($kegiatanBulan, 'bulan'));
$chartData    = json_encode(array_column($kegiatanBulan, 'jml'));
$pieLabels    = json_encode(array_column($sekolahJenis, 'jenis'));
$pieData      = json_encode(array_column($sekolahJenis, 'jml'));

$extraJs = <<<JS
<script>
// Bar Chart Kegiatan
new Chart(document.getElementById('chartKegiatan'), {
  type: 'bar',
  data: {
    labels: {$chartLabels},
    datasets: [{
      label: 'Jumlah Kegiatan',
      data: {$chartData},
      backgroundColor: 'rgba(26,58,107,.75)',
      borderColor: '#1a3a6b',
      borderWidth: 2,
      borderRadius: 6,
    }]
  },
  options: {
    responsive: true, maintainAspectRatio: true,
    plugins: { legend: { display: false } },
    scales: {
      y: { beginAtZero: true, ticks: { stepSize: 1 }, grid: { color: '#e2e8f0' } },
      x: { grid: { display: false } }
    }
  }
});

// Pie Chart Sekolah
new Chart(document.getElementById('chartSekolah'), {
  type: 'doughnut',
  data: {
    labels: {$pieLabels},
    datasets: [{
      data: {$pieData},
      backgroundColor: ['#1a3a6b','#c0392b','#0284c7','#16a34a'],
      borderWidth: 0,
    }]
  },
  options: {
    responsive: true, maintainAspectRatio: true,
    plugins: { legend: { display: false } },
    cutout: '65%',
  }
});
</script>
JS;

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