<?php
require_once __DIR__ . '/_layout.php';
if (($_GET['action'] ?? '') === 'logout') logout();

// Handle approve/reject
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $act = $_POST['action'] ?? '';
    $uid = (int)($_POST['user_id'] ?? 0);
    if ($act === 'approve' && $uid) {
        $u = fetch("SELECT * FROM kkn_users WHERE id=?", [$uid]);
        if ($u && $u['status'] === 'pending') {
            $pd = json_decode($u['password'], true);
            if (is_array($pd) && isset($pd['pending'])) {
                $hashed = password_hash($pd['password_plain'], PASSWORD_BCRYPT);
                query("UPDATE kkn_users SET password=?, status='active', token=NULL, token_expires=NULL WHERE id=?", [$hashed, $uid]);
                if ($u['role'] === 'dpl') {
                    query("UPDATE kkn_dpl SET user_id=?, email=? WHERE nidn=?", [$uid, $u['email'], $pd['nidn']]);
                } else {
                    $ex = fetch("SELECT id FROM kkn_mahasiswa WHERE user_id=?", [$uid]);
                    if (!$ex) insert("INSERT INTO kkn_mahasiswa (user_id,nama,nim,prodi,email,kecamatan,kabupaten,dpl_id) VALUES (?,?,?,?,?,?,?,?)",
                        [$uid,$pd['nama'],$pd['nim'],$pd['prodi'],$u['email'],$pd['kecamatan'],$pd['kabupaten'],$pd['dpl_id']]);
                }
                $ok = 'Akun <strong>'.htmlspecialchars($pd['nama']).'</strong> berhasil diaktifkan.';
            } else {
                query("UPDATE kkn_users SET status='active' WHERE id=?", [$uid]);
                $ok = 'Akun berhasil diaktifkan.';
            }
        } else {
            query("UPDATE kkn_users SET status='active' WHERE id=?", [$uid]);
            $ok = 'Akun berhasil diaktifkan.';
        }
    } elseif ($act === 'reject' && $uid) {
        query("UPDATE kkn_users SET status='nonactive' WHERE id=?", [$uid]);
        $ok = 'Akun dinonaktifkan.';
    } elseif ($act === 'save_evaluasi') {
        $isi = trim($_POST['isi_evaluasi'] ?? '');
        if ($isi !== '') {
            $existing = fetch("SELECT setting_value FROM kkn_settings WHERE setting_key='kkn_catatan_evaluasi'");
            $arr = $existing ? (json_decode($existing['setting_value'], true) ?? []) : [];
            $arr[] = [
                'id'  => uniqid(),
                'isi' => $isi,
                'by'  => 'Admin LPPM',
                'at'  => date('Y-m-d H:i:s'),
            ];
            $json = json_encode($arr, JSON_UNESCAPED_UNICODE);
            query("INSERT INTO kkn_settings (setting_key, setting_value) VALUES ('kkn_catatan_evaluasi',?)
                   ON DUPLICATE KEY UPDATE setting_value=?", [$json, $json]);
            $ok_eval = 'Catatan evaluasi berhasil disimpan.';
        }
    } elseif ($act === 'del_evaluasi') {
        $del_id = $_POST['del_id'] ?? '';
        $existing = fetch("SELECT setting_value FROM kkn_settings WHERE setting_key='kkn_catatan_evaluasi'");
        $arr = $existing ? (json_decode($existing['setting_value'], true) ?? []) : [];
        $arr = array_values(array_filter($arr, fn($x) => $x['id'] !== $del_id));
        $json = json_encode($arr, JSON_UNESCAPED_UNICODE);
        query("INSERT INTO kkn_settings (setting_key, setting_value) VALUES ('kkn_catatan_evaluasi',?)
               ON DUPLICATE KEY UPDATE setting_value=?", [$json, $json]);
        $del_ok = true;
    }
}

$page = $_GET['page'] ?? 'home';

// Cek tabel luaran
$tbl_luaran     = fetch("SHOW TABLES LIKE 'kkn_luaran'");
$tbl_luaran_kel = fetch("SHOW TABLES LIKE 'kkn_luaran_kelompok'");

// Export CSV
if ($page === 'luaran_ind' && isset($_GET['export'])) {
    if (!$tbl_luaran) { echo 'Tabel belum ada.'; exit; }
    $rows = fetchAll("SELECT m.nama,m.nim,m.prodi,d.kecamatan,d.kabupaten,d.nama as nama_dpl,
        MAX(CASE WHEN l.jenis='artikel_jurnal' THEN l.judul END) as j_jurnal,
        MAX(CASE WHEN l.jenis='artikel_jurnal' THEN l.filename END) as f_jurnal,
        MAX(CASE WHEN l.jenis='artikel_media' THEN l.judul END) as j_media,
        MAX(CASE WHEN l.jenis='artikel_media' THEN l.filename END) as f_media
        FROM kkn_mahasiswa m LEFT JOIN kkn_dpl d ON d.id=m.dpl_id
        LEFT JOIN kkn_luaran l ON l.mahasiswa_id=m.id
        GROUP BY m.id ORDER BY d.kecamatan,m.nama");
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=luaran_individu_'.date('Ymd').'.csv');
    echo "\xEF\xBB\xBF";
    echo "No,Nama,NIM,Prodi,Kecamatan,Kabupaten,DPL,Judul Jurnal,Status Jurnal,Judul Media,Status Media\n";
    $no=1;
    foreach($rows as $r) {
        echo implode(',',[$no++,'"'.str_replace('"','""',$r['nama']).'"','"'.$r['nim'].'"',
            '"'.str_replace('"','""',$r['prodi']).'"','"'.$r['kecamatan'].'"','"'.$r['kabupaten'].'"',
            '"'.str_replace('"','""',$r['nama_dpl']).'"',
            '"'.str_replace('"','""',($r['j_jurnal']??'')).'"',$r['f_jurnal']?'Sudah':'Belum',
            '"'.str_replace('"','""',($r['j_media']??'')).'"',$r['f_media']?'Sudah':'Belum'])."\n";
    }
    exit;
}
if ($page === 'luaran_kel' && isset($_GET['export'])) {
    if (!$tbl_luaran_kel) { echo 'Tabel belum ada.'; exit; }
    $rows = fetchAll("SELECT d.kecamatan,d.kabupaten,d.nama as nama_dpl,
        MAX(CASE WHEN lk.jenis='rpk' THEN lk.judul END) as j_rpk,
        MAX(CASE WHEN lk.jenis='rpk' THEN lk.link_url END) as f_rpk,
        MAX(CASE WHEN lk.jenis='laporan' THEN lk.judul END) as j_lap,
        MAX(CASE WHEN lk.jenis='laporan' THEN lk.link_url END) as f_lap,
        MAX(CASE WHEN lk.jenis='poster' THEN lk.judul END) as j_pos,
        MAX(CASE WHEN lk.jenis='poster' THEN lk.link_url END) as f_pos,
        MAX(CASE WHEN lk.jenis='video' THEN lk.judul END) as j_vid,
        MAX(CASE WHEN lk.jenis='video' THEN lk.link_url END) as l_vid
        FROM kkn_dpl d LEFT JOIN kkn_luaran_kelompok lk ON lk.dpl_id=d.id
        GROUP BY d.id ORDER BY d.kecamatan");
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=luaran_kelompok_'.date('Ymd').'.csv');
    echo "\xEF\xBB\xBF";
    echo "No,Kecamatan,Kabupaten,DPL,Judul RPK,St.RPK,Judul Laporan,St.Laporan,Judul Poster,St.Poster,Judul Video,St.Video\n";
    $no=1;
    foreach($rows as $r) {
        echo implode(',',[$no++,'"'.$r['kecamatan'].'"','"'.$r['kabupaten'].'"',
            '"'.str_replace('"','""',$r['nama_dpl']).'"',
            '"'.str_replace('"','""',($r['j_rpk']??'')).'"',$r['f_rpk']?'Sudah':'Belum',
            '"'.str_replace('"','""',($r['j_lap']??'')).'"',$r['f_lap']?'Sudah':'Belum',
            '"'.str_replace('"','""',($r['j_pos']??'')).'"',$r['f_pos']?'Sudah':'Belum',
            '"'.str_replace('"','""',($r['j_vid']??'')).'"',$r['l_vid']?'Ada Link':'Belum'])."\n";
    }
    exit;
}

// Stats
$total_mhs     = fetch("SELECT COUNT(*) as n FROM kkn_mahasiswa")['n'];
$total_dpl     = fetch("SELECT COUNT(*) as n FROM kkn_dpl")['n'];
$total_aktif   = fetch("SELECT COUNT(*) as n FROM kkn_users WHERE status='active' AND role!='admin'")['n'];
$total_pending = fetch("SELECT COUNT(*) as n FROM kkn_users WHERE status='pending'")['n'];
$total_logbook = fetch("SELECT COUNT(DISTINCT mahasiswa_id) as n FROM kkn_logbook")['n'];

// ── Handle Save Template Download ────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_template'])) {
    $tpl_keys = ['kkn_tpl_artikel_pengabdian','kkn_tpl_laporan_kelompok','kkn_tpl_rpk','kkn_tpl_laporan_kel_tegal','kkn_tpl_lembar_penilaian'];
    foreach($tpl_keys as $k) {
        if (isset($_POST[$k])) {
            $link = trim($_POST[$k]);
            query("INSERT INTO kkn_settings (setting_key, setting_value) VALUES (?,?) ON DUPLICATE KEY UPDATE setting_value=?",
                [$k, $link, $link]);
        }
    }
    $ok = 'Link template berhasil disimpan.';
}

// ── Handle Save Narasumber ───────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_narasumber'])) {
    $judul = trim($_POST['narasumber_judul'] ?? '');
    $link  = trim($_POST['narasumber_link'] ?? '');
    if ($judul && $link) {
        $existing = fetch("SELECT setting_value FROM kkn_settings WHERE setting_key='kkn_narasumber_files'");
        $arr = $existing ? (json_decode($existing['setting_value'], true) ?? []) : [];
        $arr[] = ['id' => uniqid(), 'judul' => $judul, 'link' => $link, 'at' => date('Y-m-d H:i:s')];
        $json = json_encode($arr, JSON_UNESCAPED_UNICODE);
        query("INSERT INTO kkn_settings (setting_key, setting_value) VALUES ('kkn_narasumber_files',?)
               ON DUPLICATE KEY UPDATE setting_value=?", [$json, $json]);
        $ok_narasumber = 'File berhasil ditambahkan.';
    }
}
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['del_narasumber'])) {
    $del_id = $_POST['del_narasumber_id'] ?? '';
    $existing = fetch("SELECT setting_value FROM kkn_settings WHERE setting_key='kkn_narasumber_files'");
    $arr = $existing ? (json_decode($existing['setting_value'], true) ?? []) : [];
    $arr = array_values(array_filter($arr, fn($x) => $x['id'] !== $del_id));
    $json = json_encode($arr, JSON_UNESCAPED_UNICODE);
    query("INSERT INTO kkn_settings (setting_key, setting_value) VALUES ('kkn_narasumber_files',?)
           ON DUPLICATE KEY UPDATE setting_value=?", [$json, $json]);
    $ok_narasumber = 'File berhasil dihapus.';
}

// ── Handle Save Sertifikat ───────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_sertifikat'])) {
    $link = trim($_POST['link_sertifikat'] ?? '');
    query("INSERT INTO kkn_settings (setting_key, setting_value) VALUES ('kkn_sertifikat_link_global',?)
           ON DUPLICATE KEY UPDATE setting_value=?", [$link, $link]);
    $ok_sert = $link ? 'Link folder sertifikat berhasil disimpan.' : 'Link folder sertifikat dihapus.';
}

dashHeader('Dashboard Admin', 'admin', $user);
// Sembunyikan "Kembali ke Website" khusus dashboard admin
echo '<style>.sidebar-footer a:first-child{display:none!important;}</style>';
dashNav([
    ['page'=>'home',      'icon'=>'<i class="ti ti-home" aria-hidden="true"></i>',         'label'=>'Dashboard'],
    ['section'=>'PENGGUNA'],
    ['page'=>'users',     'icon'=>'<i class="ti ti-users" aria-hidden="true"></i>',        'label'=>'Semua Pengguna'],
    ['page'=>'pending',   'icon'=>'<i class="ti ti-clock" aria-hidden="true"></i>',        'label'=>'Menunggu Aktivasi'],
    ['page'=>'dpl',       'icon'=>'<i class="ti ti-school" aria-hidden="true"></i>',       'label'=>'Data DPL'],
    ['page'=>'mhs',       'icon'=>'<i class="ti ti-user" aria-hidden="true"></i>','label'=>'Data Mahasiswa'],
    ['page'=>'belum_daftar','icon'=>'<i class="ti ti-user-x" aria-hidden="true"></i>',  'label'=>'Belum Daftar'],
    ['section'=>'PROGRAM KERJA'],
    ['page'=>'rekap_proker_ind','icon'=>'<i class="ti ti-user" aria-hidden="true"></i>',    'label'=>'Proker Individu'],
    ['page'=>'rekap_proker_kel','icon'=>'<i class="ti ti-users" aria-hidden="true"></i>',   'label'=>'Proker Kelompok'],
    ['section'=>'LAPORAN'],
    ['page'=>'logbook',   'icon'=>'<i class="ti ti-notebook" aria-hidden="true"></i>',     'label'=>'Semua Logbook'],
    ['page'=>'nilai',     'icon'=>'<i class="ti ti-chart-bar" aria-hidden="true"></i>',    'label'=>'Rekap Nilai'],
    ['section'=>'LUARAN'],
    ['page'=>'luaran_ind','icon'=>'<i class="ti ti-file-text" aria-hidden="true"></i>',   'label'=>'Luaran Individu'],
    ['page'=>'luaran_kel','icon'=>'<i class="ti ti-users" aria-hidden="true"></i>',        'label'=>'Luaran Kelompok'],
    ['section'=>'SERTIFIKAT'],
    ['page'=>'sertifikat','icon'=>'<i class="ti ti-certificate" aria-hidden="true"></i>',  'label'=>'Sertifikat KKN'],
    ['page'=>'template',  'icon'=>'<i class="ti ti-download" aria-hidden="true"></i>',     'label'=>'Download'],
]);
dashFooter();
dashTopbar(['home'=>'Dashboard Admin','users'=>'Semua Pengguna','pending'=>'Menunggu Aktivasi',
    'dpl'=>'Data DPL','mhs'=>'Data Mahasiswa','logbook'=>'Semua Logbook','nilai'=>'Rekap Nilai',
    'luaran_ind'=>'Luaran Individu','luaran_kel'=>'Luaran Kelompok','sertifikat'=>'Sertifikat KKN','template'=>'Download','belum_daftar'=>'Mahasiswa Belum Daftar',
    'rekap_proker_ind'=>'Rekap Program Kerja Individu',
    'rekap_proker_kel'=>'Rekap Program Kerja Kelompok'][$page] ?? 'Dashboard');

if (isset($ok)): ?>
<div class="alert alert-success"><i class="ti ti-check" aria-hidden="true"></i> <?= $ok ?></div>
<?php endif; ?>

<?php if ($page === 'home'): ?>
<div class="stat-grid">
  <div class="stat-card"><div class="num"><?= $total_mhs ?></div><div class="lbl">Total Mahasiswa</div></div>
  <div class="stat-card"><div class="num"><?= $total_dpl ?></div><div class="lbl">DPL Terdaftar</div></div>
  <div class="stat-card"><div class="num"><?= $total_aktif ?></div><div class="lbl">Akun Aktif</div></div>
  <div class="stat-card"><div class="num"><?= $total_pending ?></div><div class="lbl">Menunggu Aktivasi</div></div>
  <div class="stat-card"><div class="num"><?= $total_logbook ?></div><div class="lbl">Mahasiswa Input Logbook</div></div>
</div>

<?php
// ── Catatan Evaluasi ──────────────────────────────────────────
$eval_raw = fetch("SELECT setting_value FROM kkn_settings WHERE setting_key='kkn_catatan_evaluasi'");
$eval_list = $eval_raw ? (json_decode($eval_raw['setting_value'], true) ?? []) : [];
if (isset($ok_eval)): ?>
<div class="alert alert-success" style="margin-top:1rem;"><i class="ti ti-check" aria-hidden="true"></i> <?= $ok_eval ?></div>
<?php endif; ?>
<div class="card" style="margin-top:1.25rem;">
  <div class="card-header" style="display:flex;align-items:center;justify-content:space-between;padding:1rem 1.75rem;">
    <h3 style="margin:0;"><i class="ti ti-notes" aria-hidden="true"></i> Catatan Evaluasi KKN <?= date('Y') ?></h3>
    <span id="eval-count" style="font-size:.75rem;color:#8A96A8;font-weight:400;"><?= count($eval_list) ?> catatan tersimpan</span>
  </div>
  <div class="card-body" style="padding:1.75rem;">
    <p style="font-size:.82rem;color:#64748b;margin:0 0 1.25rem;">
      Catat hal-hal yang perlu diperbaiki, diperhatikan, atau dipertahankan untuk penyelenggaraan KKN tahun berikutnya.
    </p>
    <!-- Form tambah catatan -->
    <form method="POST" style="margin-bottom:1.25rem;">
      <input type="hidden" name="action" value="save_evaluasi">
      <div style="display:flex;gap:.625rem;align-items:flex-start;">
        <textarea name="isi_evaluasi" rows="3" placeholder="Tulis catatan evaluasi… (misal: Batas waktu upload sertifikat perlu diperpanjang, DPL kesulitan akses karena email tidak terverifikasi, dst.)"
          style="flex:1;padding:.5rem .75rem;border:1px solid #CBD5E0;border-radius:8px;font-size:.85rem;resize:vertical;font-family:inherit;"></textarea>
        <button type="submit" class="btn" style="background:#0D2E5C;color:#fff;border-color:#0D2E5C;white-space:nowrap;align-self:stretch;">
          <i class="ti ti-plus" aria-hidden="true"></i> Simpan
        </button>
      </div>
    </form>
    <!-- Daftar catatan -->
    <?php if ($eval_list): ?>
    <div id="eval-list" style="display:flex;flex-direction:column;gap:.625rem;">
      <?php foreach (array_reverse($eval_list) as $ev): ?>
      <div id="eval-item-<?= htmlspecialchars($ev['id']) ?>" style="background:#F7F9FC;border:1px solid #E2E8F0;border-radius:8px;padding:1rem 1.25rem;display:flex;gap:.75rem;align-items:flex-start;">
        <div style="flex:1;">
          <div style="font-size:.88rem;color:#1A202C;line-height:1.5;"><?= nl2br(htmlspecialchars($ev['isi'])) ?></div>
          <div style="font-size:.72rem;color:#8A96A8;margin-top:.375rem;">
            <i class="ti ti-user" aria-hidden="true"></i> <?= htmlspecialchars($ev['by']) ?> &nbsp;·&nbsp;
            <i class="ti ti-calendar" aria-hidden="true"></i> <?= date('d M Y, H:i', strtotime($ev['at'])) ?>
          </div>
        </div>
        <button onclick="delEval('<?= htmlspecialchars($ev['id']) ?>')" style="background:none;border:none;color:#C53030;cursor:pointer;padding:2px 4px;font-size:.8rem;flex-shrink:0;" title="Hapus">
          <i class="ti ti-trash" aria-hidden="true"></i>
        </button>
      </div>
      <?php endforeach; ?>
    </div>
    <?php else: ?>
    <div style="text-align:center;padding:1.5rem;color:#A0AEC0;font-size:.85rem;">
      <i class="ti ti-clipboard" style="font-size:2rem;display:block;margin-bottom:.5rem;" aria-hidden="true"></i>
      Belum ada catatan evaluasi. Tambahkan catatan pertama Anda di atas.
    </div>
    <?php endif; ?>
  </div>
</div>

<?php
$pendings = fetchAll("SELECT * FROM kkn_users WHERE status='pending' ORDER BY created_at DESC");
if ($pendings):
?>
<div class="card" style="margin-top:1.25rem;">
  <div class="card-header"><h3><i class="ti ti-clock" aria-hidden="true"></i> Menunggu Aktivasi (<?= count($pendings) ?>)</h3></div>
  <div class="card-body" style="padding:0">
    <table>
      <tr><th>Nama/Username</th><th>Email</th><th>Role</th><th>Tanggal</th><th>Aksi</th></tr>
      <?php foreach ($pendings as $u):
        $pd = json_decode($u['password'], true);
        $nama = is_array($pd) ? ($pd['nama'] ?? $u['username']) : $u['username'];
      ?>
      <tr>
        <td><strong><?= htmlspecialchars($nama) ?></strong><br><small style="color:#8A96A8"><?= $u['username'] ?></small></td>
        <td><?= htmlspecialchars($u['email']) ?></td>
        <td><span class="badge badge-<?= $u['role']==='dpl'?'dpl':'mhs' ?>"><?= strtoupper($u['role']) ?></span></td>
        <td><?= date('d M Y', strtotime($u['created_at'])) ?></td>
        <td style="display:flex;gap:6px;">
          <form method="POST" style="display:inline">
            <input type="hidden" name="user_id" value="<?= $u['id'] ?>">
            <input type="hidden" name="action" value="approve">
            <button class="btn btn-sm" style="background:#276749;color:#fff;border-color:#276749;"><i class="ti ti-check" aria-hidden="true"></i> Aktifkan</button>
          </form>
          <form method="POST" style="display:inline">
            <input type="hidden" name="user_id" value="<?= $u['id'] ?>">
            <input type="hidden" name="action" value="reject">
            <button class="btn btn-sm btn-danger"><i class="ti ti-x" aria-hidden="true"></i> Tolak</button>
          </form>
        </td>
      </tr>
      <?php endforeach; ?>
    </table>
  </div>
</div>
<?php endif; ?>
<script>
function delEval(id) {
  if (!confirm('Hapus catatan ini?')) return;
  var fd = new FormData();
  fd.append('action', 'del_evaluasi');
  fd.append('del_id', id);
  fetch(window.location.href, { method: 'POST', body: fd })
    .then(function() {
      var el = document.getElementById('eval-item-' + id);
      if (el) {
        el.style.transition = 'opacity .25s';
        el.style.opacity = '0';
        setTimeout(function() {
          el.remove();
          var items = document.querySelectorAll('[id^="eval-item-"]');
          var c = document.getElementById('eval-count');
          if (c) c.textContent = items.length + ' catatan tersimpan';
          if (!items.length) {
            var list = document.getElementById('eval-list');
            if (list) list.innerHTML = '<div style="text-align:center;padding:2rem 1rem;color:#A0AEC0;font-size:.85rem;"><i class="ti ti-clipboard" style="font-size:2rem;display:block;margin-bottom:.5rem;" aria-hidden="true"></i>Belum ada catatan evaluasi.</div>';
          }
        }, 280);
      }
    });
}
</script>

<?php elseif ($page === 'pending'): ?>
<?php $pendings = fetchAll("SELECT * FROM kkn_users WHERE status='pending' ORDER BY created_at DESC"); ?>
<div class="card">
  <div class="card-header"><h3><i class="ti ti-clock" aria-hidden="true"></i> Menunggu Aktivasi (<?= count($pendings) ?>)</h3></div>
  <div class="card-body" style="padding:0">
    <table>
      <tr><th>Nama/Username</th><th>Email</th><th>Role</th><th>Tanggal</th><th>Aksi</th></tr>
      <?php foreach ($pendings as $u):
        $pd = json_decode($u['password'], true);
        $nama = is_array($pd) ? ($pd['nama'] ?? $u['username']) : $u['username'];
      ?>
      <tr>
        <td><strong><?= htmlspecialchars($nama) ?></strong><br><small style="color:#8A96A8"><?= $u['username'] ?></small></td>
        <td><?= htmlspecialchars($u['email']) ?></td>
        <td><span class="badge badge-<?= $u['role']==='dpl'?'dpl':'mhs' ?>"><?= strtoupper($u['role']) ?></span></td>
        <td><?= date('d M Y', strtotime($u['created_at'])) ?></td>
        <td style="display:flex;gap:6px;">
          <form method="POST" style="display:inline">
            <input type="hidden" name="user_id" value="<?= $u['id'] ?>">
            <input type="hidden" name="action" value="approve">
            <button class="btn btn-sm" style="background:#276749;color:#fff;border-color:#276749;"><i class="ti ti-check" aria-hidden="true"></i> Aktifkan</button>
          </form>
          <form method="POST" style="display:inline">
            <input type="hidden" name="user_id" value="<?= $u['id'] ?>">
            <input type="hidden" name="action" value="reject">
            <button class="btn btn-sm btn-danger"><i class="ti ti-x" aria-hidden="true"></i> Tolak</button>
          </form>
        </td>
      </tr>
      <?php endforeach; ?>
    </table>
  </div>
</div>

<?php elseif ($page === 'users'): ?>
<?php $users = fetchAll("SELECT u.*, COALESCE(d.nama,m.nama) as nama_lengkap FROM kkn_users u LEFT JOIN kkn_dpl d ON d.user_id=u.id LEFT JOIN kkn_mahasiswa m ON m.user_id=u.id WHERE u.role!='admin' ORDER BY u.role,u.created_at DESC"); ?>
<div class="card">
  <div class="card-header"><h3><i class="ti ti-users" aria-hidden="true"></i> Semua Pengguna (<?= count($users) ?>)</h3></div>
  <div class="card-body" style="padding:0">
    <table>
      <tr><th>Nama</th><th>Username</th><th>Email</th><th>Role</th><th>Status</th><th>Login Terakhir</th><th>Aksi</th></tr>
      <?php foreach ($users as $u): ?>
      <tr>
        <td><?= htmlspecialchars($u['nama_lengkap']??'-') ?></td>
        <td><small><?= $u['username'] ?></small></td>
        <td><small><?= htmlspecialchars($u['email']) ?></small></td>
        <td><span class="badge badge-<?= $u['role']==='dpl'?'dpl':'mhs' ?>"><?= strtoupper($u['role']) ?></span></td>
        <td><span class="badge badge-<?= $u['status']==='active'?'active':($u['status']==='pending'?'pending':'nonactive') ?>"><?= $u['status'] ?></span></td>
        <td><small><?= $u['last_login'] ? date('d M Y', strtotime($u['last_login'])) : '-' ?></small></td>
        <td>
          <form method="POST" style="display:inline">
            <input type="hidden" name="user_id" value="<?= $u['id'] ?>">
            <input type="hidden" name="action" value="<?= $u['status']==='active'?'reject':'approve' ?>">
            <button class="btn btn-sm" style="font-size:.75rem;"><?= $u['status']==='active'?'Nonaktif':'Aktifkan' ?></button>
          </form>
        </td>
      </tr>
      <?php endforeach; ?>
    </table>
  </div>
</div>

<?php elseif ($page === 'dpl'): ?>
<?php $dpls = fetchAll("SELECT d.*, u.status, u.email as user_email, COUNT(m.id) as jml_mhs FROM kkn_dpl d LEFT JOIN kkn_users u ON u.id=d.user_id LEFT JOIN kkn_mahasiswa m ON m.dpl_id=d.id GROUP BY d.id ORDER BY d.kecamatan"); ?>
<div class="card">
  <div class="card-header"><h3><i class="ti ti-school" aria-hidden="true"></i> Data DPL (<?= count($dpls) ?>)</h3></div>
  <div class="card-body" style="padding:0">
    <table>
      <tr><th>Nama DPL</th><th>NIDN</th><th>Kecamatan</th><th>Kabupaten</th><th>Email</th><th>Status</th><th>Mhs</th></tr>
      <?php foreach ($dpls as $d): ?>
      <tr>
        <td><strong><?= htmlspecialchars($d['nama']) ?></strong></td>
        <td><?= $d['nidn'] ?></td>
        <td><?= $d['kecamatan'] ?></td>
        <td><?= $d['kabupaten'] ?></td>
        <td><small><?= htmlspecialchars($d['user_email']??$d['email']??'-') ?></small></td>
        <td><?php if($d['user_id']): ?><span class="badge badge-<?= $d['status']==='active'?'active':'pending' ?>"><?= $d['status'] ?></span><?php else: ?><span style="color:#8A96A8;font-size:.78rem;">Belum daftar</span><?php endif; ?></td>
        <td style="text-align:center;"><?= $d['jml_mhs'] ?></td>
      </tr>
      <?php endforeach; ?>
    </table>
  </div>
</div>

<?php elseif ($page === 'mhs'): ?>
<?php $mhs = fetchAll("SELECT m.*, d.nama as nama_dpl FROM kkn_mahasiswa m LEFT JOIN kkn_dpl d ON d.id=m.dpl_id ORDER BY d.kecamatan,m.nama"); ?>
<div class="card">
  <div class="card-header"><h3><i class="ti ti-user" aria-hidden="true"></i> Data Mahasiswa (<?= count($mhs) ?>)</h3></div>
  <div class="card-body" style="padding:0">
    <table>
      <tr><th>Nama</th><th>NIM</th><th>Prodi</th><th>Kecamatan</th><th>DPL</th></tr>
      <?php foreach ($mhs as $m): ?>
      <tr>
        <td><strong><?= htmlspecialchars($m['nama']) ?></strong></td>
        <td><?= $m['nim'] ?></td>
        <td><?= htmlspecialchars($m['prodi']) ?></td>
        <td><?= $m['kecamatan'] ?></td>
        <td><small><?= htmlspecialchars($m['nama_dpl']??'-') ?></small></td>
      </tr>
      <?php endforeach; ?>
    </table>
  </div>
</div>

<?php elseif ($page === 'logbook'): ?>
<?php $logs = fetchAll("SELECT l.*, m.nama, m.nim, d.kecamatan FROM kkn_logbook l JOIN kkn_mahasiswa m ON m.id=l.mahasiswa_id JOIN kkn_dpl d ON d.id=m.dpl_id ORDER BY d.kecamatan,m.nama,l.minggu,l.kegiatan_no"); ?>
<div class="card">
  <div class="card-header"><h3><i class="ti ti-notebook" aria-hidden="true"></i> Semua Logbook (<?= count($logs) ?> kegiatan)</h3></div>
  <div class="card-body" style="padding:0">
    <table>
      <tr><th>Nama/NIM</th><th>Kecamatan</th><th>Minggu</th><th>Kegiatan</th><th>Tanggal</th><th>Bukti</th></tr>
      <?php foreach ($logs as $l): ?>
      <tr>
        <td><strong><?= htmlspecialchars($l['nama']) ?></strong><br><small><?= $l['nim'] ?></small></td>
        <td><?= $l['kecamatan'] ?></td>
        <td style="text-align:center;"><?= $l['minggu'] ?></td>
        <td><?= htmlspecialchars($l['nama_kegiatan']) ?></td>
        <td><small><?= $l['waktu'] ?: '-' ?></small></td>
        <td><?= $l['bukti_link'] ? '<a href="'.htmlspecialchars($l['bukti_link']).'" target="_blank" style="color:#1A56A4;font-size:.78rem;">Lihat</a>' : '-' ?></td>
      </tr>
      <?php endforeach; ?>
    </table>
  </div>
</div>

<?php elseif ($page === 'nilai'): ?>
<?php
if (isset($_GET['export'])) {
    $rows = fetchAll("SELECT m.nama,m.nim,m.prodi,m.kecamatan,d.nama as nama_dpl,p.nilai_k1,p.nilai_k2,p.nilai_k3,p.nilai_k4,p.nilai_k5,p.nilai_akhir FROM kkn_mahasiswa m LEFT JOIN kkn_dpl d ON d.id=m.dpl_id LEFT JOIN kkn_penilaian p ON p.mahasiswa_id=m.id ORDER BY m.kecamatan,m.nama");
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=rekap_nilai_'.date('Ymd').'.csv');
    echo "\xEF\xBB\xBF";
    echo "No,Nama,NIM,Prodi,Kecamatan,DPL,K1,K2,K3,K4,K5,Nilai Akhir\n";
    $no=1;
    foreach($rows as $r) echo implode(',',[$no++,'"'.str_replace('"','""',$r['nama']).'"','"'.$r['nim'].'"','"'.str_replace('"','""',$r['prodi']).'"','"'.$r['kecamatan'].'"','"'.str_replace('"','""',$r['nama_dpl']).'"',$r['nilai_k1']??'',$r['nilai_k2']??'',$r['nilai_k3']??'',$r['nilai_k4']??'',$r['nilai_k5']??'',$r['nilai_akhir']??''])."\n";
    exit;
}
$nilai = fetchAll("SELECT m.nama,m.nim,m.prodi,m.kecamatan,m.kabupaten,d.nama as nama_dpl,p.nilai_k1,p.nilai_k2,p.nilai_k3,p.nilai_k4,p.nilai_k5,p.nilai_akhir,p.catatan FROM kkn_mahasiswa m LEFT JOIN kkn_dpl d ON d.id=m.dpl_id LEFT JOIN kkn_penilaian p ON p.mahasiswa_id=m.id ORDER BY m.kecamatan,m.nama");
?>
<div class="card">
  <div class="card-header">
    <h3><i class="ti ti-chart-bar" aria-hidden="true"></i> Rekap Nilai Akhir</h3>
    <a href="?page=nilai&export=1" class="btn btn-gold btn-sm"><i class="ti ti-download" aria-hidden="true"></i> Export CSV</a>
  </div>
  <div class="card-body" style="padding:0">
    <table>
      <tr><th>Nama</th><th>NIM</th><th>Prodi</th><th>Kecamatan / DPL</th><th>K1</th><th>K2</th><th>K3</th><th>K4</th><th>K5</th><th>Akhir</th></tr>
      <?php foreach ($nilai as $n): ?>
      <tr>
        <td style="vertical-align:top;"><?= htmlspecialchars($n['nama']) ?></td>
        <td style="vertical-align:top;"><?= $n['nim'] ?></td>
        <td style="vertical-align:top;"><?= htmlspecialchars($n['prodi']) ?></td>
        <td style="vertical-align:top;"><?= $n['kecamatan'] ?><br><small style="color:#8A96A8;"><?= htmlspecialchars($n['nama_dpl']??'-') ?></small></td>
        <td style="vertical-align:top;"><?= $n['nilai_k1']??'-' ?></td>
        <td><?= $n['nilai_k2']??'-' ?></td>
        <td><?= $n['nilai_k3']??'-' ?></td>
        <td><?= $n['nilai_k4']??'-' ?></td>
        <td><?= $n['nilai_k5']??'-' ?></td>
        <td><strong style="color:<?= ($n['nilai_akhir']??0)>=75?'#276749':'#C53030' ?>"><?= $n['nilai_akhir']??'-' ?></strong></td>
      </tr>
      <?php endforeach; ?>
    </table>
  </div>
</div>

<?php elseif ($page === 'luaran_ind'): ?>
<?php
if (!$tbl_luaran) { echo '<div class="card"><div class="card-body" style="padding:1.5rem;color:#8A96A8;">Tabel luaran belum dibuat. Jalankan SQL di phpMyAdmin.</div></div>'; dashClose(); exit; }
$all_mhs_adm = fetchAll("SELECT m.*,d.kecamatan,d.nama as nama_dpl FROM kkn_mahasiswa m LEFT JOIN kkn_dpl d ON d.id=m.dpl_id ORDER BY d.kecamatan,m.nama");
$all_luaran  = fetchAll("SELECT l.*,m.id as mhs_id FROM kkn_luaran l JOIN kkn_mahasiswa m ON m.id=l.mahasiswa_id");
$lu_by_mhs = [];
foreach ($all_luaran as $l) $lu_by_mhs[$l['mhs_id']][$l['jenis']] = $l;
?>
<div class="card">
  <div class="card-header">
    <h3><i class="ti ti-file-text" aria-hidden="true"></i> Luaran Individu (<?= count($all_mhs_adm) ?> mahasiswa)</h3>
    <a href="<?= BASE_URL ?>/kkn-system/dashboard/export-luaran-ind.php" class="btn btn-gold btn-sm"><i class="ti ti-download" aria-hidden="true"></i> Export CSV</a>
  </div>
  <div class="card-body" style="padding:0">
    <table>
      <tr><th>Nama/NIM</th><th>Kecamatan / DPL</th><th style="text-align:center">Artikel Jurnal</th><th style="text-align:center">Artikel Media</th><th>Tgl Input</th></tr>
      <?php foreach ($all_mhs_adm as $m): $lu = $lu_by_mhs[$m['id']] ?? []; ?>
      <tr>
        <td style="vertical-align:top;"><strong><?= htmlspecialchars($m['nama']) ?></strong><br><small style="color:#8A96A8"><?= $m['nim'] ?></small></td>
        <td style="vertical-align:top;"><?= $m['kecamatan'] ?><br><small style="color:#8A96A8"><?= htmlspecialchars($m['nama_dpl']??'-') ?></small></td>
        <td style="text-align:center;vertical-align:top;">
          <?php if(isset($lu['artikel_jurnal'])): $lj=$lu['artikel_jurnal']; ?>
            <?php if(!empty($lj['link_url'])): ?><a href="<?= htmlspecialchars($lj['link_url']) ?>" target="_blank" style="color:#1A56A4;font-size:.8rem;"><i class="ti ti-external-link"></i> Buka</a><?php elseif(!empty($lj['filename'])): ?><a href="<?= BASE_URL ?>/kkn-system/uploads/luaran/<?= $lj['filename'] ?>" target="_blank" style="color:#1A56A4;font-size:.8rem;"><i class="ti ti-download"></i> Unduh</a><?php endif; ?>
          <?php else: ?><span style="color:#D1D5DB">—</span><?php endif; ?>
        </td>
        <td style="text-align:center;vertical-align:top;">
          <?php if(isset($lu['artikel_media'])): $lm=$lu['artikel_media']; ?>
            <?php if(!empty($lm['link_url'])): ?><a href="<?= htmlspecialchars($lm['link_url']) ?>" target="_blank" style="color:#1A56A4;font-size:.8rem;"><i class="ti ti-external-link"></i> Buka</a><?php elseif(!empty($lm['filename'])): ?><a href="<?= BASE_URL ?>/kkn-system/uploads/luaran/<?= $lm['filename'] ?>" target="_blank" style="color:#1A56A4;font-size:.8rem;"><i class="ti ti-download"></i> Unduh</a><?php endif; ?>
          <?php else: ?><span style="color:#D1D5DB">—</span><?php endif; ?>
        </td>
        <td style="vertical-align:top;font-size:.72rem;color:#8A96A8;">
          <?php $tgl = $lu['artikel_jurnal']['uploaded_at'] ?? ($lu['artikel_media']['uploaded_at'] ?? null); ?>
          <?php if($tgl): ?><span style="display:block;"><?= date('d M Y', strtotime($tgl)) ?></span><span style="display:block;color:#A0AEC0;"><?= date('H:i', strtotime($tgl)) ?></span><?php else: ?>—<?php endif; ?>
        </td>
      </tr>
      <?php endforeach; ?>
    </table>
  </div>
</div>

<?php elseif ($page === 'luaran_kel'): ?>
<?php
if (!$tbl_luaran_kel) { echo '<div class="card"><div class="card-body" style="padding:1.5rem;color:#8A96A8;">Tabel luaran kelompok belum dibuat. Jalankan SQL di phpMyAdmin.</div></div>'; dashClose(); exit; }
$all_dpl_adm = fetchAll("SELECT * FROM kkn_dpl ORDER BY kecamatan");
$all_lk      = fetchAll("SELECT lk.*, m.nama as input_nama, m.nim as input_nim FROM kkn_luaran_kelompok lk LEFT JOIN kkn_mahasiswa m ON m.id=lk.ketua_id");
$lk_by_dpl = [];
foreach ($all_lk as $lk) $lk_by_dpl[$lk['dpl_id']][$lk['jenis']] = $lk;
?>
<div class="card">
  <div class="card-header">
    <h3><i class="ti ti-users" aria-hidden="true"></i> Luaran Kelompok (<?= count($all_dpl_adm) ?> kelompok)</h3>
    <a href="<?= BASE_URL ?>/kkn-system/dashboard/export-luaran-kel.php" class="btn btn-gold btn-sm"><i class="ti ti-download" aria-hidden="true"></i> Export CSV</a>
  </div>
  <div class="card-body" style="padding:0">
    <table>
      <tr><th>Kecamatan/DPL</th><th style="text-align:center">RPK</th><th style="text-align:center">Laporan</th><th style="text-align:center">Poster</th><th style="text-align:center">Video</th><th>Diinput oleh</th><th>Tgl Input</th></tr>
      <?php foreach ($all_dpl_adm as $d): $items = $lk_by_dpl[$d['id']] ?? []; ?>
      <tr>
        <td><strong><?= $d['kecamatan'] ?>, <?= $d['kabupaten'] ?></strong><br><small style="color:#8A96A8"><?= htmlspecialchars($d['nama']) ?></small></td>
        <?php foreach (['rpk','laporan','poster','video'] as $j): $it = $items[$j] ?? null; ?>
        <td style="text-align:center">
          <?php if ($it && $it['filename']): ?>
          <a href="<?= BASE_URL ?>/kkn-system/uploads/luaran/<?= $it['filename'] ?>" target="_blank" style="color:#1A56A4;font-size:.78rem;"><i class="ti ti-download"></i></a>
          <?php elseif ($it && $it['link_url']): ?>
          <a href="<?= htmlspecialchars($it['link_url']) ?>" target="_blank" style="color:#1A56A4;font-size:.78rem;"><i class="ti ti-external-link"></i></a>
          <?php else: ?><span style="color:#D1D5DB;font-size:.78rem;">—</span><?php endif; ?>
        </td>
        <?php endforeach; ?>
        <td style="font-size:.72rem;color:#8A96A8;vertical-align:top;">
          <?php
          $any = array_filter($items ?? [], fn($x) => !empty($x['input_nama']));
          if ($any) {
              $inp = reset($any);
              echo htmlspecialchars($inp['input_nama']);
              if (!empty($inp['input_nim'])) echo '<br><span style="color:#A0AEC0;">'.$inp['input_nim'].'</span>';
          } else { echo '—'; }
          ?>
        </td>
        <td style="font-size:.72rem;color:#8A96A8;vertical-align:top;">
          <?php
          $tgl_kel = null;
          foreach($items ?? [] as $it) {
              if (!empty($it['uploaded_at'])) { $tgl_kel = $it['uploaded_at']; break; }
          }
          if($tgl_kel): ?>
          <span style="display:block;"><?= date('d M Y', strtotime($tgl_kel)) ?></span>
          <span style="display:block;color:#A0AEC0;"><?= date('H:i', strtotime($tgl_kel)) ?></span>
          <?php else: ?>—<?php endif; ?>
        </td>
      </tr>
      <?php endforeach; ?>
    </table>
  </div>
</div>

<?php elseif ($page === 'belum_daftar'): ?>
<?php
$upload_result = null;
$belum_daftar  = [];
$sudah_daftar  = [];

// Hapus data session jika diminta
if (isset($_GET['reset_data'])) {
    unset($_SESSION['kkn_master_data']);
    header('Location: ?page=belum_daftar');
    exit;
}

// Load dari session jika ada
if (!empty($_SESSION['kkn_master_data'])) {
    $saved = $_SESSION['kkn_master_data'];
    $rows  = $saved['rows'];
    // Re-proses dengan data DB terbaru
    $mhs_db = fetchAll("SELECT m.nim, m.nama, m.prodi, m.kecamatan, m.kabupaten, d.nama as nama_dpl
                        FROM kkn_mahasiswa m LEFT JOIN kkn_dpl d ON d.id=m.dpl_id");
    $mhs_by_nim = [];
    foreach ($mhs_db as $m) $mhs_by_nim[$m['nim']] = $m;
    foreach ($rows as $r) {
        $nim = $r['nim'];
        if (!isset($mhs_by_nim[$nim])) {
            $belum_daftar[] = $r;
        } else {
            $db = $mhs_by_nim[$nim];
            $kec_ok = strtolower(trim($db['kecamatan'])) === strtolower(trim($r['kecamatan']));
            $kab_ok = strtolower(trim($db['kabupaten'])) === strtolower(trim($r['kabupaten']));
            $r['db_kecamatan'] = $db['kecamatan'];
            $r['db_kabupaten'] = $db['kabupaten'];
            $r['db_nama']      = $db['nama'];
            $r['db_prodi']     = $db['prodi'];
            $r['db_dpl']       = $db['nama_dpl'];
            $r['kec_ok']       = $kec_ok;
            $r['kab_ok']       = $kab_ok;
            $r['sesuai']       = $kec_ok && $kab_ok;
            $sudah_daftar[]    = $r;
        }
    }
    $tidak_sesuai  = array_filter($sudah_daftar, fn($r) => !$r['sesuai']);
    $upload_result = 'ok';
    $upload_msg    = count($rows) . ' data master tersimpan: <strong>' . count($belum_daftar) . ' belum daftar</strong>, '
                   . count($sudah_daftar) . ' sudah terdaftar'
                   . (count($tidak_sesuai) ? ', <strong style="color:#C53030">' . count($tidak_sesuai) . ' tidak sesuai kelompok</strong>' : ', semua kelompok sesuai') . '.';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['csv_file']) && $_FILES['csv_file']['error'] === 0 && empty($upload_result)) {
    $ext  = strtolower(pathinfo($_FILES['csv_file']['name'], PATHINFO_EXTENSION));
    $rows = [];
    if ($ext === 'csv') {
        if (($h = fopen($_FILES['csv_file']['tmp_name'], 'r')) !== false) {
            $first_line = fgets($h);
            rewind($h);
            $sep = (substr_count($first_line, "\t") > substr_count($first_line, ",")) ? "\t" : ",";
            fgetcsv($h, 0, $sep);
            while (($row = fgetcsv($h, 0, $sep)) !== false) {
                if (count($row) >= 2 && trim($row[0]) !== '') {
                    $is_no_col = is_numeric(trim($row[0])) && strlen(trim($row[0])) <= 4;
                    $c = $is_no_col ? 1 : 0;
                    if (empty(trim($row[$c] ?? ''))) continue;
                    $rows[] = [
                        'no'        => $is_no_col ? trim($row[0]) : '',
                        'nim'       => trim($row[$c]   ?? ''),
                        'nama'      => trim($row[$c+1] ?? ''),
                        'prodi'     => trim($row[$c+2] ?? ''),
                        'kecamatan' => trim($row[$c+3] ?? ''),
                        'kabupaten' => trim($row[$c+4] ?? ''),
                        'dpl_nama'  => trim($row[$c+5] ?? ''),
                    ];
                }
            }
            fclose($h);
        }
    }

    if (empty($rows)) {
        $upload_result = 'error';
        $upload_msg    = 'File kosong atau format tidak sesuai.';
    } else {
        // Ambil semua data mahasiswa dari database
        $mhs_db = fetchAll("SELECT m.nim, m.nama, m.prodi, m.kecamatan, m.kabupaten, d.nama as nama_dpl
                            FROM kkn_mahasiswa m LEFT JOIN kkn_dpl d ON d.id=m.dpl_id");
        $mhs_by_nim = [];
        foreach ($mhs_db as $m) $mhs_by_nim[$m['nim']] = $m;

        foreach ($rows as $r) {
            $nim = $r['nim'];
            if (!isset($mhs_by_nim[$nim])) {
                $belum_daftar[] = $r;
            } else {
                $db = $mhs_by_nim[$nim];
                // Cek kesesuaian kecamatan & kabupaten
                $kec_ok = strtolower(trim($db['kecamatan'])) === strtolower(trim($r['kecamatan']));
                $kab_ok = strtolower(trim($db['kabupaten'])) === strtolower(trim($r['kabupaten']));
                $r['db_kecamatan'] = $db['kecamatan'];
                $r['db_kabupaten'] = $db['kabupaten'];
                $r['db_nama']      = $db['nama'];
                $r['db_prodi']     = $db['prodi'];
                $r['db_dpl']       = $db['nama_dpl'];
                $r['kec_ok']       = $kec_ok;
                $r['kab_ok']       = $kab_ok;
                $r['sesuai']       = $kec_ok && $kab_ok;
                $sudah_daftar[]    = $r;
            }
        }
        $tidak_sesuai = array_filter($sudah_daftar, fn($r) => !$r['sesuai']);
        $upload_result = 'ok';
        $upload_msg    = count($rows) . ' data diproses: <strong>' . count($belum_daftar) . ' belum daftar</strong>, '
                       . count($sudah_daftar) . ' sudah terdaftar'
                       . (count($tidak_sesuai) ? ', <strong style="color:#C53030">' . count($tidak_sesuai) . ' tidak sesuai kelompok</strong>' : ', semua kelompok sesuai') . '.';
        // Simpan ke session
        $_SESSION['kkn_master_data'] = ['rows' => $rows, 'uploaded_at' => date('d M Y H:i')];
    }
}
?>
<div style="max-width:800px;">
  <!-- Form Upload -->
  <div class="card" style="margin-bottom:1.25rem;">
    <div class="card-header"><h3><i class="ti ti-upload" aria-hidden="true"></i> Upload Data Peserta KKN</h3></div>
    <div class="card-body" style="padding:1.25rem 1.5rem;">
      <div style="background:#E8F0FB;border-radius:8px;padding:.875rem 1rem;margin-bottom:1.25rem;font-size:.8rem;color:#0D2E5C;line-height:1.6;">
        <strong><i class="ti ti-info-circle"></i> Format file CSV:</strong>
        Kolom: No | NIM | Nama | Prodi | Kecamatan | Kabupaten | DPL. Baris pertama = header (diabaikan). Salin langsung dari Excel data peserta KKN.
        <?php if(!empty($_SESSION['kkn_master_data'])): ?>
        <div style="margin-top:.5rem;color:#276749;"><i class="ti ti-check"></i> Data master tersimpan sejak <?= $_SESSION['kkn_master_data']['uploaded_at'] ?>.
        <a href="?page=belum_daftar&reset_data=1" style="color:#C53030;margin-left:8px;font-weight:600;"><i class="ti ti-refresh"></i> Ganti Data</a></div>
        <?php endif; ?>
      </div>
      <?php if($upload_result): ?>
      <div class="alert alert-<?= $upload_result==='ok'?'success':'error' ?>">
        <i class="ti ti-<?= $upload_result==='ok'?'check':'alert-circle' ?>"></i> <?= $upload_msg ?>
      </div>
      <?php endif; ?>
      <?php if(empty($_SESSION['kkn_master_data'])): ?>
      <form method="POST" enctype="multipart/form-data">
        <div class="form-group">
          <label style="font-size:.8rem;font-weight:600;">Pilih File CSV</label>
          <input type="file" name="csv_file" accept=".csv" required>
        </div>
        <button type="submit" class="btn btn-gold"><i class="ti ti-search"></i> Cek & Tampilkan</button>
      </form>
      <?php endif; ?>
    </div>
  </div>

  <?php if($upload_result === 'ok'): ?>
  <!-- Hasil: Belum Daftar -->
  <div class="card" style="margin-bottom:1.25rem;">
    <div class="card-header">
      <h3><i class="ti ti-user-x" style="color:#C53030;" aria-hidden="true"></i> Belum Daftar
        <span style="background:#C53030;color:#fff;padding:2px 10px;border-radius:20px;font-size:.7rem;margin-left:6px;"><?= count($belum_daftar) ?></span>
      </h3>
      <?php if($belum_daftar): ?>
      <form method="POST" action="<?= BASE_URL ?>/kkn-system/dashboard/export-belum-daftar.php" style="display:inline;" target="_blank">
        <input type="hidden" name="export_json" value="<?= htmlspecialchars(json_encode($belum_daftar)) ?>">
        <button type="submit" class="btn btn-sm btn-gold"><i class="ti ti-download"></i> Export CSV</button>
      </form>
      <?php endif; ?>
    </div>
    <?php if($belum_daftar): ?>
    <div class="card-body" style="padding:0;">
      <table>
        <tr><th>#</th><th>NIM</th><th>Nama Mahasiswa</th><th>Status</th></tr>
        <?php foreach($belum_daftar as $i=>$r): ?>
        <tr>
          <td style="color:#8A96A8;"><?= $i+1 ?></td>
          <td style="font-family:monospace;"><?= htmlspecialchars($r['nim']) ?></td>
          <td><?= htmlspecialchars($r['nama']) ?></td>
          <td><span style="background:#FFF5F5;color:#C53030;padding:2px 9px;border-radius:20px;font-size:.7rem;font-weight:700;">Belum Daftar</span></td>
        </tr>
        <?php endforeach; ?>
      </table>
    </div>
    <?php else: ?>
    <div style="padding:2rem;text-align:center;color:#276749;font-size:.88rem;">
      <i class="ti ti-circle-check" style="font-size:2rem;display:block;margin-bottom:.5rem;"></i>
      Semua mahasiswa sudah terdaftar!
    </div>
    <?php endif; ?>
  </div>

  <!-- Hasil: Sudah Daftar -->
  <div class="card">
    <div class="card-header">
      <h3><i class="ti ti-user-check" style="color:#276749;" aria-hidden="true"></i> Sudah Terdaftar
        <span style="background:#276749;color:#fff;padding:2px 10px;border-radius:20px;font-size:.7rem;margin-left:6px;"><?= count($sudah_daftar) ?></span>
      </h3>
    </div>
    <?php if($sudah_daftar): ?>
    <div class="card-body" style="padding:0;">
      <table>
        <tr><th>#</th><th>NIM</th><th>Nama</th><th>Kecamatan (Master)</th><th>Kecamatan (DB)</th><th>Kelompok</th></tr>
        <?php foreach($sudah_daftar as $i=>$r): ?>
        <tr style="<?= !$r['sesuai'] ? 'background:#FFF5F5;' : '' ?>">
          <td style="color:#8A96A8;"><?= $i+1 ?></td>
          <td style="font-family:monospace;font-size:.72rem;"><?= htmlspecialchars($r['nim']) ?></td>
          <td>
            <div style="font-size:.78rem;font-weight:600;"><?= htmlspecialchars($r['db_nama']) ?></div>
            <div style="font-size:.68rem;color:#8A96A8;"><?= htmlspecialchars($r['db_prodi']) ?></div>
          </td>
          <td style="font-size:.75rem;"><?= htmlspecialchars($r['kecamatan']) ?>, <?= htmlspecialchars($r['kabupaten']) ?></td>
          <td style="font-size:.75rem;">
            <span style="color:<?= $r['kec_ok']?'#276749':'#C53030' ?>;"><?= htmlspecialchars($r['db_kecamatan']) ?></span>,
            <span style="color:<?= $r['kab_ok']?'#276749':'#C53030' ?>;"><?= htmlspecialchars($r['db_kabupaten']) ?></span>
          </td>
          <td>
            <?php if($r['sesuai']): ?>
            <span style="background:#F0FFF4;color:#276749;padding:2px 9px;border-radius:20px;font-size:.7rem;font-weight:700;">✓ Sesuai</span>
            <?php else: ?>
            <span style="background:#FFF5F5;color:#C53030;padding:2px 9px;border-radius:20px;font-size:.7rem;font-weight:700;">✗ Tidak Sesuai</span>
            <?php endif; ?>
          </td>
        </tr>
        <?php endforeach; ?>
      </table>
    </div>
    <?php endif; ?>
  </div>

  <!-- Export hidden form -->
  <form id="export-form" method="POST" enctype="multipart/form-data" style="display:none;">
    <input type="hidden" name="export_data" value="<?= htmlspecialchars(json_encode($belum_daftar)) ?>">
  </form>
  <script>
  function exportBelumDaftar() {
    var data = <?= json_encode($belum_daftar) ?>;
    var csv = '﻿No,NIM,Nama,Prodi,Kecamatan,Kabupaten,DPL
';
    data.forEach(function(r, i){
      csv += (i+1)+',"'+r.nim+'","'+r.nama+'","'+r.prodi+'","'+r.kecamatan+'","'+r.kabupaten+'","'+r.dpl_nama+'"
';
    });
    var a = document.createElement('a');
    a.href = 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv);
    a.download = 'belum_daftar_kkn.csv';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
  }
  </script>
  <?php endif; ?>
</div>

<?php elseif ($page === 'template'): ?>
<?php
$tpl_data = [
    'kkn_tpl_rpk'                => 'Template RPK (Rencana Program Kerja)',
    'kkn_tpl_artikel_pengabdian' => 'Template Artikel Pengabdian',
    'kkn_tpl_laporan_kelompok'   => 'Template Laporan Kelompok',
    'kkn_tpl_laporan_kel_tegal'  => 'Template Laporan Kelompok (Tegal)',
    'kkn_tpl_lembar_penilaian'   => 'Template Lembar Penilaian Desa',
];
$tpl_links = [];
foreach($tpl_data as $k => $label) {
    $row = fetch("SELECT setting_value FROM kkn_settings WHERE setting_key=?", [$k]);
    $tpl_links[$k] = $row['setting_value'] ?? '';
}
?>
<div style="max-width:700px;">

  <!-- ── Materi Narasumber ─────────────────────────────── -->
  <div class="card" style="margin-bottom:1.25rem;">
    <div class="card-header" style="display:flex;align-items:center;justify-content:space-between;">
      <h3><i class="ti ti-file-upload" aria-hidden="true"></i> Materi Narasumber</h3>
      <span style="font-size:.72rem;color:#8A96A8;" id="ns-count"></span>
    </div>
    <div class="card-body" style="padding:1.25rem 1.5rem;">
      <?php if(isset($ok_narasumber)): ?><div class="alert alert-success" style="margin-bottom:1rem;"><i class="ti ti-check"></i> <?= htmlspecialchars($ok_narasumber) ?></div><?php endif; ?>
      <!-- Form tambah -->
      <form method="POST" style="margin-bottom:1.25rem;">
        <div style="display:grid;grid-template-columns:1fr 1fr auto;gap:.625rem;align-items:flex-end;">
          <div class="form-group" style="margin:0;">
            <label style="font-size:.74rem;font-weight:600;color:#444;">Judul / Nama File</label>
            <input type="text" name="narasumber_judul" placeholder="Contoh: Materi Pelatihan UMKM Digital" required>
          </div>
          <div class="form-group" style="margin:0;">
            <label style="font-size:.74rem;font-weight:600;color:#444;">Link Google Drive</label>
            <input type="url" name="narasumber_link" placeholder="https://drive.google.com/..." required>
          </div>
          <button type="submit" name="save_narasumber" class="btn btn-gold" style="height:38px;white-space:nowrap;">
            <i class="ti ti-plus" aria-hidden="true"></i> Tambah
          </button>
        </div>
      </form>
      <!-- Daftar file -->
      <?php
      $ns_raw = fetch("SELECT setting_value FROM kkn_settings WHERE setting_key='kkn_narasumber_files'");
      $ns_list = $ns_raw ? (json_decode($ns_raw['setting_value'], true) ?? []) : [];
      ?>
      <?php if($ns_list): ?>
      <div style="display:flex;flex-direction:column;gap:.5rem;" id="ns-list">
        <?php foreach(array_reverse($ns_list) as $ns): ?>
        <div style="background:#F7F9FC;border:1px solid #E2E8F0;border-radius:8px;padding:.75rem 1rem;display:flex;align-items:center;gap:.75rem;">
          <i class="ti ti-file-description" style="color:#1A56A4;font-size:1.1rem;flex-shrink:0;" aria-hidden="true"></i>
          <div style="flex:1;">
            <div style="font-size:.8rem;font-weight:600;color:#0D2E5C;"><?= htmlspecialchars($ns['judul']) ?></div>
            <a href="<?= htmlspecialchars($ns['link']) ?>" target="_blank" style="font-size:.7rem;color:#1A56A4;">
              <i class="ti ti-external-link" style="font-size:.7rem;"></i> Buka Link
            </a>
            <span style="font-size:.68rem;color:#A0AEC0;margin-left:.5rem;"><?= date('d M Y, H:i', strtotime($ns['at'])) ?></span>
          </div>
          <form method="POST" onsubmit="return confirm('Hapus file ini?')" style="flex-shrink:0;">
            <input type="hidden" name="del_narasumber_id" value="<?= htmlspecialchars($ns['id']) ?>">
            <button type="submit" name="del_narasumber" style="background:none;border:none;color:#C53030;cursor:pointer;padding:2px 4px;">
              <i class="ti ti-trash" aria-hidden="true"></i>
            </button>
          </form>
        </div>
        <?php endforeach; ?>
      </div>
      <?php else: ?>
      <div style="text-align:center;padding:1.5rem;color:#A0AEC0;font-size:.8rem;">
        <i class="ti ti-file-off" style="font-size:2rem;display:block;margin-bottom:.5rem;" aria-hidden="true"></i>
        Belum ada file materi. Tambahkan di atas.
      </div>
      <?php endif; ?>
    </div>
  </div>

  <!-- ── Template Download ─────────────────────────────── -->
  <div class="card">
    <div class="card-header"><h3><i class="ti ti-download" aria-hidden="true"></i> Kelola Link Template Download</h3></div>
    <div class="card-body" style="padding:1.25rem 1.5rem;">
      <div style="background:#E8F0FB;border-radius:8px;padding:.875rem 1rem;margin-bottom:1.25rem;font-size:.8rem;color:#0D2E5C;line-height:1.6;">
        <i class="ti ti-info-circle"></i> Upload file template ke Google Drive → atur akses <strong>"Siapa saja yang memiliki link"</strong> → salin link → paste di bawah.
      </div>
      <form method="POST">
        <?php foreach($tpl_data as $key => $label): ?>
        <div class="form-group">
          <label style="font-size:.74rem;font-weight:600;color:#444;"><?= $label ?></label>
          <input type="url" name="<?= $key ?>" value="<?= htmlspecialchars($tpl_links[$key]) ?>" placeholder="https://drive.google.com/file/d/...">
          <?php if($tpl_links[$key]): ?>
          <div style="font-size:.72rem;color:#276749;margin-top:3px;display:flex;align-items:center;gap:4px;">
            <i class="ti ti-check"></i> Tersimpan.
            <a href="<?= htmlspecialchars($tpl_links[$key]) ?>" target="_blank" style="color:#1A56A4;margin-left:4px;">Buka <i class="ti ti-external-link" style="font-size:.7rem;"></i></a>
          </div>
          <?php else: ?>
          <div style="font-size:.72rem;color:#F59E0B;margin-top:3px;"><i class="ti ti-alert-triangle"></i> Belum diisi.</div>
          <?php endif; ?>
        </div>
        <?php endforeach; ?>
        <button type="submit" name="save_template" class="btn btn-gold" style="margin-top:.5rem;">
          <i class="ti ti-device-floppy" aria-hidden="true"></i> Simpan Semua Link
        </button>
      </form>
    </div>
  </div>
</div>

<?php elseif ($page === 'sertifikat'): ?>
<?php
$link_sert = fetch("SELECT setting_value FROM kkn_settings WHERE setting_key='kkn_sertifikat_link_global'")['setting_value'] ?? '';
if (isset($ok_sert)): ?><div class="alert alert-success"><i class="ti ti-check"></i> <?= htmlspecialchars($ok_sert) ?></div><?php endif; ?>
<div style="max-width:680px;">
  <!-- Panduan -->
  <div class="card" style="margin-bottom:1.25rem;">
    <div class="card-header"><h3><i class="ti ti-list-check" aria-hidden="true"></i> Cara Kerja</h3></div>
    <div class="card-body" style="padding:1.25rem 1.5rem;">
      <div style="display:flex;flex-direction:column;gap:.875rem;">
        <?php foreach([
          ['1','Upload semua file sertifikat ke <strong>1 folder Google Drive</strong>. Beri nama file sesuai nama mahasiswa, contoh: <strong>Kinder Boy.pdf</strong>'],
          ['2','Atur akses folder ke <strong>"Siapa saja yang memiliki link dapat melihat"</strong> agar mahasiswa bisa membuka tanpa login Google.'],
          ['3','Salin link folder dan tempel di kolom di bawah, lalu klik <strong>Simpan</strong>.'],
          ['4','Mahasiswa akan melihat tombol <strong>"Buka Folder Sertifikat"</strong> di menu Sertifikat KKN.'],
        ] as [$n,$txt]): ?>
        <div style="display:flex;gap:10px;align-items:flex-start;">
          <div style="width:26px;height:26px;background:#0D2E5C;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:.78rem;font-weight:700;color:#C8922A;flex-shrink:0;"><?= $n ?></div>
          <div style="font-size:.85rem;color:#2C3545;line-height:1.6;"><?= $txt ?></div>
        </div>
        <?php endforeach; ?>
      </div>
    </div>
  </div>
  <!-- Form input link -->
  <div class="card">
    <div class="card-header"><h3><i class="ti ti-brand-google-drive" aria-hidden="true"></i> Link Folder Sertifikat Google Drive</h3></div>
    <div class="card-body" style="padding:1.25rem 1.5rem;">
      <form method="POST">
        <div class="form-group">
          <label style="font-size:.82rem;font-weight:600;color:#444;">Link Folder Google Drive</label>
          <input type="url" name="link_sertifikat" value="<?= htmlspecialchars($link_sert) ?>" placeholder="https://drive.google.com/drive/folders/...">
          <div style="font-size:.72rem;color:#8A96A8;margin-top:4px;">
            <?php if($link_sert): ?>
            <span style="color:#276749;"><i class="ti ti-check"></i> Link sudah tersimpan.</span>
            <a href="<?= htmlspecialchars($link_sert) ?>" target="_blank" style="color:#1A56A4;margin-left:8px;">Buka folder <i class="ti ti-external-link" style="font-size:.72rem;"></i></a>
            <?php else: ?>
            <span style="color:#F59E0B;"><i class="ti ti-alert-triangle"></i> Belum ada link. Mahasiswa akan melihat pesan "Sertifikat belum tersedia".</span>
            <?php endif; ?>
          </div>
        </div>
        <button type="submit" name="save_sertifikat" class="btn btn-gold" style="margin-top:.5rem;">
          <i class="ti ti-device-floppy" aria-hidden="true"></i> Simpan Link
        </button>
      </form>
    </div>
  </div>
</div>
<?php elseif ($page === 'rekap_proker_ind'): ?>
<style>.proker-admin-table td{vertical-align:top!important;padding-top:6px;}</style>
<?php
$rekap_ind = fetchAll("SELECT pi.*, m.nama as mhs_nama, m.nim, m.prodi, d.kecamatan, d.kabupaten, d.nama as nama_dpl
    FROM kkn_proker_individu pi
    JOIN kkn_mahasiswa m ON m.id=pi.mahasiswa_id
    JOIN kkn_dpl d ON d.id=m.dpl_id
    ORDER BY pi.created_at DESC");
$total_mhs   = fetch("SELECT COUNT(*) as n FROM kkn_mahasiswa")['n'] ?? 0;
$sudah_input = count(array_unique(array_column($rekap_ind, 'mahasiswa_id')));
?>
<div style="display:grid;grid-template-columns:repeat(3,1fr);gap:1rem;margin-bottom:1.25rem;">
  <div class="stat-card"><div class="num"><?= count($rekap_ind) ?></div><div class="lbl">Total Proker Individu</div></div>
  <div class="stat-card"><div class="num"><?= $sudah_input ?></div><div class="lbl">Mahasiswa Sudah Input</div></div>
  <div class="stat-card"><div class="num"><?= $total_mhs - $sudah_input ?></div><div class="lbl">Mahasiswa Belum Input</div></div>
</div>
<div class="card">
  <div class="card-header">
    <h3><i class="ti ti-user" aria-hidden="true"></i> Rekap Program Kerja Individu</h3>
  </div>
  <div class="card-body" style="padding:0;">
    <table class="proker-admin-table">
      <colgroup>
        <col style="width:40px">
        <col style="width:16%">
        <col style="width:26%">
        <col style="width:26%">
        <col style="width:16%">
        <col style="width:12%">
      </colgroup>
      <tr><th>#</th><th>Mahasiswa</th><th>Judul Program Kerja</th><th>Sasaran Kegiatan</th><th>Target Luaran</th><th>Waktu Input</th></tr>
      <?php foreach($rekap_ind as $i=>$r): ?>
      <tr>
        <td style="color:#8A96A8;font-size:.75rem;"><?= $i+1 ?></td>
        <td >
          <div style="font-weight:600;font-size:.78rem;"><?= htmlspecialchars($r['mhs_nama']) ?></div>
          <div style="font-size:.68rem;color:#8A96A8;"><?= htmlspecialchars($r['prodi']) ?></div>
          <div style="font-size:.68rem;color:#8A96A8;">Kec. <?= htmlspecialchars($r['kecamatan']) ?></div>
        </td>
        <td style="font-size:.78rem;font-weight:600;"><?= htmlspecialchars($r['judul']) ?></td>
        <td style="font-size:.75rem;"><?= htmlspecialchars($r['target']??'-') ?></td>
        <td ><?php if($r['target_luaran']??''): ?><span style="font-size:.75rem;color:#1A56A4;font-weight:500;"><?= htmlspecialchars($r['target_luaran']) ?></span><?php else: ?>—<?php endif; ?></td>
        <td style="font-size:.72rem;color:#8A96A8;"><?php if($r['created_at']): ?><span style="display:block;"><?= date('d M Y', strtotime($r['created_at'])) ?></span><span style="display:block;color:#A0AEC0;"><?= date('H:i', strtotime($r['created_at'])) ?></span><?php else: ?>—<?php endif; ?></td>
      </tr>
      <?php endforeach; ?>
      <?php if(empty($rekap_ind)): ?>
      <tr><td colspan="7" style="text-align:center;padding:2rem;color:#8A96A8;">Belum ada program kerja individu yang diinput.</td></tr>
      <?php endif; ?>
    </table>
  </div>
</div>

<?php elseif ($page === 'rekap_proker_kel'): ?>
<style>.proker-admin-table td{vertical-align:top!important;padding-top:6px;}</style>
<?php
$rekap_kel = fetchAll("SELECT pk.*, d.kecamatan, d.kabupaten, d.nama as nama_dpl, m.nama as input_nama
    FROM kkn_proker_kelompok pk
    JOIN kkn_dpl d ON d.id=pk.dpl_id
    JOIN kkn_mahasiswa m ON m.id=pk.input_by
    ORDER BY pk.created_at DESC");
$total_dpl     = fetch("SELECT COUNT(*) as n FROM kkn_dpl")['n'] ?? 0;
$dpl_input_kel = count(array_unique(array_column($rekap_kel, 'dpl_id')));
?>
<div style="display:grid;grid-template-columns:repeat(3,1fr);gap:1rem;margin-bottom:1.25rem;">
  <div class="stat-card"><div class="num"><?= count($rekap_kel) ?></div><div class="lbl">Total Proker Kelompok</div></div>
  <div class="stat-card"><div class="num"><?= $dpl_input_kel ?></div><div class="lbl">Kelompok Sudah Input</div></div>
  <div class="stat-card"><div class="num"><?= $total_dpl - $dpl_input_kel ?></div><div class="lbl">Kelompok Belum Input</div></div>
</div>
<div class="card">
  <div class="card-header">
    <h3><i class="ti ti-users" aria-hidden="true"></i> Rekap Program Kerja Kelompok</h3>
  </div>
  <div class="card-body" style="padding:0;">
    <table class="proker-admin-table">
      <colgroup>
        <col style="width:40px">
        <col style="width:13%">
        <col style="width:24%">
        <col style="width:22%">
        <col style="width:14%">
        <col style="width:10%">
        <col style="width:10%">
      </colgroup>
      <tr><th>#</th><th>Kelompok / Lokasi</th><th>Judul Program Kerja Kelompok</th><th>Sasaran Kegiatan</th><th>Target Luaran</th><th>Diinput oleh</th><th>Waktu Input</th></tr>
      <?php foreach($rekap_kel as $i=>$r): ?>
      <tr>
        <td style="color:#8A96A8;font-size:.75rem;"><?= $i+1 ?></td>
        <td style="font-size:.75rem;">Kec. <?= htmlspecialchars($r['kecamatan']) ?><div style="font-size:.68rem;color:#8A96A8;"><?= htmlspecialchars($r['kabupaten']) ?></div></td>
        <td style="font-size:.78rem;font-weight:600;"><?= htmlspecialchars($r['judul']) ?></td>
        <td style="font-size:.75rem;"><?= htmlspecialchars($r['target']??'-') ?></td>
        <td><?php if($r['target_luaran']??''): ?><span style="font-size:.75rem;color:#1A56A4;font-weight:500;"><?= htmlspecialchars($r['target_luaran']) ?></span><?php else: ?>—<?php endif; ?></td>
        <td style="font-size:.72rem;color:#8A96A8;"><?= htmlspecialchars($r['input_nama']) ?></td>
        <td style="font-size:.72rem;color:#8A96A8;"><?php if($r['created_at']): ?><span style="display:block;"><?= date('d M Y', strtotime($r['created_at'])) ?></span><span style="display:block;color:#A0AEC0;"><?= date('H:i', strtotime($r['created_at'])) ?></span><?php else: ?>—<?php endif; ?></td>
      </tr>
      <?php endforeach; ?>
      <?php if(empty($rekap_kel)): ?>
      <tr><td colspan="7" style="text-align:center;padding:2rem;color:#8A96A8;">Belum ada program kerja kelompok yang diinput.</td></tr>
      <?php endif; ?>
    </table>
  </div>
</div>

<?php endif; ?>

<?php dashClose(); ?>
