<?php
ini_set('log_errors', 1);
ini_set('error_log', '/home/lppm/php_errors.log');
ini_set('display_errors', 0);
ob_start();
require_once __DIR__ . '/_layout.php';
if (($_GET['action'] ?? '') === 'logout') logout();
$mhs = fetch("SELECT m.*, d.nama as nama_dpl, d.kecamatan, d.kabupaten FROM kkn_mahasiswa m LEFT JOIN kkn_dpl d ON d.id=m.dpl_id WHERE m.user_id=?", [$user['id']]);
if (!$mhs) { echo '<p style="padding:2rem">Data mahasiswa tidak ditemukan. Hubungi admin LPPM.</p>'; dashClose(); exit; }
$page       = $_GET['page'] ?? 'home';
// ── Batas edit proker: (dinonaktifkan) ────────────────
$BATAS_PROKER = strtotime('2026-12-31 23:59:59 Asia/Jakarta');
$proker_locked = false;
$sisa_waktu = $BATAS_PROKER - time();
$minggu_raw = $_GET['minggu'] ?? '1';
$minggu     = ($minggu_raw === '0') ? 0 : max(1, min(6, (int)$minggu_raw));
function loadLogbook($mhs_id) {
    $result = [];
    for ($w = 1; $w <= 6; $w++) {
        $result[$w] = fetchAll("SELECT * FROM kkn_logbook WHERE mahasiswa_id=? AND minggu=? ORDER BY kegiatan_no", [$mhs_id, $w]);
    }
    return $result;
}
// Save logbook
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $page === 'logbook') {
    $minggu_post = (int)($_POST['minggu'] ?? 1);
    $jumlah      = (int)($_POST['jumlah_kegiatan'] ?? 1);
    query("DELETE FROM kkn_logbook WHERE mahasiswa_id = ? AND minggu = ?", [$mhs['id'], $minggu_post]);
    $urut = 1;
    for ($kg = 1; $kg <= ($jumlah + 20); $kg++) {
        if (!isset($_POST["nama_$kg"])) continue;
        $nama_keg = trim($_POST["nama_$kg"] ?? '');
        $waktu    = trim($_POST["waktu_$kg"] ?? '');
        $desk     = trim($_POST["desk_$kg"] ?? '');
        $bukti    = trim($_POST["bukti_$kg"] ?? '');
        $tipe     = $_POST["tipe_$kg"] ?? null;
        $pid_ind  = ($tipe==='proker_individu') ? ((int)($_POST["proker_ind_id_$kg"]??0) ?: null) : null;
        $pid_kel  = ($tipe==='proker_kelompok') ? ((int)($_POST["proker_kel_id_$kg"]??0) ?: null) : null;
        if ($nama_keg && empty($bukti)) {
            $ok = null;
            $save_error = 'Kegiatan #' . $kg . ' belum memiliki link bukti Google Drive. Semua kegiatan wajib menyertakan bukti.';
            break;
        }
        if ($nama_keg) {
            insert("INSERT INTO kkn_logbook (mahasiswa_id, minggu, kegiatan_no, nama_kegiatan, waktu, deskripsi, bukti_link, tipe_kegiatan, proker_ind_id, proker_kel_id) VALUES (?,?,?,?,?,?,?,?,?,?)",
                [$mhs['id'], $minggu_post, $urut, $nama_keg, $waktu, $desk, $bukti, $tipe ?: null, $pid_ind, $pid_kel]);
            $urut++;
        }
    }
    $ok = 'Logbook Minggu ' . $minggu_post . ' berhasil disimpan! (' . ($urut-1) . ' kegiatan)';
    $minggu = $minggu_post;
}
// ── Save Proker Individu ─────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_proker_ind'])) {
    if ($proker_locked) {
        $proker_err = 'Batas waktu input proker sudah berakhir.';
    } else {
        $judul_p        = trim($_POST['judul_proker_ind'] ?? '');
        $deskripsi_p    = trim($_POST['deskripsi_proker_ind'] ?? '');
        $target_p       = trim($_POST['target_proker_ind'] ?? '');
        $target_luaran_p= trim($_POST['target_luaran_ind'] ?? '');
        $edit_id        = (int)($_POST['edit_proker_ind_id'] ?? 0);
        if (!$judul_p) { $proker_err = 'Judul program kerja wajib diisi.'; }
        elseif (!$deskripsi_p) { $proker_err = 'Deskripsi kegiatan wajib diisi.'; }
        elseif (!$target_p) { $proker_err = 'Sasaran kegiatan wajib diisi.'; }
        elseif (!$target_luaran_p) { $proker_err = 'Target luaran wajib dipilih.'; }
        else {
            try {
                if ($edit_id) {
                    query("UPDATE kkn_proker_individu SET judul=?,deskripsi=?,target=?,target_luaran=?,updated_at=NOW() WHERE id=? AND mahasiswa_id=?",
                        [$judul_p, $deskripsi_p, $target_p, $target_luaran_p, $edit_id, $mhs['id']]);
                } else {
                    insert("INSERT INTO kkn_proker_individu (mahasiswa_id,judul,deskripsi,target,target_luaran) VALUES (?,?,?,?,?)",
                        [$mhs['id'], $judul_p, $deskripsi_p, $target_p, $target_luaran_p]);
                }
                $proker_ok = 'Program kerja individu berhasil disimpan.';
            } catch (Exception $e) {
                $proker_err = 'Gagal menyimpan: ' . $e->getMessage();
                error_log('[PROKER IND] ' . $e->getMessage());
            }
        }
    }
}
// ── Delete Proker Individu ────────────────────────────────────
if (isset($_GET['del_proker_ind']) && !$proker_locked) {
    $del_id = (int)$_GET['del_proker_ind'];
    query("DELETE FROM kkn_proker_individu WHERE id=? AND mahasiswa_id=?", [$del_id, $mhs['id']]);
    $js_redirect = '?page=proker';
}
// ── Save Proker Kelompok ──────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_proker_kel'])) {
    if ($proker_locked) {
        $proker_err = 'Batas waktu input proker sudah berakhir.';
    } elseif (empty($mhs['dpl_id'])) {
        $proker_err = 'Data DPL tidak ditemukan. Hubungi admin LPPM.';
    } else {
        $judul_pk         = trim($_POST['judul_proker_kel'] ?? '');
        $deskripsi_pk     = trim($_POST['deskripsi_proker_kel'] ?? '');
        $target_pk        = trim($_POST['target_proker_kel'] ?? '');
        $target_luaran_pk = trim($_POST['target_luaran_kel'] ?? '');
        $edit_id          = (int)($_POST['edit_proker_kel_id'] ?? 0);
        if (!$judul_pk) { $proker_err = 'Judul program kerja wajib diisi.'; }
        elseif (!$deskripsi_pk) { $proker_err = 'Deskripsi kegiatan wajib diisi.'; }
        elseif (!$target_pk) { $proker_err = 'Sasaran kegiatan wajib diisi.'; }
        elseif (!$target_luaran_pk) { $proker_err = 'Target luaran wajib dipilih.'; }
        else {
            try {
                if ($edit_id) {
                    query("UPDATE kkn_proker_kelompok SET judul=?,deskripsi=?,target=?,target_luaran=?,updated_at=NOW() WHERE id=? AND dpl_id=?",
                        [$judul_pk, $deskripsi_pk, $target_pk, $target_luaran_pk, $edit_id, $mhs['dpl_id']]);
                } else {
                    insert("INSERT INTO kkn_proker_kelompok (dpl_id,input_by,judul,deskripsi,target,target_luaran) VALUES (?,?,?,?,?,?)",
                        [$mhs['dpl_id'], $mhs['id'], $judul_pk, $deskripsi_pk, $target_pk, $target_luaran_pk]);
                }
                $proker_ok = 'Program kerja kelompok berhasil disimpan.';
            } catch (Exception $e) {
                $proker_err = 'Gagal menyimpan: ' . $e->getMessage();
                error_log('[PROKER KEL] ' . $e->getMessage());
            }
        }
    }
}
// ── Delete Proker Kelompok ────────────────────────────────────
if (isset($_GET['del_proker_kel']) && !$proker_locked) {
    $del_id = (int)$_GET['del_proker_kel'];
    query("DELETE FROM kkn_proker_kelompok WHERE id=? AND dpl_id=?", [$del_id, $mhs['dpl_id']]);
    $js_redirect = '?page=proker';
}
// ── Ganti Password ───────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ganti_password'])) {
    $pass_lama  = $_POST['pass_lama'] ?? '';
    $pass_baru  = trim($_POST['pass_baru'] ?? '');
    $pass_ulang = trim($_POST['pass_ulang'] ?? '');
    $u = fetch("SELECT password FROM kkn_users WHERE id=?", [$user['id']]);
    if (!password_verify($pass_lama, $u['password'])) { $pass_err = 'Password lama tidak sesuai.'; }
    elseif (strlen($pass_baru) < 6) { $pass_err = 'Password baru minimal 6 karakter.'; }
    elseif ($pass_baru !== $pass_ulang) { $pass_err = 'Konfirmasi password tidak cocok.'; }
    else {
        query("UPDATE kkn_users SET password=? WHERE id=?", [password_hash($pass_baru, PASSWORD_BCRYPT), $user['id']]);
        $pass_ok = 'Password berhasil diubah.';
    }
}
// ── Save/Delete Luaran Individu ───────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['del_luaran'])) {
    $jenis = $_POST['jenis_luaran'] ?? '';
    if (in_array($jenis, ['artikel_jurnal','artikel_media'])) {
        query("DELETE FROM kkn_luaran WHERE mahasiswa_id=? AND jenis=?", [$mhs['id'], $jenis]);
        $luaran_ok = 'Luaran berhasil dihapus.';
    }
}
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_luaran'])) {
    $tbl_luaran = fetch("SHOW TABLES LIKE 'kkn_luaran'");
    if ($tbl_luaran) {
        $jenis = $_POST['jenis_luaran'] ?? '';
        $judul = trim($_POST['judul_luaran'] ?? '');
        $link  = trim($_POST['link_luaran'] ?? '');
        if (!in_array($jenis, ['artikel_jurnal', 'artikel_media'])) { $upload_err = 'Jenis luaran tidak valid.'; }
        elseif (empty($judul)) { $upload_err = 'Judul luaran wajib diisi.'; }
        elseif (empty($link)) { $upload_err = 'Link Google Drive wajib diisi.'; }
        elseif (!filter_var($link, FILTER_VALIDATE_URL)) { $upload_err = 'Format link tidak valid.'; }
        else {
            $existing = fetch("SELECT id FROM kkn_luaran WHERE mahasiswa_id=? AND jenis=?", [$mhs['id'], $jenis]);
            if ($existing) {
                query("UPDATE kkn_luaran SET judul=?, link_url=?, filename=NULL, uploaded_at=NOW() WHERE mahasiswa_id=? AND jenis=?", [$judul, $link, $mhs['id'], $jenis]);
            } else {
                insert("INSERT INTO kkn_luaran (mahasiswa_id, jenis, judul, link_url, uploaded_at) VALUES (?,?,?,?,NOW())", [$mhs['id'], $jenis, $judul, $link]);
            }
            $upload_ok = 'Link luaran berhasil disimpan!';
        }
    }
}
// ── Nilai dari Desa ───────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_nilai_desa'])) {
    $tbl_nd_h = fetch("SELECT 1 FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name='kkn_nilai_desa'");
    if ($tbl_nd_h) {
        $link  = trim($_POST['nd_link']??'');
        $rows  = $_POST['nd'] ?? [];
        $saved = 0;
        foreach ($rows as $mhs_id => $val) {
            $mhs_id = (int)$mhs_id;
            $cek = fetch("SELECT id FROM kkn_mahasiswa WHERE id=? AND dpl_id=?", [$mhs_id, $mhs['dpl_id']]);
            if (!$cek) continue;
            $n1 = max(0,min(20,(int)($val['n1']??0))); $n2 = max(0,min(20,(int)($val['n2']??0)));
            $n3 = max(0,min(20,(int)($val['n3']??0))); $n4 = max(0,min(20,(int)($val['n4']??0)));
            $n5 = max(0,min(20,(int)($val['n5']??0))); $total = $n1+$n2+$n3+$n4+$n5;
            $existing = fetch("SELECT id,status FROM kkn_nilai_desa WHERE mahasiswa_id=?", [$mhs_id]);
            if ($existing) {
                if ($existing['status'] === 'disetujui') continue;
                query("UPDATE kkn_nilai_desa SET n1=?,n2=?,n3=?,n4=?,n5=?,total=?,link_bukti=?,status='pending',catatan_dpl=NULL,validated_at=NULL,input_by=?,dpl_id=?,updated_at=NOW() WHERE mahasiswa_id=?",
                    [$n1,$n2,$n3,$n4,$n5,$total,$link,$mhs['id'],$mhs['dpl_id'],$mhs_id]);
            } else {
                insert("INSERT INTO kkn_nilai_desa (dpl_id,mahasiswa_id,input_by,n1,n2,n3,n4,n5,total,link_bukti) VALUES (?,?,?,?,?,?,?,?,?,?)",
                    [$mhs['dpl_id'],$mhs_id,$mhs['id'],$n1,$n2,$n3,$n4,$n5,$total,$link]);
            }
            $saved++;
        }
        $nd_ok = "Nilai $saved anggota berhasil disimpan. Menunggu validasi DPL.";
    } else { $nd_ok = 'Fitur nilai desa belum aktif.'; }
}
// ── Save/Delete Luaran Kelompok ───────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['del_luaran_kel'])) {
    $jenis = $_POST['jenis_luaran_kel'] ?? '';
    if (in_array($jenis, ['rpk','laporan','poster','video'])) {
        query("DELETE FROM kkn_luaran_kelompok WHERE dpl_id=? AND jenis=?", [$mhs['dpl_id'], $jenis]);
        $luaran_kel_ok = 'Luaran kelompok berhasil dihapus.';
    }
}
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_luaran_kel'])) {
    $tbl_luaran_kel = fetch("SHOW TABLES LIKE 'kkn_luaran_kelompok'");
    if ($tbl_luaran_kel) {
        $jenis = $_POST['jenis_luaran_kel'] ?? '';
        $judul = trim($_POST['judul_luaran_kel'] ?? '');
        $link  = trim($_POST['link_luaran_kel'] ?? '');
        if (!in_array($jenis, ['rpk','laporan','poster','video'])) { $upload_err_kel = 'Jenis luaran tidak valid.'; }
        elseif (empty($judul)) { $upload_err_kel = 'Judul wajib diisi.'; }
        elseif (empty($link)) { $upload_err_kel = 'Link Google Drive wajib diisi.'; }
        elseif (!filter_var($link, FILTER_VALIDATE_URL)) { $upload_err_kel = 'Format link tidak valid.'; }
        else {
            $existing = fetch("SELECT id FROM kkn_luaran_kelompok WHERE dpl_id=? AND jenis=?", [$mhs['dpl_id'], $jenis]);
            if ($existing) {
                query("UPDATE kkn_luaran_kelompok SET judul=?, link_url=?, filename=NULL, ketua_id=?, uploaded_at=NOW() WHERE dpl_id=? AND jenis=?",
                    [$judul, $link, $mhs['id'], $mhs['dpl_id'], $jenis]);
            } else {
                insert("INSERT INTO kkn_luaran_kelompok (dpl_id, ketua_id, jenis, judul, link_url) VALUES (?,?,?,?,?)",
                    [$mhs['dpl_id'], $mhs['id'], $jenis, $judul, $link]);
            }
            $upload_ok_kel = 'Link luaran kelompok berhasil disimpan!';
        }
    }
}
$logbook_all = loadLogbook($mhs['id']);
$user['nim'] = $mhs['nim'] ?? '-';
dashHeader('Dashboard Mahasiswa', 'mahasiswa', $user);
dashNav([
    ['page'=>'home',       'icon'=>'<i class="ti ti-home" aria-hidden="true"></i>',          'label'=>'Dashboard'],
    ['page'=>'profil',     'icon'=>'<i class="ti ti-user" aria-hidden="true"></i>',          'label'=>'Profil Saya'],
    ['section'=>'KEGIATAN'],
    ['page'=>'proker',     'icon'=>'<i class="ti ti-clipboard-list" aria-hidden="true"></i>','label'=>'Program Kerja'],
    ['page'=>'logbook',    'icon'=>'<i class="ti ti-notebook" aria-hidden="true"></i>',      'label'=>'Logbook Mingguan'],
    ['page'=>'luaran',     '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'],
    ['page'=>'nilai',      'icon'=>'<i class="ti ti-chart-bar" aria-hidden="true"></i>',     'label'=>'Lihat Nilai'],
    ['page'=>'sertifikat', 'icon'=>'<i class="ti ti-certificate" aria-hidden="true"></i>',  'label'=>'Sertifikat KKN'],
    ['page'=>'download',   'icon'=>'<i class="ti ti-download" aria-hidden="true"></i>',      'label'=>'Download'],
]);
dashFooter();
dashTopbar(['home'=>'Dashboard Mahasiswa','logbook'=>'Logbook Kegiatan','nilai'=>'Nilai KKN',
    'proker'=>'Program Kerja','luaran'=>'Luaran Individu','luaran_kel'=>'Luaran Kelompok',
    'profil'=>'Profil Saya','sertifikat'=>'Sertifikat KKN','download'=>'Download'][$page] ?? 'Dashboard');
if (isset($ok)): ?><div class="alert alert-success"><i class="ti ti-check" aria-hidden="true"></i> <?= htmlspecialchars($ok) ?></div><?php endif; ?>
<?php if (isset($upload_ok)): ?><div class="alert alert-success"><i class="ti ti-check" aria-hidden="true"></i> <?= htmlspecialchars($upload_ok) ?></div><?php endif; ?>
<?php if (isset($upload_err)): ?><div class="alert alert-error"><i class="ti ti-alert-circle" aria-hidden="true"></i> <?= htmlspecialchars($upload_err) ?></div><?php endif; ?>
<?php if (isset($upload_ok_kel)): ?><div class="alert alert-success"><i class="ti ti-check" aria-hidden="true"></i> <?= htmlspecialchars($upload_ok_kel) ?></div><?php endif; ?>
<?php if (isset($upload_err_kel)): ?><div class="alert alert-error"><i class="ti ti-alert-circle" aria-hidden="true"></i> <?= htmlspecialchars($upload_err_kel) ?></div><?php endif; ?>
<?php /* ══════ PROGRAM KERJA ══════ */ ?>
<?php if ($page === 'proker'): ?>
<?php if (isset($proker_err)): ?><div class="alert alert-error"><i class="ti ti-alert-circle" aria-hidden="true"></i> <?= htmlspecialchars($proker_err) ?></div><?php endif; ?>
<?php if (isset($proker_ok)): ?><div class="alert alert-success"><i class="ti ti-check" aria-hidden="true"></i> <?= htmlspecialchars($proker_ok) ?></div><?php endif; ?>
<?php
$proker_ind_list = fetchAll("SELECT * FROM kkn_proker_individu WHERE mahasiswa_id=? ORDER BY created_at", [$mhs['id']]);
$proker_kel_list = fetchAll("SELECT * FROM kkn_proker_kelompok WHERE dpl_id=? ORDER BY created_at", [$mhs['dpl_id']]);
$edit_ind = isset($_GET['edit_ind']) ? fetch("SELECT * FROM kkn_proker_individu WHERE id=? AND mahasiswa_id=?", [(int)$_GET['edit_ind'], $mhs['id']]) : null;
$edit_kel = isset($_GET['edit_kel']) ? fetch("SELECT * FROM kkn_proker_kelompok WHERE id=? AND dpl_id=?", [(int)$_GET['edit_kel'], $mhs['dpl_id']]) : null;
?>
<!-- Banner terkunci -->
<?php if($proker_locked): ?>
<div style="background:#FEF3C7;border:1px solid #FDE68A;border-radius:10px;padding:12px 16px;margin-bottom:1.25rem;display:flex;align-items:center;gap:8px;font-size:.75rem;color:#92400E;">
  <i class="ti ti-lock" style="font-size:1rem;" aria-hidden="true"></i>
  <strong>Program kerja sudah terkunci.</strong> Batas waktu input telah berakhir.
</div>
<?php endif; ?>
<!-- Proker Individu -->
<div class="card" style="margin-bottom:1.25rem;">
  <div class="card-header">
    <h3><i class="ti ti-user" aria-hidden="true"></i> Program Kerja Individu</h3>
    <?php if(!$proker_locked): ?><a href="?page=proker" class="btn btn-sm btn-primary"><i class="ti ti-plus" aria-hidden="true"></i> Tambah</a><?php endif; ?>
  </div>
  <div class="card-body" style="padding:1.25rem 1.5rem;">
    <?php if($proker_ind_list): ?>
    <?php foreach($proker_ind_list as $i=>$pi): ?>
    <div style="background:#F7F9FC;border:1px solid #E2E8F0;border-radius:8px;padding:1rem 1.25rem;margin-bottom:.75rem;display:flex;justify-content:space-between;align-items:flex-start;gap:1rem;">
      <div style="flex:1;">
        <div style="font-weight:700;color:#0D2E5C;font-size:.82rem;margin-bottom:.5rem;"><?= ($i+1) ?>. <?= htmlspecialchars($pi['judul']) ?></div>
        <table style="width:100%;border-collapse:collapse;">
          <tr><td style="font-size:.73rem;color:#64748b;font-weight:600;width:90px;padding:2px 0;vertical-align:top;">Deskripsi</td><td style="font-size:.73rem;color:#64748b;padding:2px 0 2px 4px;vertical-align:top;"><?= htmlspecialchars($pi['deskripsi']??'—') ?></td></tr>
          <tr><td style="font-size:.73rem;color:#64748b;font-weight:600;width:90px;padding:2px 0;vertical-align:top;">Sasaran</td><td style="font-size:.73rem;color:#64748b;padding:2px 0 2px 4px;vertical-align:top;"><?= htmlspecialchars($pi['target']??'—') ?></td></tr>
          <tr><td style="font-size:.73rem;color:#64748b;font-weight:600;width:90px;padding:2px 0;vertical-align:top;">Target Luaran</td><td style="font-size:.73rem;color:#1A56A4;font-weight:500;padding:2px 0 2px 4px;vertical-align:top;"><?= htmlspecialchars($pi['target_luaran']??'—') ?></td></tr>
          <?php if($pi['created_at']??''): ?>
          <tr><td style="font-size:.73rem;color:#64748b;font-weight:600;width:90px;padding:2px 0;">Diinput</td><td style="font-size:.73rem;color:#64748b;padding:2px 0 2px 4px;"><?php $bln=['','Januari','Februari','Maret','April','Mei','Juni','Juli','Agustus','September','Oktober','November','Desember']; echo date('d',$ts=strtotime($pi['created_at'])).' '.$bln[(int)date('n',$ts)].' '.date('Y',$ts); ?>; Pukul <?= date('H.i', strtotime($pi['created_at'])) ?></td></tr>
          <?php endif; ?>
        </table>
      </div>
      <?php if(!$proker_locked): ?>
      <div style="display:flex;gap:5px;flex-shrink:0;">
        <a href="?page=proker&edit_ind=<?= $pi['id'] ?>" class="btn btn-sm" style="padding:4px 9px;font-size:.72rem;"><i class="ti ti-edit" aria-hidden="true"></i></a>
        <a href="?page=proker&del_proker_ind=<?= $pi['id'] ?>" class="btn btn-sm btn-danger" style="padding:4px 9px;font-size:.72rem;" onclick="return confirm('Hapus proker ini?')"><i class="ti ti-trash" aria-hidden="true"></i></a>
      </div>
      <?php endif; ?>
    </div>
    <?php endforeach; ?>
    <?php endif; ?>
    <?php if(!$proker_locked): ?>
    <div style="border-top:1px solid #F0F4F8;margin-top:1rem;padding-top:1rem;">
      <div style="font-size:.82rem;font-weight:700;color:#0D2E5C;margin-bottom:.75rem;"><?= $edit_ind ? 'Edit Program Kerja Individu' : 'Tambah Program Kerja Individu' ?></div>
      <form method="POST">
        <input type="hidden" name="save_proker_ind" value="1">
        <input type="hidden" name="edit_proker_ind_id" value="<?= $edit_ind['id'] ?? 0 ?>">
        <div class="form-group"><label>Judul Program Kerja Individu <span style="color:#e53e3e;">*</span></label><input type="text" name="judul_proker_ind" placeholder="Contoh: Pelatihan Digital Marketing UMKM" value="<?= htmlspecialchars($edit_ind['judul'] ?? '') ?>" required></div>
        <div class="form-group"><label>Deskripsi Kegiatan <span style="color:#e53e3e;">*</span></label><textarea name="deskripsi_proker_ind" rows="3" placeholder="Uraian singkat kegiatan..." required><?= htmlspecialchars($edit_ind['deskripsi'] ?? '') ?></textarea><div style="font-size:.68rem;color:#8A96A8;margin-top:4px;line-height:1.6;">50–100 kata — singkat tapi informatif.</div></div>
        <div class="form-row">
          <div class="form-group"><label>Sasaran Kegiatan <span style="color:#e53e3e;">*</span></label><input type="text" name="target_proker_ind" placeholder="Contoh: 30 pelaku UMKM" value="<?= htmlspecialchars($edit_ind['target'] ?? '') ?>" required></div>
          <div class="form-group"><label>Target Luaran <span style="color:#e53e3e;">*</span></label><input type="text" name="target_luaran_ind" value="<?= htmlspecialchars($edit_ind['target_luaran'] ?? '') ?>" placeholder="Contoh: Modul pelatihan, Aplikasi desa, dst." required></div>
        </div>
        <div style="display:flex;gap:.5rem;"><button type="submit" class="btn btn-gold"><i class="ti ti-device-floppy" aria-hidden="true"></i> Simpan</button><?php if($edit_ind): ?><a href="?page=proker" class="btn" style="background:#F5F7FA;color:#64748b;">Batal</a><?php endif; ?></div>
      </form>
    </div>
    <?php elseif(empty($proker_ind_list)): ?>
    <div style="text-align:center;padding:1.5rem;color:#8A96A8;font-size:.82rem;">Belum ada program kerja individu.</div>
    <?php endif; ?>
  </div>
</div>
<!-- Proker Kelompok -->
<div class="card">
  <div class="card-header">
    <h3><i class="ti ti-users" aria-hidden="true"></i> Program Kerja Kelompok — Kec. <?= $mhs['kecamatan'] ?></h3>
    <?php if(!$proker_locked): ?><a href="?page=proker" class="btn btn-sm btn-primary"><i class="ti ti-plus" aria-hidden="true"></i> Tambah</a><?php endif; ?>
  </div>
  <div class="card-body" style="padding:1.25rem 1.5rem;">
    <?php if($proker_kel_list): ?>
    <?php foreach($proker_kel_list as $i=>$pk): ?>
    <div style="background:#F7F9FC;border:1px solid #E2E8F0;border-radius:8px;padding:1rem 1.25rem;margin-bottom:.75rem;display:flex;justify-content:space-between;align-items:flex-start;gap:1rem;">
      <div style="flex:1;">
        <div style="font-weight:700;color:#0D2E5C;font-size:.82rem;margin-bottom:.5rem;"><?= ($i+1) ?>. <?= htmlspecialchars($pk['judul']) ?></div>
        <table style="width:100%;border-collapse:collapse;">
          <tr><td style="font-size:.73rem;color:#64748b;font-weight:600;width:90px;padding:2px 0;vertical-align:top;">Deskripsi</td><td style="font-size:.73rem;color:#64748b;padding:2px 0 2px 4px;vertical-align:top;"><?= htmlspecialchars($pk['deskripsi']??'—') ?></td></tr>
          <tr><td style="font-size:.73rem;color:#64748b;font-weight:600;width:90px;padding:2px 0;vertical-align:top;">Sasaran</td><td style="font-size:.73rem;color:#64748b;padding:2px 0 2px 4px;vertical-align:top;"><?= htmlspecialchars($pk['target']??'—') ?></td></tr>
          <tr><td style="font-size:.73rem;color:#64748b;font-weight:600;width:90px;padding:2px 0;vertical-align:top;">Target Luaran</td><td style="font-size:.73rem;color:#1A56A4;font-weight:500;padding:2px 0 2px 4px;vertical-align:top;"><?= htmlspecialchars($pk['target_luaran']??'—') ?></td></tr>
          <?php if($pk['created_at']??''): ?>
          <tr><td style="font-size:.73rem;color:#64748b;font-weight:600;width:90px;padding:2px 0;">Diinput</td><td style="font-size:.73rem;color:#64748b;padding:2px 0 2px 4px;"><?php echo date('d',$ts=strtotime($pk['created_at'])).' '.$bln[(int)date('n',$ts)].' '.date('Y',$ts); ?>; Pukul <?= date('H.i', strtotime($pk['created_at'])) ?></td></tr>
          <?php endif; ?>
        </table>
      </div>
      <?php if(!$proker_locked): ?>
      <div style="display:flex;gap:5px;flex-shrink:0;">
        <a href="?page=proker&edit_kel=<?= $pk['id'] ?>" class="btn btn-sm" style="padding:4px 9px;font-size:.72rem;"><i class="ti ti-edit" aria-hidden="true"></i></a>
        <a href="?page=proker&del_proker_kel=<?= $pk['id'] ?>" class="btn btn-sm btn-danger" style="padding:4px 9px;font-size:.72rem;" onclick="return confirm('Hapus proker ini?')"><i class="ti ti-trash" aria-hidden="true"></i></a>
      </div>
      <?php endif; ?>
    </div>
    <?php endforeach; ?>
    <?php endif; ?>
    <?php if(!$proker_locked): ?>
    <div style="border-top:1px solid #F0F4F8;margin-top:1rem;padding-top:1rem;">
      <div style="font-size:.82rem;font-weight:700;color:#0D2E5C;margin-bottom:.75rem;"><?= $edit_kel ? 'Edit Program Kerja Kelompok' : 'Tambah Program Kerja Kelompok' ?></div>
      <form method="POST">
        <input type="hidden" name="save_proker_kel" value="1">
        <input type="hidden" name="edit_proker_kel_id" value="<?= $edit_kel['id'] ?? 0 ?>">
        <div class="form-group"><label>Judul Program Kerja Kelompok <span style="color:#e53e3e;">*</span></label><input type="text" name="judul_proker_kel" placeholder="Contoh: Revitalisasi Taman Baca Desa" value="<?= htmlspecialchars($edit_kel['judul'] ?? '') ?>" required></div>
        <div class="form-group"><label>Deskripsi Kegiatan <span style="color:#e53e3e;">*</span></label><textarea name="deskripsi_proker_kel" rows="3" placeholder="Uraian singkat kegiatan kelompok..." required><?= htmlspecialchars($edit_kel['deskripsi'] ?? '') ?></textarea><div style="font-size:.68rem;color:#8A96A8;margin-top:4px;line-height:1.6;">50–100 kata — singkat tapi informatif.</div></div>
        <div class="form-row">
          <div class="form-group"><label>Sasaran Kegiatan <span style="color:#e53e3e;">*</span></label><input type="text" name="target_proker_kel" placeholder="Contoh: 30 petani Desa Moga" value="<?= htmlspecialchars($edit_kel['target'] ?? '') ?>" required></div>
          <div class="form-group"><label>Target Luaran <span style="color:#e53e3e;">*</span></label><input type="text" name="target_luaran_kel" value="<?= htmlspecialchars($edit_kel['target_luaran'] ?? '') ?>" placeholder="Contoh: Modul pelatihan, Aplikasi desa, dst." required></div>
        </div>
        <div style="display:flex;gap:.5rem;"><button type="submit" class="btn btn-gold"><i class="ti ti-device-floppy" aria-hidden="true"></i> Simpan</button><?php if($edit_kel): ?><a href="?page=proker" class="btn" style="background:#F5F7FA;color:#64748b;">Batal</a><?php endif; ?></div>
      </form>
    </div>
    <?php elseif(empty($proker_kel_list)): ?>
    <div style="text-align:center;padding:1.5rem;color:#8A96A8;font-size:.82rem;">Belum ada program kerja kelompok.</div>
    <?php endif; ?>
  </div>
</div>
<?php /* ══════ HOME ══════ */ ?>
<?php elseif ($page === 'home'): ?>
<div style="background:#fff;border-radius:12px;border:1px solid #E2E8F0;padding:1.5rem;margin-bottom:1.5rem;display:grid;grid-template-columns:1fr 1fr;gap:1rem;">
  <div><div style="font-size:.72rem;color:#8A96A8;font-weight:700;text-transform:uppercase;letter-spacing:.08em;margin-bottom:.25rem;">Nama</div><div style="font-weight:700;color:#0D2E5C;"><?= htmlspecialchars($mhs['nama']) ?></div></div>
  <div><div style="font-size:.72rem;color:#8A96A8;font-weight:700;text-transform:uppercase;letter-spacing:.08em;margin-bottom:.25rem;">NIM</div><div style="font-weight:700;color:#0D2E5C;"><?= $mhs['nim'] ?></div></div>
  <div><div style="font-size:.72rem;color:#8A96A8;font-weight:700;text-transform:uppercase;letter-spacing:.08em;margin-bottom:.25rem;">Program Studi</div><div><?= htmlspecialchars($mhs['prodi']) ?></div></div>
  <div><div style="font-size:.72rem;color:#8A96A8;font-weight:700;text-transform:uppercase;letter-spacing:.08em;margin-bottom:.25rem;">Lokasi KKN</div><div>Kec. <?= $mhs['kecamatan'] ?>, <?= $mhs['kabupaten'] ?></div></div>
  <div style="grid-column:1/-1"><div style="font-size:.72rem;color:#8A96A8;font-weight:700;text-transform:uppercase;letter-spacing:.08em;margin-bottom:.25rem;">Dosen Pembimbing Lapangan</div><div style="font-weight:600;color:#1A56A4;"><i class="ti ti-school" aria-hidden="true"></i> <?= htmlspecialchars($mhs['nama_dpl'] ?? '-') ?></div></div>
</div>
<div class="card">
  <div class="card-header"><h3><i class="ti ti-notebook" aria-hidden="true"></i> Progress Logbook</h3><a href="?page=logbook" class="btn btn-gold btn-sm"><i class="ti ti-pencil" aria-hidden="true"></i> Isi Logbook</a></div>
  <div class="card-body" style="padding:1.25rem;">
    <div style="display:grid;grid-template-columns:repeat(6,1fr);gap:.75rem;">
      <?php for ($w = 1; $w <= 6; $w++):
        $filled = count(array_filter($logbook_all[$w] ?? [], fn($e) => !empty($e['nama_kegiatan'])));
        $total_w = count($logbook_all[$w] ?? []);
        $pct    = $total_w > 0 ? round($filled/$total_w*100) : 0;
        $color  = ($filled > 0 && $filled === $total_w) ? '#276749' : ($filled > 0 ? '#1A56A4' : '#8A96A8');
      ?>
      <a href="?page=logbook&minggu=<?= $w ?>" style="text-decoration:none;text-align:center;background:#F8FAFF;border-radius:10px;border:2px solid <?= ($filled>0&&$filled===$total_w)?'#276749':($filled>0?'#1A56A4':'#E2E8F0') ?>;padding:.75rem .5rem;">
        <div style="font-size:.7rem;color:#8A96A8;font-weight:600;">MINGGU</div>
        <div style="font-family:'Playfair Display',serif;font-size:1.4rem;font-weight:700;color:<?= $color ?>;"><?= $w ?></div>
        <div style="font-size:.72rem;font-weight:600;color:<?= $color ?>"><?= $filled ?><?= $total_w > 0 ? '/'.$total_w : '' ?></div>
        <div style="background:#E2E8F0;border-radius:4px;height:4px;margin-top:.4rem;overflow:hidden;"><div style="background:<?= $color ?>;width:<?= $pct ?>%;height:100%;border-radius:4px;"></div></div>
      </a>
      <?php endfor; ?>
    </div>
  </div>
</div>
<?php /* ══════ LOGBOOK REKAP ══════ */ ?>
<?php elseif ($page === 'logbook' && $minggu === 0): ?>
<?php
$KUOTA = 3; $rekap_minggu = []; $total_bukti = 0;
for ($w = 1; $w <= 6; $w++) {
    $entries = $logbook_all[$w] ?? []; $jml_semua = count($entries);
    $jml_bukti = count(array_filter($entries, fn($e) => !empty($e['bukti_link'])));
    $pct_w = min(100, round($jml_bukti / $KUOTA * 100));
    if ($jml_semua === 0) $ket = 'Belum ada kegiatan';
    elseif ($jml_bukti === 0) $ket = $jml_semua . ' kegiatan, belum ada bukti';
    elseif ($pct_w >= 100) $ket = 'Memenuhi kuota (' . $jml_bukti . ' kegiatan)';
    else $ket = $jml_bukti . '/' . $KUOTA . ' kuota terpenuhi';
    $rekap_minggu[$w] = ['jml'=>$jml_bukti,'total'=>$jml_semua,'kuota'=>$KUOTA,'pct'=>$pct_w,'ket'=>$ket];
    $total_bukti += $jml_bukti;
}
$total_pct = round(array_sum(array_column($rekap_minggu, 'pct')) / 6);
?>
<div class="card" style="margin-bottom:1.5rem;">
  <div class="card-header" style="background:#0D2E5C;"><h3 style="color:#fff;"><i class="ti ti-clipboard-list" aria-hidden="true"></i> Rekap Kegiatan Logbook KKN 2026</h3></div>
  <div class="card-body" style="padding:1.25rem 1.5rem;">
    <div style="display:grid;grid-template-columns:1fr 1fr;gap:.5rem 2rem;font-size:.78rem;margin-bottom:1.25rem;padding-bottom:1rem;border-bottom:1px solid #F0F4F8;">
      <div><span style="color:#8A96A8;min-width:60px;">Nama</span><strong>: <?= htmlspecialchars($mhs['nama']) ?></strong></div>
      <div><span style="color:#8A96A8;min-width:60px;">NIM</span><strong>: <?= $mhs['nim'] ?></strong></div>
      <div><span style="color:#8A96A8;">Kelompok</span>: Kec. <?= $mhs['kecamatan'] ?>, <?= $mhs['kabupaten'] ?></div>
      <div><span style="color:#8A96A8;">DPL</span>: <?= htmlspecialchars($mhs['nama_dpl'] ?? '-') ?></div>
    </div>
    <table style="font-size:.88rem;margin-bottom:1.5rem;">
      <thead><tr><th>Minggu</th><th style="text-align:center;">Jumlah Kegiatan</th><th style="text-align:center;">Persentase</th><th>Keterangan</th></tr></thead>
      <tbody>
        <?php for ($w = 1; $w <= 6; $w++): $r = $rekap_minggu[$w]; ?>
        <tr>
          <td><strong>MINGGU <?= ['I','II','III','IV','V','VI'][$w-1] ?></strong></td>
          <td style="text-align:center;"><strong style="color:<?= $r['jml']===0?'#8A96A8':($r['pct']>=100?'#276749':'#1A56A4') ?>"><?= $r['jml'] ?></strong> <span style="color:#8A96A8;font-size:.78rem;">kegiatan</span></td>
          <td style="text-align:center;"><div style="display:flex;align-items:center;gap:6px;justify-content:center;"><div style="background:#E2E8F0;border-radius:4px;height:6px;width:60px;overflow:hidden;"><div style="background:<?= $r['pct']===100?'#276749':'#1A56A4' ?>;width:<?= $r['pct'] ?>%;height:100%;border-radius:4px;"></div></div><span style="font-size:.78rem;color:#0D2E5C;font-weight:600;"><?= $r['pct'] ?>%</span></div></td>
          <td style="color:<?= $r['total']===0?'#8A96A8':($r['jml']===$r['total']?'#276749':'#1A56A4') ?>"><?= $r['ket'] ?></td>
        </tr>
        <?php endfor; ?>
      </tbody>
      <tfoot><tr style="background:#F8FAFF;border-top:2px solid #E2E8F0;"><td><strong>TOTAL</strong></td><td style="text-align:center;"><strong style="color:#0D2E5C;"><?= $total_bukti ?> kegiatan</strong></td><td style="text-align:center;"><div style="display:flex;align-items:center;gap:6px;justify-content:center;"><div style="background:#E2E8F0;border-radius:4px;height:8px;width:60px;overflow:hidden;"><div style="background:#C8922A;width:<?= $total_pct ?>%;height:100%;border-radius:4px;"></div></div><span style="font-weight:700;color:#C8922A;"><?= $total_pct ?>%</span></div></td><td style="color:#8A96A8;font-size:.78rem;">Rata-rata persentase 6 minggu</td></tr></tfoot>
    </table>
  </div>
</div>
<?php /* ══════ LOGBOOK INPUT ══════ */ ?>
<?php elseif ($page === 'logbook'): ?>
<?php
$existing_entries = array_values($logbook_all[$minggu] ?? []);
$jumlah_existing = count($existing_entries);
$proker_ind_opt  = fetchAll("SELECT id, judul FROM kkn_proker_individu WHERE mahasiswa_id=? ORDER BY created_at", [$mhs['id']]);
$proker_kel_opts = fetchAll("SELECT id, judul FROM kkn_proker_kelompok WHERE dpl_id=?", [$mhs['dpl_id']]);
?>
<div style="display:flex;gap:.4rem;margin-bottom:1.25rem;flex-wrap:wrap;">
  <?php for ($w = 1; $w <= 6; $w++): $jml = count($logbook_all[$w] ?? []); ?>
  <a href="?page=logbook&minggu=<?= $w ?>" class="btn btn-sm <?= $w===$minggu?'btn-gold':'btn-primary' ?>">Minggu <?= $w ?> <span style="opacity:.7">(<?= $jml ?>)</span></a>
  <?php endfor; ?>
  <a href="?page=logbook&minggu=0" class="btn btn-sm" style="background:#276749;border-color:#276749;color:#fff;">Rekap</a>
</div>
<form method="POST" id="form-logbook">
  <input type="hidden" name="minggu" value="<?= $minggu ?>">
  <input type="hidden" name="jumlah_kegiatan" id="jumlah_kegiatan" value="<?= max(1, $jumlah_existing) ?>">
  <div class="card">
    <div class="card-header"><h3><i class="ti ti-notebook" aria-hidden="true"></i> Logbook Minggu <?= $minggu ?></h3><span style="font-size:.8rem;color:#8A96A8;"><?= $jumlah_existing ?> kegiatan tersimpan</span></div>
    <div class="card-body" style="padding:1.25rem;">
      <div id="kegiatan-container">
      <?php $tampil = max(1, $jumlah_existing);
      for ($kg = 1; $kg <= $tampil; $kg++): $e = $existing_entries[$kg-1] ?? null; ?>
      <div class="kegiatan-item" id="kegiatan-<?= $kg ?>" style="background:#F8FAFF;border-radius:10px;border:1px solid #E2E8F0;padding:1.25rem;margin-bottom:1rem;">
        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:.75rem;">
          <div style="font-weight:700;color:#0D2E5C;font-size:.9rem;">Kegiatan #<?= $kg ?></div>
          <?php if ($kg > 1): ?><button type="button" onclick="hapusKegiatan(<?= $kg ?>)" style="background:none;border:none;color:#e53e3e;cursor:pointer;font-size:.82rem;display:flex;align-items:center;gap:4px;font-family:inherit;"><i class="ti ti-trash" aria-hidden="true"></i> Hapus</button><?php endif; ?>
        </div>
        <div class="form-row">
          <div class="form-group"><label>Nama Kegiatan</label><input type="text" name="nama_<?= $kg ?>" placeholder="Contoh: Sosialisasi Digitalisasi UMKM" value="<?= htmlspecialchars($e['nama_kegiatan'] ?? '') ?>"></div>
          <div class="form-group"><label>Tanggal Pelaksanaan</label><input type="date" name="waktu_<?= $kg ?>" value="<?= htmlspecialchars(!empty($e['waktu']) ? (strtotime($e['waktu']) ? date('Y-m-d', strtotime($e['waktu'])) : $e['waktu']) : '') ?>"></div>
        </div>
        <div class="form-group"><label>Deskripsi Kegiatan</label><textarea name="desk_<?= $kg ?>" rows="3" placeholder="Uraian kegiatan..."><?= htmlspecialchars($e['deskripsi'] ?? '') ?></textarea></div>
        <div class="form-group" style="margin:0">
          <label><i class="ti ti-brand-google-drive" style="color:#1A56A4;"></i> Link Bukti Google Drive (PDF) <span style="color:#e53e3e;">*</span></label>
          <input type="url" name="bukti_<?= $kg ?>" placeholder="https://drive.google.com/..." value="<?= htmlspecialchars($e['bukti_link'] ?? '') ?>" required>
          <div style="font-size:.72rem;color:#8A96A8;margin-top:4px;line-height:1.6;"><i class="ti ti-info-circle"></i> Upload file <strong>PDF</strong> minimal 2 foto kegiatan ke Google Drive.</div>
        </div>
        <div class="form-group" style="margin-top:.75rem;margin-bottom:0;">
          <label>Keterkaitan dengan Program Kerja</label>
          <select name="tipe_<?= $kg ?>" onchange="toggleProker(this, <?= $kg ?>)" style="margin-bottom:.4rem;">
            <option value="">-- Pilih Tipe Kegiatan --</option>
            <option value="proker_individu" <?= ($e['tipe_kegiatan']??'')==='proker_individu'?'selected':'' ?>>Proker Utama Individu</option>
            <option value="proker_kelompok" <?= ($e['tipe_kegiatan']??'')==='proker_kelompok'?'selected':'' ?>>Proker Kelompok</option>
            <option value="pendukung" <?= ($e['tipe_kegiatan']??'')==='pendukung'?'selected':'' ?>>Program Pendukung</option>
          </select>
          <div id="proker-ind-<?= $kg ?>" style="display:<?= ($e['tipe_kegiatan']??'')==='proker_individu'?'block':'none' ?>;">
            <select name="proker_ind_id_<?= $kg ?>"><option value="">-- Pilih Proker Individu --</option><?php foreach($proker_ind_opt as $pio): ?><option value="<?= $pio['id'] ?>" <?= ($e['proker_ind_id']??'')==$pio['id']?'selected':'' ?>><?= htmlspecialchars($pio['judul']) ?></option><?php endforeach; ?><?php if(empty($proker_ind_opt)): ?><option value="" disabled>Belum ada proker individu</option><?php endif; ?></select>
          </div>
          <div id="proker-kel-<?= $kg ?>" style="display:<?= ($e['tipe_kegiatan']??'')==='proker_kelompok'?'block':'none' ?>;">
            <select name="proker_kel_id_<?= $kg ?>"><option value="">-- Pilih Proker Kelompok --</option><?php foreach($proker_kel_opts as $pk): ?><option value="<?= $pk['id'] ?>" <?= ($e['proker_kel_id']??'')==$pk['id']?'selected':'' ?>><?= htmlspecialchars($pk['judul']) ?></option><?php endforeach; ?><?php if(empty($proker_kel_opts)): ?><option value="" disabled>Belum ada proker kelompok</option><?php endif; ?></select>
          </div>
        </div>
      </div>
      <?php endfor; ?>
      </div>
      <button type="button" onclick="tambahKegiatan()" class="btn btn-primary" style="width:100%;margin-bottom:1rem;padding:10px;"><i class="ti ti-plus" aria-hidden="true"></i> Tambah Kegiatan</button>
      <button type="submit" class="btn btn-gold" style="width:100%;padding:13px;"><i class="ti ti-device-floppy" aria-hidden="true"></i> Simpan Logbook Minggu <?= $minggu ?></button>
    </div>
  </div>
</form>
<script>
var kgCount = <?= max(1, $jumlah_existing) ?>;
function toggleProker(sel, n) {
  document.getElementById('proker-ind-'+n).style.display = sel.value==='proker_individu'?'block':'none';
  document.getElementById('proker-kel-'+n).style.display = sel.value==='proker_kelompok'?'block':'none';
}
function tambahKegiatan() {
  kgCount++;
  document.getElementById('jumlah_kegiatan').value = kgCount;
  var html = '<div class="kegiatan-item" id="kegiatan-'+kgCount+'" style="background:#F8FAFF;border-radius:10px;border:1px solid #E2E8F0;padding:1.25rem;margin-bottom:1rem;">'
    +'<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:.75rem;"><div style="font-weight:700;color:#0D2E5C;font-size:.9rem;">Kegiatan #'+kgCount+'</div>'
    +'<button type="button" onclick="hapusKegiatan('+kgCount+')" style="background:none;border:none;color:#e53e3e;cursor:pointer;font-size:.82rem;display:flex;align-items:center;gap:4px;font-family:inherit;"><i class="ti ti-trash"></i> Hapus</button></div>'
    +'<div class="form-row"><div class="form-group"><label>Nama Kegiatan</label><input type="text" name="nama_'+kgCount+'" placeholder="Nama kegiatan"></div>'
    +'<div class="form-group"><label>Tanggal Pelaksanaan</label><input type="date" name="waktu_'+kgCount+'"></div></div>'
    +'<div class="form-group"><label>Deskripsi Kegiatan</label><textarea name="desk_'+kgCount+'" rows="3" placeholder="Uraian kegiatan..."></textarea></div>'
    +'<div class="form-group" style="margin:0"><label><i class="ti ti-brand-google-drive" style="color:#1A56A4;"></i> Link Bukti Google Drive <span style="color:#e53e3e;">*</span></label>'
    +'<input type="url" name="bukti_'+kgCount+'" placeholder="https://drive.google.com/..." required>'
    +'<div style="font-size:.72rem;color:#8A96A8;margin-top:4px;">Upload PDF ke Google Drive minimal 2 foto kegiatan.</div></div></div>';
  document.getElementById('kegiatan-container').insertAdjacentHTML('beforeend', html);
  document.getElementById('kegiatan-'+kgCount).scrollIntoView({behavior:'smooth',block:'start'});
}
function hapusKegiatan(n) {
  var el = document.getElementById('kegiatan-'+n);
  if (el) el.remove();
  document.getElementById('jumlah_kegiatan').value = document.querySelectorAll('.kegiatan-item').length;
}
</script>
<?php /* ══════ NILAI ══════ */ ?>
<?php elseif ($page === 'nilai'): ?>
<?php $nilai = fetch("SELECT p.*, d.nama as nama_dpl FROM kkn_penilaian p JOIN kkn_dpl d ON d.id=p.dpl_id WHERE p.mahasiswa_id=?",[$mhs['id']]); ?>
<?php if ($nilai): ?>
<div class="card">
  <div class="card-header"><h3><i class="ti ti-chart-bar" aria-hidden="true"></i> Nilai KKN — <?= htmlspecialchars($mhs['nama']) ?></h3></div>
  <div class="card-body" style="padding:1.5rem;">
    <div style="display:grid;grid-template-columns:repeat(5,1fr);gap:1rem;margin-bottom:1.5rem;">
      <?php foreach(['K1'=>['Kehadiran','15%'],'K2'=>['Observasi','20%'],'K3'=>['Pelaksanaan','25%'],'K4'=>['Luaran','25%'],'K5'=>['Sikap','15%']] as $k=>[$label,$bobot]): ?>
      <div style="background:#F8FAFF;border-radius:10px;border:1px solid #E2E8F0;padding:1rem;text-align:center;">
        <div style="font-size:.7rem;color:#8A96A8;font-weight:700;"><?= $k ?> (<?= $bobot ?>)</div>
        <div style="font-family:'Playfair Display',serif;font-size:1.8rem;font-weight:700;color:#0D2E5C;"><?= $nilai['nilai_'.strtolower($k)] ?></div>
        <div style="font-size:.68rem;color:#8A96A8;"><?= $label ?></div>
      </div>
      <?php endforeach; ?>
    </div>
    <div style="background:linear-gradient(135deg,#0D2E5C,#1A56A4);border-radius:12px;padding:1.5rem;text-align:center;color:#fff;">
      <div style="font-size:.85rem;color:rgba(255,255,255,.7);">Nilai Akhir KKN 2026</div>
      <div style="font-family:'Playfair Display',serif;font-size:3.5rem;font-weight:700;color:#C8922A;"><?= $nilai['nilai_akhir'] ?></div>
      <div style="font-size:.8rem;color:rgba(255,255,255,.6);">DPL: <?= htmlspecialchars($nilai['nama_dpl']) ?></div>
    </div>
  </div>
</div>
<?php else: ?>
<div style="text-align:center;padding:3rem;background:#fff;border-radius:12px;border:1px solid #E2E8F0;">
  <div style="font-size:2.5rem;color:#8A96A8;margin-bottom:1rem;"><i class="ti ti-clock" aria-hidden="true"></i></div>
  <h3 style="color:#0D2E5C;margin-bottom:.5rem;">Nilai Belum Tersedia</h3>
  <p style="color:#8A96A8;font-size:.9rem;">DPL Anda belum memasukkan nilai.</p>
</div>
<?php endif; ?>
<?php /* ══════ LUARAN INDIVIDU ══════ */ ?>
<?php elseif ($page === 'luaran'): ?>
<?php
$tbl_luaran = fetch("SHOW TABLES LIKE 'kkn_luaran'");
if (!$tbl_luaran) { echo '<div class="card"><div class="card-body" style="padding:1.5rem;color:#8A96A8;">Fitur luaran belum aktif.</div></div>'; dashClose(); exit; }
$luaran_list = fetchAll("SELECT * FROM kkn_luaran WHERE mahasiswa_id=? ORDER BY uploaded_at DESC", [$mhs['id']]);
$luaran_by_jenis = array_column($luaran_list, null, 'jenis');
?>
<div class="card" style="margin-bottom:1.25rem;">
  <div class="card-header" style="background:#0D2E5C;"><h3 style="color:#fff;"><i class="ti ti-file-text" aria-hidden="true"></i> Luaran Individu KKN 2026</h3></div>
  <div class="card-body" style="padding:1.25rem 1.5rem;">
    <div style="background:#EEF4FF;border:1px solid #C3D5F5;border-radius:8px;padding:.85rem 1rem;font-size:.8rem;color:#1e40af;margin-bottom:1.5rem;display:flex;gap:10px;align-items:flex-start;">
      <i class="ti ti-brand-google-drive" style="font-size:1.2rem;flex-shrink:0;margin-top:1px;"></i>
      <div><strong>Cara share Google Drive:</strong> Buka file → klik kanan → Bagikan → ubah akses ke <strong>"Siapa saja yang memiliki link"</strong> → salin link → paste di sini.</div>
    </div>
    <?php foreach(['artikel_jurnal'=>['Artikel Jurnal Pengabdian','Artikel ilmiah di jurnal pengabdian masyarakat','#EEF4FF','#0D2E5C','ti-book'],'artikel_media'=>['Artikel Media Cetak/Online','Artikel di media cetak atau portal berita online','#FFF7ED','#92400E','ti-news']] as $jenis=>[$judul_label,$desc,$bg,$color,$icon]):
      $lu = $luaran_by_jenis[$jenis] ?? null; ?>
    <div style="border:1px solid #E2E8F0;border-radius:10px;overflow:hidden;margin-bottom:1rem;">
      <div style="background:<?= $bg ?>;padding:.75rem 1rem;border-bottom:1px solid #E2E8F0;display:flex;justify-content:space-between;align-items:center;">
        <div><div style="font-size:.75rem;font-weight:600;color:#0D2E5C;"><i class="ti <?= $icon ?>" aria-hidden="true"></i> <?= $judul_label ?></div><div style="font-size:.72rem;color:#8A96A8;margin-top:2px;"><?= $desc ?></div></div>
        <?php if ($lu && !empty($lu['link_url'])): ?><span style="background:#D1FAE5;color:#065F46;font-size:.7rem;font-weight:600;padding:2px 10px;border-radius:20px;flex-shrink:0;">✓ Sudah diisi</span>
        <?php else: ?><span style="background:#FEF3C7;color:#92400E;font-size:.7rem;font-weight:600;padding:2px 10px;border-radius:20px;flex-shrink:0;">Belum diisi</span><?php endif; ?>
      </div>
      <div style="padding:1rem 1.25rem;">
        <?php if ($lu && !empty($lu['link_url'])): ?>
        <div style="background:<?= $bg ?>;border:1px solid #E2E8F0;border-radius:8px;padding:.75rem 1rem;margin-bottom:.75rem;font-size:.85rem;">
          <div style="font-weight:600;color:<?= $color ?>;margin-bottom:4px;"><?= htmlspecialchars($lu['judul']) ?></div>
          <div style="font-size:.75rem;color:#8A96A8;">Diperbarui: <?= date('d M Y, H:i', strtotime($lu['uploaded_at'])) ?> · <a href="<?= htmlspecialchars($lu['link_url']) ?>" target="_blank" style="color:#1A56A4;font-weight:600;"><i class="ti ti-external-link" aria-hidden="true"></i> Buka di Google Drive</a></div>
        </div>
        <?php endif; ?>
        <form method="POST">
          <input type="hidden" name="save_luaran" value="1">
          <input type="hidden" name="jenis_luaran" value="<?= $jenis ?>">
          <div class="form-group"><label style="font-size:.8rem;">Judul <?= $judul_label ?></label><input type="text" name="judul_luaran" placeholder="Masukkan judul" value="<?= htmlspecialchars($lu['judul'] ?? '') ?>"></div>
          <div class="form-group" style="margin:0"><label style="font-size:.8rem;"><i class="ti ti-brand-google-drive" style="color:#1A56A4;"></i> Link Google Drive</label><input type="url" name="link_luaran" placeholder="https://drive.google.com/..." value="<?= htmlspecialchars($lu['link_url'] ?? '') ?>"></div>
          <div style="display:flex;gap:.625rem;margin-top:.75rem;"><button type="submit" class="btn btn-primary" style="padding:8px 16px;font-size:.82rem;"><i class="ti ti-link" aria-hidden="true"></i> <?= $lu ? 'Perbarui Link' : 'Simpan Link' ?></button></div>
        </form>
        <?php if($lu): ?><form method="POST" onsubmit="return confirm('Hapus luaran ini?')" style="margin-top:.5rem;"><input type="hidden" name="del_luaran" value="1"><input type="hidden" name="jenis_luaran" value="<?= $jenis ?>"><button type="submit" style="background:none;border:none;color:#C53030;cursor:pointer;font-size:.78rem;display:flex;align-items:center;gap:4px;padding:0;"><i class="ti ti-trash" aria-hidden="true"></i> Hapus luaran ini</button></form><?php endif; ?>
      </div>
    </div>
    <?php endforeach; ?>
  </div>
</div>
<?php /* ══════ LUARAN KELOMPOK ══════ */ ?>
<?php elseif ($page === 'luaran_kel'): ?>
<?php
$tbl_nd = fetch("SELECT 1 FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name='kkn_nilai_desa'");
$anggota_kel = fetchAll("SELECT m.id,m.nama,m.nim,m.prodi FROM kkn_mahasiswa m WHERE m.dpl_id=? ORDER BY m.nama", [$mhs['dpl_id']]);
$nd_all = $tbl_nd ? fetchAll("SELECT * FROM kkn_nilai_desa WHERE dpl_id=?", [$mhs['dpl_id']]) : [];
$nd_by_mhs = array_column($nd_all, null, 'mahasiswa_id');
$nd_link_bukti = '';
foreach($nd_all as $_r) { if(!empty($_r['link_bukti'])) { $nd_link_bukti=$_r['link_bukti']; break; } }
$tbl_luaran_kel = fetch("SHOW TABLES LIKE 'kkn_luaran_kelompok'");
if (!$tbl_luaran_kel) { echo '<div class="card"><div class="card-body" style="padding:1.5rem;color:#8A96A8;">Fitur luaran kelompok belum aktif.</div></div>'; dashClose(); exit; }
$luaran_kel_list = fetchAll("SELECT * FROM kkn_luaran_kelompok WHERE dpl_id=? ORDER BY jenis", [$mhs['dpl_id']]);
$luaran_kel_by_jenis = array_column($luaran_kel_list, null, 'jenis');
?>
<div class="card">
  <div class="card-header" style="background:#0D2E5C;"><h3 style="color:#fff;"><i class="ti ti-users" aria-hidden="true"></i> Luaran Kelompok KKN 2026</h3><span style="font-size:.75rem;color:rgba(255,255,255,.6);">Kec. <?= $mhs['kecamatan'] ?>, <?= $mhs['kabupaten'] ?></span></div>
  <div class="card-body" style="padding:1.25rem 1.5rem;">
    <div style="background:#EEF4FF;border:1px solid #C3D5F5;border-radius:8px;padding:.85rem 1rem;font-size:.8rem;color:#1e40af;margin-bottom:1.5rem;display:flex;gap:10px;align-items:flex-start;">
      <i class="ti ti-brand-google-drive" style="font-size:1.2rem;flex-shrink:0;margin-top:1px;"></i>
      <div><strong>Semua luaran kelompok menggunakan link Google Drive.</strong><br>Upload file ke Drive → ubah akses ke <strong>"Siapa saja yang memiliki link"</strong> → salin dan paste link di sini.</div>
    </div>
    <?php foreach(['rpk'=>['RPK (Rencana Program Kerja)','Dokumen RPK kelompok','#EEF4FF','#0D2E5C','ti-clipboard-list'],'laporan'=>['Laporan Kelompok','Laporan akhir pelaksanaan KKN','#F0FDF4','#065F46','ti-file-description'],'poster'=>['Poster Program Unggulan','Poster visual program unggulan','#FFF7ED','#92400E','ti-photo'],'video'=>['Video Dokumentasi','Video dokumentasi kegiatan KKN','#F5F3FF','#4C1D95','ti-video']] as $jenis=>[$judul_label,$desc,$bg,$color,$icon]):
      $lu = $luaran_kel_by_jenis[$jenis] ?? null; $has_link = $lu && !empty($lu['link_url']); ?>
    <div style="border:1px solid #E2E8F0;border-radius:10px;overflow:hidden;margin-bottom:1rem;">
      <div style="background:<?= $bg ?>;padding:.75rem 1rem;border-bottom:1px solid #E2E8F0;display:flex;justify-content:space-between;align-items:center;">
        <div><div style="font-size:.75rem;font-weight:600;color:#0D2E5C;"><i class="ti <?= $icon ?>" aria-hidden="true"></i> <?= $judul_label ?></div><div style="font-size:.72rem;color:#8A96A8;margin-top:2px;"><?= $desc ?></div></div>
        <?php if ($has_link): ?><span style="background:#D1FAE5;color:#065F46;font-size:.7rem;font-weight:600;padding:2px 10px;border-radius:20px;flex-shrink:0;">✓ Sudah diisi</span>
        <?php else: ?><span style="background:#FEF3C7;color:#92400E;font-size:.7rem;font-weight:600;padding:2px 10px;border-radius:20px;flex-shrink:0;">Belum diisi</span><?php endif; ?>
      </div>
      <div style="padding:1rem 1.25rem;">
        <?php if ($has_link): ?><div style="background:<?= $bg ?>;border:1px solid #E2E8F0;border-radius:8px;padding:.75rem 1rem;margin-bottom:.75rem;font-size:.85rem;"><div style="font-weight:600;color:<?= $color ?>;margin-bottom:4px;"><?= htmlspecialchars($lu['judul']) ?></div><div style="font-size:.75rem;color:#8A96A8;">Diperbarui: <?= date('d M Y, H:i', strtotime($lu['uploaded_at'])) ?> · <a href="<?= htmlspecialchars($lu['link_url']) ?>" target="_blank" style="color:#1A56A4;font-weight:600;"><i class="ti ti-external-link" aria-hidden="true"></i> Buka Link</a></div></div><?php endif; ?>
        <form method="POST">
          <input type="hidden" name="save_luaran_kel" value="1"><input type="hidden" name="jenis_luaran_kel" value="<?= $jenis ?>">
          <div class="form-group"><label style="font-size:.8rem;">Judul / Nama <?= $judul_label ?></label><input type="text" name="judul_luaran_kel" placeholder="Masukkan judul" value="<?= htmlspecialchars($lu['judul'] ?? '') ?>"></div>
          <div class="form-group" style="margin:0"><label style="font-size:.8rem;"><i class="ti ti-brand-google-drive" style="color:#1A56A4;"></i> Link Google Drive</label><input type="url" name="link_luaran_kel" placeholder="https://drive.google.com/..." value="<?= htmlspecialchars($lu['link_url'] ?? '') ?>"></div>
          <button type="submit" class="btn btn-gold" style="margin-top:.75rem;padding:8px 16px;font-size:.82rem;"><i class="ti ti-link" aria-hidden="true"></i> <?= $has_link ? 'Perbarui Link' : 'Simpan Link' ?></button>
        </form>
        <?php if($lu): ?><form method="POST" onsubmit="return confirm('Hapus luaran ini?')" style="margin-top:.5rem;"><input type="hidden" name="del_luaran_kel" value="1"><input type="hidden" name="jenis_luaran_kel" value="<?= $jenis ?>"><button type="submit" style="background:none;border:none;color:#C53030;cursor:pointer;font-size:.78rem;display:flex;align-items:center;gap:4px;padding:0;"><i class="ti ti-trash" aria-hidden="true"></i> Hapus luaran ini</button></form><?php endif; ?>
      </div>
    </div>
    <?php endforeach; ?>
  </div>
</div>
<!-- Nilai dari Desa -->
<div class="card" style="margin-top:1.25rem;">
  <div class="card-header" style="display:flex;align-items:center;justify-content:space-between;">
    <h3><i class="ti ti-star" aria-hidden="true"></i> Nilai dari Desa</h3>
    <?php if(!empty($nd_all)): $st_all = $nd_all[0]['status']??'pending'; ?>
    <?php if($st_all==='disetujui'): ?><span style="background:#D1FAE5;color:#065F46;font-size:.72rem;font-weight:700;padding:3px 12px;border-radius:20px;">✓ Divalidasi DPL</span>
    <?php elseif($st_all==='ditolak'): ?><span style="background:#FEE2E2;color:#991B1B;font-size:.72rem;font-weight:700;padding:3px 12px;border-radius:20px;">✗ Ditolak DPL</span>
    <?php else: ?><span style="background:#FEF3C7;color:#92400E;font-size:.72rem;font-weight:700;padding:3px 12px;border-radius:20px;">⏳ Menunggu Validasi</span><?php endif; ?>
    <?php endif; ?>
  </div>
  <div class="card-body" style="padding:1.25rem 1.5rem;">
    <?php if(isset($nd_ok)): ?><div class="alert alert-success"><i class="ti ti-check"></i> <?= htmlspecialchars($nd_ok) ?></div><?php endif; ?>
    <?php if(!empty($nd_all) && !empty($nd_all[0]['catatan_dpl'])): ?><div style="background:#FEF3C7;border:1px solid #FDE68A;border-radius:8px;padding:.75rem 1rem;margin-bottom:1rem;font-size:.78rem;color:#92400E;"><strong>Catatan DPL:</strong> <?= htmlspecialchars($nd_all[0]['catatan_dpl']) ?></div><?php endif; ?>
    <form method="POST">
      <input type="hidden" name="save_nilai_desa" value="1">
      <div style="overflow-x:auto;margin-bottom:1rem;">
        <table style="width:100%;border-collapse:collapse;font-size:.78rem;">
          <thead><tr style="background:#F7F9FC;"><th style="padding:8px 10px;text-align:left;border-bottom:2px solid #E2E8F0;">Nama Anggota</th><th style="padding:8px 6px;text-align:center;border-bottom:2px solid #E2E8F0;font-size:.72rem;">Inisiatif<br>/20</th><th style="padding:8px 6px;text-align:center;border-bottom:2px solid #E2E8F0;font-size:.72rem;">Tg.Jawab<br>/20</th><th style="padding:8px 6px;text-align:center;border-bottom:2px solid #E2E8F0;font-size:.72rem;">Kerjasama<br>/20</th><th style="padding:8px 6px;text-align:center;border-bottom:2px solid #E2E8F0;font-size:.72rem;">Kehadiran<br>/20</th><th style="padding:8px 6px;text-align:center;border-bottom:2px solid #E2E8F0;font-size:.72rem;">Capaian<br>/20</th><th style="padding:8px 6px;text-align:center;border-bottom:2px solid #E2E8F0;font-size:.72rem;">Total<br>/100</th></tr></thead>
          <tbody>
          <?php foreach($anggota_kel as $ag): $nv = $nd_by_mhs[$ag['id']] ?? null; $locked = $nv && $nv['status']==='disetujui'; ?>
          <tr style="border-bottom:1px solid #F5F7FA;"><td style="padding:8px 10px;"><div style="font-weight:600;color:#0D2E5C;"><?= htmlspecialchars($ag['nama']) ?></div><div style="font-size:.68rem;color:#8A96A8;"><?= $ag['nim'] ?></div></td>
          <?php foreach(['n1','n2','n3','n4','n5'] as $nk): ?>
          <td style="padding:6px 4px;text-align:center;"><?php if($locked): ?><span style="font-weight:700;color:#276749;"><?= $nv[$nk] ?></span><?php else: ?><input type="number" name="nd[<?= $ag['id'] ?>][<?= $nk ?>]" min="0" max="20" value="<?= $nv[$nk] ?? '' ?>" style="width:52px;text-align:center;padding:4px;border:1px solid #E2E8F0;border-radius:6px;font-size:.78rem;"><?php endif; ?></td>
          <?php endforeach; ?>
          <td style="padding:6px 4px;text-align:center;font-weight:700;"><?= $nv ? $nv['total'] : '—' ?></td></tr>
          <?php endforeach; ?>
          </tbody>
        </table>
      </div>
      <div class="form-group" style="margin-bottom:.75rem;"><label style="font-size:.75rem;font-weight:600;"><i class="ti ti-brand-google-drive" style="color:#1A56A4;"></i> Link Scan Lembar Penilaian</label><input type="url" name="nd_link" placeholder="https://drive.google.com/..." value="<?= htmlspecialchars($nd_link_bukti) ?>"></div>
      <?php $all_locked = !empty($nd_all) && !array_filter($nd_all, fn($r) => $r['status']!=='disetujui'); ?>
      <?php if(!$all_locked): ?><button type="submit" class="btn btn-primary" style="padding:8px 18px;font-size:.82rem;"><i class="ti ti-device-floppy" aria-hidden="true"></i> <?= !empty($nd_all) ? 'Perbarui Nilai' : 'Simpan Nilai' ?></button>
      <?php else: ?><div style="font-size:.78rem;color:#276749;"><i class="ti ti-lock"></i> Semua nilai sudah divalidasi DPL.</div><?php endif; ?>
    </form>
  </div>
</div>
<?php /* ══════ PROFIL ══════ */ ?>
<?php elseif ($page === 'profil'): ?>
<div class="card">
  <div class="card-header"><h3><i class="ti ti-user" aria-hidden="true"></i> Profil Mahasiswa</h3></div>
  <div class="card-body" style="padding:1.5rem;">
    <?php foreach(['Nama Lengkap'=>$mhs['nama'],'NIM'=>$mhs['nim'],'Program Studi'=>$mhs['prodi'],'Email'=>$mhs['email'],'Kecamatan KKN'=>'Kec. '.$mhs['kecamatan'].', Kab. '.$mhs['kabupaten'],'DPL'=>$mhs['nama_dpl']] as $lbl=>$val): ?>
    <div style="display:flex;gap:1rem;padding:.75rem 0;border-bottom:1px solid #F5F7FA;"><div style="font-size:.8rem;font-weight:600;color:#8A96A8;width:150px;flex-shrink:0;"><?= $lbl ?></div><div style="color:#0D2E5C;"><?= htmlspecialchars($val ?? '-') ?></div></div>
    <?php endforeach; ?>
  </div>
</div>
<div class="card" style="margin-top:1.25rem;">
  <div class="card-header"><h3><i class="ti ti-lock" aria-hidden="true"></i> Ganti Password</h3></div>
  <div class="card-body" style="padding:1.25rem 1.5rem;">
    <?php if(isset($pass_ok)): ?><div class="alert alert-success"><i class="ti ti-check"></i> <?= htmlspecialchars($pass_ok) ?></div><?php endif; ?>
    <?php if(isset($pass_err)): ?><div class="alert alert-error"><i class="ti ti-alert-circle"></i> <?= htmlspecialchars($pass_err) ?></div><?php endif; ?>
    <form method="POST">
      <div class="form-group"><label>Password Lama</label><input type="password" name="pass_lama" placeholder="Masukkan password lama" required></div>
      <div class="form-row">
        <div class="form-group"><label>Password Baru</label><input type="password" name="pass_baru" placeholder="Minimal 6 karakter" required></div>
        <div class="form-group"><label>Konfirmasi Password Baru</label><input type="password" name="pass_ulang" placeholder="Ulangi password baru" required></div>
      </div>
      <button type="submit" name="ganti_password" class="btn btn-gold"><i class="ti ti-lock" aria-hidden="true"></i> Simpan Password Baru</button>
    </form>
  </div>
</div>
<?php /* ══════ SERTIFIKAT ══════ */ ?>
<?php elseif ($page === 'sertifikat'): ?>
<?php
$row_sert_ind  = fetch("SELECT setting_value FROM kkn_settings WHERE setting_key=?", ['kkn_sertifikat_mhs_'.$mhs['id']]);
$row_sert_glob = fetch("SELECT setting_value FROM kkn_settings WHERE setting_key='kkn_sertifikat_link_global'");
$sert_link     = $row_sert_ind['setting_value'] ?? $row_sert_glob['setting_value'] ?? '';
$sert_is_ind   = !empty($row_sert_ind['setting_value']);
$total_logbook = fetch("SELECT COUNT(*) as n FROM kkn_logbook WHERE mahasiswa_id=? AND bukti_link != ''", [$mhs['id']])['n'] ?? 0;
$pct_logbook   = $total_logbook >= 24 ? 100 : round($total_logbook / 30 * 100);
$syarat_logbook  = $total_logbook >= 24;
$luaran_jurnal   = fetch("SELECT id FROM kkn_luaran WHERE mahasiswa_id=? AND jenis='artikel_jurnal' AND link_url != ''", [$mhs['id']]);
$luaran_media    = fetch("SELECT id FROM kkn_luaran WHERE mahasiswa_id=? AND jenis='artikel_media' AND link_url != ''", [$mhs['id']]);
$syarat_luaran_ind = $luaran_jurnal && $luaran_media;
$luaran_laporan  = fetch("SELECT id FROM kkn_luaran_kelompok WHERE dpl_id=? AND jenis='laporan' AND link_url != ''", [$mhs['dpl_id']]);
$syarat_luaran_kel = (bool)$luaran_laporan;
$nilai_kkn       = fetch("SELECT id FROM kkn_penilaian WHERE mahasiswa_id=? AND nilai_akhir IS NOT NULL", [$mhs['id']]);
$syarat_nilai    = (bool)$nilai_kkn;
$total_eval      = fetch("SELECT COUNT(*) as n FROM kkn_monev_eval me JOIN kkn_logbook lb ON lb.id=me.logbook_id WHERE lb.mahasiswa_id=?", [$mhs['id']])['n'] ?? 0;
$total_tdk_valid = fetch("SELECT COUNT(*) as n FROM kkn_monev_eval me JOIN kkn_logbook lb ON lb.id=me.logbook_id WHERE lb.mahasiswa_id=? AND me.status_eval='tidak_valid'", [$mhs['id']])['n'] ?? 0;
$syarat_monev    = $total_logbook > 0 && $total_eval >= $total_logbook && $total_tdk_valid === 0;
$semua_terpenuhi = $syarat_logbook && $syarat_luaran_ind && $syarat_luaran_kel && $syarat_nilai && $syarat_monev;
?>
<div style="max-width:680px;">
  <div style="background:#fff;border-radius:14px;border:1px solid #E2E8F0;overflow:hidden;margin-bottom:1.5rem;">
    <div style="background:#0D2E5C;padding:1.25rem 1.5rem;display:flex;align-items:center;gap:10px;"><i class="ti ti-certificate" style="color:#C8922A;font-size:1.4rem;" aria-hidden="true"></i><h3 style="color:#fff;font-size:1rem;font-weight:700;margin:0;">Sertifikat KKN 2026</h3></div>
    <div style="padding:1.75rem;">
      <?php if($sert_link && $semua_terpenuhi): ?>
      <div style="text-align:center;padding:1.5rem 0;"><div style="width:80px;height:80px;background:#C6F6D5;border-radius:50%;display:flex;align-items:center;justify-content:center;margin:0 auto 1.25rem;"><i class="ti ti-certificate" style="font-size:2.2rem;color:#276749;" aria-hidden="true"></i></div><h4 style="font-size:1.1rem;font-weight:700;color:#0D2E5C;margin-bottom:.5rem;">Sertifikat KKN Anda Sudah Tersedia</h4><a href="<?= htmlspecialchars($sert_link) ?>" target="_blank" style="display:inline-flex;align-items:center;gap:8px;background:#C8922A;color:#fff;padding:.875rem 2rem;border-radius:8px;text-decoration:none;font-weight:700;font-size:.95rem;"><i class="ti ti-brand-google-drive" aria-hidden="true"></i> Buka Folder Sertifikat</a></div>
      <?php elseif(!$semua_terpenuhi): ?>
      <div style="padding:.5rem 0 1rem;"><div style="text-align:center;margin-bottom:1.5rem;"><div style="width:72px;height:72px;background:#FEF9C3;border-radius:50%;display:flex;align-items:center;justify-content:center;margin:0 auto .875rem;"><i class="ti ti-lock" style="font-size:2rem;color:#C8922A;" aria-hidden="true"></i></div><h4 style="font-size:1rem;font-weight:700;color:#0D2E5C;margin-bottom:.25rem;">Sertifikat Belum Dapat Diakses</h4><p style="font-size:.82rem;color:#64748b;">Selesaikan semua syarat berikut.</p></div>
      <div style="display:flex;flex-direction:column;gap:.625rem;max-width:480px;margin:0 auto;">
        <?php foreach([[$syarat_logbook,'Logbook kegiatan',$total_logbook.'/24 kegiatan ('.$pct_logbook.'%)'],[$syarat_luaran_ind,'Luaran individu','Jurnal '.($luaran_jurnal?'✓':'belum').' · Media '.($luaran_media?'✓':'belum')],[$syarat_luaran_kel,'Laporan kelompok',$luaran_laporan?'Sudah':'Belum dikumpulkan'],[$syarat_nilai,'Nilai KKN dari DPL',$nilai_kkn?'Sudah diinput':'Belum diinput DPL'],[$syarat_monev,'Validasi Tim Monev',$total_tdk_valid>0?$total_tdk_valid.' kegiatan tidak valid':($total_eval>=$total_logbook&&$total_logbook>0?'Sudah divalidasi':'Belum divalidasi')]] as [$ok,$label,$detail]): ?>
        <div style="display:flex;align-items:center;gap:12px;padding:.75rem 1rem;background:<?= $ok?'#F0FFF4':'#FFF5F5' ?>;border:0.5px solid <?= $ok?'#C6F6D5':'#FED7D7' ?>;border-radius:8px;"><div style="width:28px;height:28px;border-radius:50%;background:<?= $ok?'#276749':'#C53030' ?>;display:flex;align-items:center;justify-content:center;flex-shrink:0;"><i class="ti ti-<?= $ok?'check':'x' ?>" style="color:#fff;font-size:.85rem;" aria-hidden="true"></i></div><div><div style="font-size:.82rem;font-weight:700;color:<?= $ok?'#276749':'#C53030' ?>;"><?= $label ?></div><div style="font-size:.72rem;color:#64748b;margin-top:1px;"><?= $detail ?></div></div></div>
        <?php endforeach; ?>
      </div></div>
      <?php else: ?>
      <div style="text-align:center;padding:2rem 0;"><h4 style="color:#0D2E5C;margin-bottom:.5rem;">Semua Syarat Terpenuhi</h4><p style="font-size:.85rem;color:#64748b;">Sertifikat sedang dalam proses penerbitan oleh LPPM.</p></div>
      <?php endif; ?>
    </div>
  </div>
</div>
<?php /* ══════ DOWNLOAD ══════ */ ?>
<?php elseif ($page === 'download'): ?>
<?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) ?? []) : [];
$templates = [
    'kkn_tpl_rpk'                => ['Template RPK (Rencana Program Kerja)',      'Template penyusunan rencana program kerja KKN.','ti-clipboard-list','#C8922A','#FEF8E8'],
    'kkn_tpl_artikel_pengabdian' => ['Template Artikel Pengabdian',               'Template penulisan artikel jurnal pengabdian masyarakat.','ti-file-text','#1A56A4','#EEF4FF'],
    'kkn_tpl_laporan_kelompok'   => ['Template Laporan Kelompok',                 'Template laporan akhir pelaksanaan KKN kelompok.','ti-users','#276749','#F0FFF4'],
    'kkn_tpl_laporan_kel_tegal'  => ['Template Laporan Kelompok (Tegal)',         'Template laporan akhir khusus wilayah Kabupaten Tegal.','ti-file-description','#7C3AED','#F5F3FF'],
    'kkn_tpl_lembar_penilaian'   => ['Template Lembar Penilaian Desa',            'Lembar penilaian program KKN oleh perangkat desa.','ti-star','#C8922A','#FFFBEB'],
];
$tpl_links = [];
foreach($templates as $key => $tpl) {
    $row = fetch("SELECT setting_value FROM kkn_settings WHERE setting_key=?", [$key]);
    $tpl_links[$key] = $row['setting_value'] ?? '';
}
?>
<div style="max-width:900px;">
  <div style="font-size:.82rem;font-weight:700;color:#0D2E5C;margin-bottom:.75rem;"><i class="ti ti-download" style="color:#C8922A;" aria-hidden="true"></i> Template Luaran</div>
  <div style="display:grid;grid-template-columns:1fr 1fr;gap:1rem;">
  <?php foreach($templates as $key=>[$judul,$desc,$icon,$color,$bg]): $link = $tpl_links[$key]; ?>
  <div style="background:#fff;border-radius:12px;border:1px solid #E2E8F0;overflow:hidden;display:flex;flex-direction:column;">
    <div style="background:<?= $bg ?>;padding:.75rem 1rem;display:flex;align-items:center;gap:10px;border-bottom:1px solid #E2E8F0;">
      <div style="width:36px;height:36px;background:#fff;border-radius:8px;display:flex;align-items:center;justify-content:center;border:1px solid #E2E8F0;flex-shrink:0;"><i class="ti <?= $icon ?>" style="font-size:1.1rem;color:<?= $color ?>;" aria-hidden="true"></i></div>
      <div><div style="font-weight:700;color:#0D2E5C;font-size:.78rem;"><?= $judul ?></div><div style="font-size:.68rem;color:#8A96A8;margin-top:2px;"><?= $desc ?></div></div>
    </div>
    <div style="padding:.75rem 1rem;margin-top:auto;">
      <?php if($link): ?><a href="<?= htmlspecialchars($link) ?>" target="_blank" style="display:inline-flex;align-items:center;gap:6px;background:<?= $color ?>;color:#fff;padding:6px 14px;border-radius:7px;text-decoration:none;font-weight:600;font-size:.72rem;"><i class="ti ti-download" aria-hidden="true"></i> Download</a>
      <?php else: ?><div style="font-size:.75rem;color:#F59E0B;"><i class="ti ti-alert-triangle" aria-hidden="true"></i> Belum tersedia</div><?php endif; ?>
    </div>
  </div>
  <?php endforeach; ?>
  </div>
  <?php if($ns_list): ?>
  <div style="margin-top:1.5rem;">
    <div style="font-size:.82rem;font-weight:700;color:#0D2E5C;margin-bottom:.75rem;"><i class="ti ti-file-upload" style="color:#C8922A;" aria-hidden="true"></i> Materi Pembekalan</div>
    <div style="display:grid;grid-template-columns:1fr 1fr;gap:1rem;">
      <?php foreach(array_reverse($ns_list) as $ns): ?>
      <div style="background:#fff;border:1px solid #E2E8F0;border-radius:12px;overflow:hidden;display:flex;flex-direction:column;">
        <div style="background:#EEF4FF;padding:.75rem 1rem;display:flex;align-items:center;gap:10px;border-bottom:1px solid #E2E8F0;"><div style="width:36px;height:36px;background:#fff;border-radius:8px;display:flex;align-items:center;justify-content:center;border:1px solid #E2E8F0;flex-shrink:0;"><i class="ti ti-file-description" style="font-size:1.1rem;color:#1A56A4;" aria-hidden="true"></i></div><div style="font-weight:700;color:#0D2E5C;font-size:.78rem;"><?= htmlspecialchars($ns['judul']) ?></div></div>
        <div style="padding:.75rem 1rem;margin-top:auto;"><a href="<?= htmlspecialchars($ns['link']) ?>" target="_blank" style="display:inline-flex;align-items:center;gap:6px;background:#1A56A4;color:#fff;padding:6px 14px;border-radius:7px;text-decoration:none;font-weight:600;font-size:.72rem;"><i class="ti ti-download" aria-hidden="true"></i> Download</a></div>
      </div>
      <?php endforeach; ?>
    </div>
  </div>
  <?php endif; ?>
</div>
<?php endif; ?>
<?php if (!empty($js_redirect)): ?>
<script>window.location.replace('<?= htmlspecialchars($js_redirect) ?>');</script>
<?php endif; ?>
<?php dashClose(); ?>