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

$dpl = fetch("SELECT * FROM kkn_dpl WHERE user_id=?", [$user['id']]);
if (!$dpl) { echo '<p style="padding:2rem">Data DPL tidak ditemukan. Hubungi admin LPPM.</p>'; dashClose(); exit; }

$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 Luaran Individu
if ($page === 'luaran' && isset($_GET['export'])) {
    if (!$tbl_luaran) { echo 'Tabel belum ada.'; exit; }
    $rows = fetchAll("SELECT m.nama,m.nim,m.prodi,
        MAX(CASE WHEN l.jenis='artikel_jurnal' THEN l.judul END) as j_jurnal,
        MAX(CASE WHEN l.jenis='artikel_jurnal' THEN l.link_url END) as link_jurnal,
        MAX(CASE WHEN l.jenis='artikel_media' THEN l.judul END) as j_media,
        MAX(CASE WHEN l.jenis='artikel_media' THEN l.link_url END) as link_media
        FROM kkn_mahasiswa m
        LEFT JOIN kkn_luaran l ON l.mahasiswa_id=m.id
        WHERE m.dpl_id=?
        GROUP BY m.id ORDER BY m.nama", [$dpl['id']]);
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=luaran_individu_'.$dpl['kecamatan'].'_'.date('Ymd').'.csv');
    echo "\xEF\xBB\xBF";
    echo "No,Nama,NIM,Prodi,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']).'"',
            '"'.str_replace('"','""',($r['j_jurnal']??'')).'"',$r['link_jurnal']?'Ada Link':'Belum',
            '"'.str_replace('"','""',($r['j_media']??'')).'"',$r['link_media']?'Ada Link':'Belum'])."\n";
    }
    exit;
}

// Export CSV Luaran Kelompok
if ($page === 'luaran_kel' && isset($_GET['export'])) {
    if (!$tbl_luaran_kel) { echo 'Tabel belum ada.'; exit; }
    $rows = fetchAll("SELECT * FROM kkn_luaran_kelompok WHERE dpl_id=? ORDER BY jenis", [$dpl['id']]);
    $lk = array_column($rows, null, 'jenis');
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=luaran_kelompok_'.$dpl['kecamatan'].'_'.date('Ymd').'.csv');
    echo "\xEF\xBB\xBF";
    echo "Jenis,Judul,Status,Tanggal Upload\n";
    foreach(['rpk'=>'RPK','laporan'=>'Laporan Kelompok','poster'=>'Poster','video'=>'Video Dokumentasi'] as $j=>$lbl) {
        $it = $lk[$j] ?? null;
        echo implode(',', ['"'.$lbl.'"','"'.str_replace('"','""',($it['judul']??'')).'"',
            $it?'Ada Link':'Belum', $it?'"'.date('d M Y',strtotime($it['uploaded_at'])).'"':'"-"'])."\n";
    }
    exit;
}

// Data mahasiswa bimbingan
$mhs_list = fetchAll("SELECT m.*, u.status as akun_status FROM kkn_mahasiswa m LEFT JOIN kkn_users u ON u.id=m.user_id WHERE m.dpl_id=? ORDER BY m.nama", [$dpl['id']]);

$user['nidn'] = $dpl['nidn'] ?? '-';
dashHeader('Dashboard DPL', 'dpl', $user);
dashNav([
    ['page'=>'home',       'icon'=>'<i class="ti ti-home" aria-hidden="true"></i>',          'label'=>'Dashboard'],
    ['section'=>'MAHASISWA'],
    ['page'=>'mhs',        'icon'=>'<i class="ti ti-users" aria-hidden="true"></i>',         'label'=>'Daftar Mahasiswa'],
    ['page'=>'logbook',    'icon'=>'<i class="ti ti-notebook" aria-hidden="true"></i>',      'label'=>'Lihat Logbook'],
    ['section'=>'PROGRAM KERJA'],
    ['page'=>'proker_ind', 'icon'=>'<i class="ti ti-user" aria-hidden="true"></i>',          'label'=>'Individu'],
    ['page'=>'proker_kel', 'icon'=>'<i class="ti ti-users" aria-hidden="true"></i>',         'label'=>'Kelompok'],
    ['section'=>'PENILAIAN'],
    ['page'=>'penilaian',  'icon'=>'<i class="ti ti-chart-bar" aria-hidden="true"></i>',    'label'=>'Input Penilaian'],
    ['page'=>'rekap',      'icon'=>'<i class="ti ti-list" aria-hidden="true"></i>',          'label'=>'Rekap Nilai'],
    ['section'=>'LUARAN'],
    ['page'=>'nilai_desa', 'icon'=>'<i class="ti ti-star" aria-hidden="true"></i>', 'label'=>'Nilai dari Desa'],
    ['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'],
]);
dashFooter();
dashTopbar(['home'=>'Dashboard DPL','mhs'=>'Daftar Mahasiswa','logbook'=>'Logbook Mahasiswa',
    'proker_ind'=>'Program Kerja Individu','proker_kel'=>'Program Kerja Kelompok',
    'penilaian'=>'Input Penilaian','rekap'=>'Rekap Nilai',
    'luaran'=>'Luaran Individu','luaran_kel'=>'Luaran Kelompok'][$page] ?? 'Dashboard');

?>

<?php if ($page === 'home'): ?>
<div class="stat-grid">
  <div class="stat-card"><div class="num"><?= count($mhs_list) ?></div><div class="lbl">Mahasiswa Bimbingan</div></div>
  <div class="stat-card"><div class="num"><?= count(array_filter($mhs_list, fn($m) => $m['akun_status']==='active')) ?></div><div class="lbl">Akun Aktif</div></div>
  <div class="stat-card"><div class="num"><?= fetch("SELECT COUNT(DISTINCT mahasiswa_id) as n FROM kkn_logbook WHERE mahasiswa_id IN (SELECT id FROM kkn_mahasiswa WHERE dpl_id=?)", [$dpl['id']])['n'] ?></div><div class="lbl">Isi Logbook</div></div>
  <div class="stat-card"><div class="num"><?= fetch("SELECT COUNT(*) as n FROM kkn_penilaian WHERE dpl_id=?", [$dpl['id']])['n'] ?></div><div class="lbl">Sudah Dinilai</div></div>
</div>
<div class="card" style="margin-top:1.25rem;">
  <div class="card-header"><h3><i class="ti ti-map-pin" aria-hidden="true"></i> Lokasi KKN</h3></div>
  <div class="card-body" style="padding:1.25rem;font-size:.9rem;">
    <div style="display:grid;grid-template-columns:1fr 1fr;gap:.75rem;">
      <div><div style="font-size:.72rem;color:#8A96A8;font-weight:700;text-transform:uppercase;margin-bottom:3px;">Kecamatan</div><strong><?= $dpl['kecamatan'] ?></strong></div>
      <div><div style="font-size:.72rem;color:#8A96A8;font-weight:700;text-transform:uppercase;margin-bottom:3px;">Kabupaten</div><strong><?= $dpl['kabupaten'] ?></strong></div>
      <div><div style="font-size:.72rem;color:#8A96A8;font-weight:700;text-transform:uppercase;margin-bottom:3px;">NIDN</div><?= $dpl['nidn'] ?></div>
      <div><div style="font-size:.72rem;color:#8A96A8;font-weight:700;text-transform:uppercase;margin-bottom:3px;">Email</div><?= htmlspecialchars($dpl['email']??$user['email']??'-') ?></div>
    </div>
  </div>
</div>

<?php elseif ($page === 'mhs'): ?>
<div class="card">
  <div class="card-header"><h3><i class="ti ti-users" aria-hidden="true"></i> Mahasiswa Bimbingan — <?= $dpl['kecamatan'] ?> (<?= count($mhs_list) ?>)</h3></div>
  <div class="card-body" style="padding:0">
    <table>
      <tr><th>Nama</th><th>NIM</th><th>Prodi</th><th>Status</th><th>Logbook</th><th>Nilai</th></tr>
      <?php foreach ($mhs_list as $m):
        $jml_log = fetch("SELECT COUNT(*) as n FROM kkn_logbook WHERE mahasiswa_id=?", [$m['id']])['n'];
        $nilai   = fetch("SELECT nilai_akhir FROM kkn_penilaian WHERE mahasiswa_id=?", [$m['id']]);
      ?>
      <tr>
        <td><strong><?= htmlspecialchars($m['nama']) ?></strong></td>
        <td><?= $m['nim'] ?></td>
        <td><small><?= htmlspecialchars($m['prodi']) ?></small></td>
        <td><span class="badge badge-<?= $m['akun_status']==='active'?'active':'pending' ?>"><?= $m['akun_status']??'inactive' ?></span></td>
        <td style="text-align:center"><?= $jml_log ?> kegiatan</td>
        <td style="text-align:center">
          <?php if ($nilai): ?>
          <strong style="color:#276749"><?= $nilai['nilai_akhir'] ?></strong>
          <?php else: ?><span style="color:#8A96A8;font-size:.78rem">—</span><?php endif; ?>
        </td>
      </tr>
      <?php endforeach; ?>
    </table>
  </div>
</div>

<?php elseif ($page === 'logbook'): ?>
<?php
$mhs_id = (int)($_GET['mhs_id'] ?? 0);
if ($mhs_id) {
    $sel_mhs = fetch("SELECT * FROM kkn_mahasiswa WHERE id=? AND dpl_id=?", [$mhs_id, $dpl['id']]);
    if ($sel_mhs) {
        $logs = fetchAll("SELECT * FROM kkn_logbook WHERE mahasiswa_id=? ORDER BY minggu,kegiatan_no", [$mhs_id]);
    }
}
?>
<div class="card">
  <div class="card-header"><h3><i class="ti ti-notebook" aria-hidden="true"></i> Logbook Mahasiswa</h3></div>
  <div class="card-body" style="padding:1.25rem;">
    <div class="form-group">
      <label>Pilih Mahasiswa</label>
      <select onchange="window.location='?page=logbook&mhs_id='+this.value">
        <option value="">-- Pilih Mahasiswa --</option>
        <?php foreach ($mhs_list as $m): ?>
        <option value="<?= $m['id'] ?>" <?= $mhs_id==$m['id']?'selected':'' ?>><?= htmlspecialchars($m['nama']) ?> (<?= $m['nim'] ?>)</option>
        <?php endforeach; ?>
      </select>
    </div>
    <?php if (isset($logs) && $sel_mhs): ?>
    <table style="margin-top:1rem;">
      <tr><th>Minggu</th><th>Kegiatan</th><th>Tanggal</th><th>Deskripsi</th><th>Bukti</th></tr>
      <?php foreach ($logs as $l): ?>
      <tr>
        <td style="text-align:center"><strong><?= $l['minggu'] ?></strong></td>
        <td><?= htmlspecialchars($l['nama_kegiatan']) ?></td>
        <td><small><?= $l['waktu']?:'-' ?></small></td>
        <td style="font-size:.8rem;max-width:200px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;"><?= htmlspecialchars(substr($l['deskripsi']??'',0,60)) ?></td>
        <td><?= $l['bukti_link'] ? '<a href="'.htmlspecialchars($l['bukti_link']).'" target="_blank" style="color:#1A56A4;font-size:.78rem;"><i class="ti ti-external-link"></i></a>' : '-' ?></td>
      </tr>
      <?php endforeach; ?>
      <?php if (!$logs): ?>
      <tr><td colspan="5" style="text-align:center;color:#8A96A8;padding:1.5rem;">Belum ada logbook.</td></tr>
      <?php endif; ?>
    </table>
    <?php endif; ?>
  </div>
</div>

<?php elseif ($page === 'penilaian'): ?>
<?php
$ok_penilaian = null;
$err_penilaian = null;
// ── Validasi Nilai Desa ───────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['validasi_nilai_desa'])) {
    $status  = in_array($_POST['nd_status']??'', ['disetujui','ditolak']) ? $_POST['nd_status'] : '';
    $catatan = trim($_POST['nd_catatan']??'');
    if ($status) {
        $tbl_nd = fetch("SELECT 1 FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name='kkn_nilai_desa'");
        if ($tbl_nd) {
            query("UPDATE kkn_nilai_desa SET status=?, catatan_dpl=?, validated_at=NOW() WHERE dpl_id=?",
                [$status, $catatan ?: null, $dpl['id']]);
            $nd_val_ok = 'Validasi berhasil disimpan.';
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_nilai'])) {
    $mhs_id_p = (int)$_POST['mhs_id'];
    $k = [];
    for ($i=1;$i<=5;$i++) $k[$i] = (float)($_POST["k$i"] ?? 0);
    $akhir = $k[1]*0.15 + $k[2]*0.20 + $k[3]*0.25 + $k[4]*0.25 + $k[5]*0.15;
    $catatan = trim($_POST['catatan'] ?? '');
    $existing = fetch("SELECT id FROM kkn_penilaian WHERE mahasiswa_id=? AND dpl_id=?", [$mhs_id_p, $dpl['id']]);
    if ($existing) {
        query("UPDATE kkn_penilaian SET nilai_k1=?,nilai_k2=?,nilai_k3=?,nilai_k4=?,nilai_k5=?,nilai_akhir=?,catatan=? WHERE mahasiswa_id=? AND dpl_id=?",
            [$k[1],$k[2],$k[3],$k[4],$k[5],round($akhir,2),$catatan,$mhs_id_p,$dpl['id']]);
    } else {
        insert("INSERT INTO kkn_penilaian (mahasiswa_id,dpl_id,nilai_k1,nilai_k2,nilai_k3,nilai_k4,nilai_k5,nilai_akhir,catatan) VALUES (?,?,?,?,?,?,?,?,?)",
            [$mhs_id_p,$dpl['id'],$k[1],$k[2],$k[3],$k[4],$k[5],round($akhir,2),$catatan]);
    }
    $ok_penilaian = 'Nilai berhasil disimpan!';
}
$mhs_id_p = (int)($_GET['mhs_id'] ?? $_POST['mhs_id'] ?? 0);
$existing_nilai = $mhs_id_p ? fetch("SELECT * FROM kkn_penilaian WHERE mahasiswa_id=? AND dpl_id=?", [$mhs_id_p, $dpl['id']]) : null;
?>
<?php if ($ok_penilaian): ?>
<div class="alert alert-success"><i class="ti ti-check" aria-hidden="true"></i> <?= $ok_penilaian ?></div>
<?php endif; ?>
<div class="card">
  <div class="card-header"><h3><i class="ti ti-chart-bar" aria-hidden="true"></i> Input Penilaian</h3></div>
  <div class="card-body" style="padding:1.25rem 1.5rem;">
    <div class="form-group">
      <label>Pilih Mahasiswa</label>
      <select onchange="window.location='?page=penilaian&mhs_id='+this.value">
        <option value="">-- Pilih Mahasiswa --</option>
        <?php foreach ($mhs_list as $m): ?>
        <option value="<?= $m['id'] ?>" <?= $mhs_id_p==$m['id']?'selected':'' ?>><?= htmlspecialchars($m['nama']) ?> (<?= $m['nim'] ?>)</option>
        <?php endforeach; ?>
      </select>
    </div>
    <?php if ($mhs_id_p): ?>
    <form method="POST">
      <input type="hidden" name="save_nilai" value="1">
      <input type="hidden" name="mhs_id" value="<?= $mhs_id_p ?>">
      <?php
      $komponen = [
        1 => ['Kedisiplinan & Kehadiran', 15],
        2 => ['Observasi & Perencanaan', 20],
        3 => ['Pelaksanaan Program', 25],
        4 => ['Luaran KKN', 25],
        5 => ['Sikap & Kompetensi', 15],
      ];
      foreach ($komponen as $i => [$label, $bobot]):
        $val = $existing_nilai["nilai_k$i"] ?? '';
      ?>
      <div style="display:grid;grid-template-columns:1fr 120px;gap:1rem;align-items:center;padding:.75rem 0;border-bottom:1px solid #F0F4F8;">
        <div>
          <div style="font-size:.88rem;font-weight:600;color:#0D2E5C;">K<?= $i ?> — <?= $label ?></div>
          <div style="font-size:.75rem;color:#8A96A8;">Bobot <?= $bobot ?>% · Nilai 0–100</div>
        </div>
        <input type="number" name="k<?= $i ?>" min="0" max="100" step="0.5"
               value="<?= $val ?>" placeholder="0–100"
               style="text-align:center;font-size:1rem;font-weight:600;">
      </div>
      <?php endforeach; ?>
      <div class="form-group" style="margin-top:1rem;">
        <label>Catatan DPL (opsional)</label>
        <textarea name="catatan" rows="3" placeholder="Masukkan catatan atau saran untuk mahasiswa..."><?= htmlspecialchars($existing_nilai['catatan'] ?? '') ?></textarea>
      </div>
      <button type="submit" class="btn btn-gold" style="width:100%;padding:12px;">
        <i class="ti ti-device-floppy" aria-hidden="true"></i> Simpan Penilaian
      </button>
    </form>
    <?php endif; ?>
  </div>
</div>

<?php elseif ($page === 'rekap'): ?>
<?php
$rekap = fetchAll("SELECT m.nama,m.nim,m.prodi,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_penilaian p ON p.mahasiswa_id=m.id
    WHERE m.dpl_id=? ORDER BY m.nama", [$dpl['id']]);
?>
<div class="card">
  <div class="card-header">
    <h3><i class="ti ti-list" aria-hidden="true"></i> Rekap Nilai — <?= $dpl['kecamatan'] ?></h3>
  </div>
  <div class="card-body" style="padding:0">
    <table>
      <tr><th>Nama</th><th>NIM</th><th>K1</th><th>K2</th><th>K3</th><th>K4</th><th>K5</th><th>Akhir</th></tr>
      <?php foreach ($rekap as $r): ?>
      <tr>
        <td><strong><?= htmlspecialchars($r['nama']) ?></strong></td>
        <td><?= $r['nim'] ?></td>
        <td><?= $r['nilai_k1']??'-' ?></td>
        <td><?= $r['nilai_k2']??'-' ?></td>
        <td><?= $r['nilai_k3']??'-' ?></td>
        <td><?= $r['nilai_k4']??'-' ?></td>
        <td><?= $r['nilai_k5']??'-' ?></td>
        <td><strong style="color:<?= ($r['nilai_akhir']??0)>=75?'#276749':'#C53030' ?>"><?= $r['nilai_akhir']??'-' ?></strong></td>
      </tr>
      <?php endforeach; ?>
    </table>
  </div>
</div>

<?php elseif ($page === 'luaran'): ?>
<?php
if (!$tbl_luaran) { echo '<div class="card"><div class="card-body" style="padding:1.5rem;color:#8A96A8;">Tabel luaran belum dibuat. Hubungi admin LPPM.</div></div>'; dashClose(); exit; }
$luaran_individu = fetchAll("SELECT l.*,m.nama as nama_mhs,m.nim FROM kkn_luaran l JOIN kkn_mahasiswa m ON m.id=l.mahasiswa_id WHERE m.dpl_id=? ORDER BY m.nama,l.jenis", [$dpl['id']]);
$lu_by_mhs = [];
foreach ($luaran_individu as $l) $lu_by_mhs[$l['mahasiswa_id']][$l['jenis']] = $l;
?>
<div class="card">
  <div class="card-header">
    <h3><i class="ti ti-file-text" aria-hidden="true"></i> Luaran Individu Mahasiswa</h3>
    <a href="?page=luaran&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 / NIM</th><th>Prodi</th><th style="text-align:center">Artikel Jurnal</th><th style="text-align:center">Artikel Media</th></tr>
      <?php foreach ($mhs_list as $m): $lu = $lu_by_mhs[$m['id']] ?? []; ?>
      <tr>
        <td><strong><?= htmlspecialchars($m['nama']) ?></strong><br><small style="color:#8A96A8"><?= $m['nim'] ?></small></td>
        <td><small><?= htmlspecialchars($m['prodi']) ?></small></td>
        <td style="text-align:center"><?= isset($lu['artikel_jurnal'],$lu['artikel_jurnal']['link_url']) ? '<a href="'.htmlspecialchars($lu['artikel_jurnal']['link_url']).'" target="_blank" style="color:#1A56A4;font-size:.8rem;"><i class="ti ti-external-link"></i> Buka</a>' : '<span style="color:#D1D5DB">—</span>' ?></td>
        <td style="text-align:center"><?= isset($lu['artikel_media'],$lu['artikel_media']['link_url']) ? '<a href="'.htmlspecialchars($lu['artikel_media']['link_url']).'" target="_blank" style="color:#1A56A4;font-size:.8rem;"><i class="ti ti-external-link"></i> Buka</a>' : '<span style="color:#D1D5DB">—</span>' ?></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. Hubungi admin LPPM.</div></div>'; dashClose(); exit; }
$luaran_kel = fetchAll("SELECT * FROM kkn_luaran_kelompok WHERE dpl_id=? ORDER BY jenis", [$dpl['id']]);
$lk = array_column($luaran_kel, null, 'jenis');
$label_jenis = ['rpk'=>'RPK','laporan'=>'Laporan Kelompok','poster'=>'Poster','video'=>'Video Dokumentasi'];
?>
<div class="card">
  <div class="card-header">
    <h3><i class="ti ti-users" aria-hidden="true"></i> Luaran Kelompok — <?= $dpl['kecamatan'] ?></h3>
    <a href="?page=luaran_kel&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>Jenis Luaran</th><th>Judul</th><th>Tanggal</th><th style="text-align:center">Link</th></tr>
      <?php foreach (['rpk','laporan','poster','video'] as $j): $it = $lk[$j] ?? null; ?>
      <tr>
        <td><strong><?= $label_jenis[$j] ?></strong></td>
        <td style="font-size:.82rem"><?= $it ? htmlspecialchars($it['judul']) : '<span style="color:#8A96A8">—</span>' ?></td>
        <td style="font-size:.78rem;color:#8A96A8"><?= $it ? date('d M Y', strtotime($it['uploaded_at'])) : '—' ?></td>
        <td style="text-align:center">
          <?php if ($it && $it['link_url']): ?>
          <a href="<?= htmlspecialchars($it['link_url']) ?>" target="_blank" style="color:#1A56A4;font-size:.8rem;"><i class="ti ti-external-link" aria-hidden="true"></i> Buka</a>
          <?php else: ?><span style="color:#D1D5DB;font-size:.78rem">Belum upload</span><?php endif; ?>
        </td>
      </tr>
      <?php endforeach; ?>
    </table>
  </div>
</div>

<?php elseif ($page === 'nilai_desa'): ?>
<?php
$tbl_nd = fetch("SELECT 1 FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name='kkn_nilai_desa'");
$nd_all = $tbl_nd ? fetchAll("SELECT nd.*, m.nama as mhs_nama, m.nim FROM kkn_nilai_desa nd
    JOIN kkn_mahasiswa m ON m.id=nd.mahasiswa_id
    WHERE nd.dpl_id=? ORDER BY m.nama", [$dpl['id']]) : [];
$nd_link_bukti = '';
foreach($nd_all as $_r) { if(!empty($_r['link_bukti'])) { $nd_link_bukti=$_r['link_bukti']; break; } }
$nd_status  = $nd_all ? ($nd_all[0]['status']??'pending') : null;
$nd_catatan = $nd_all ? ($nd_all[0]['catatan_dpl']??'') : '';
?>
<div class="card">
  <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($nd_status): ?>
    <?php if($nd_status==='disetujui'): ?>
      <span style="background:#D1FAE5;color:#065F46;font-size:.72rem;font-weight:700;padding:3px 12px;border-radius:20px;"><i class="ti ti-check"></i> Divalidasi</span>
    <?php elseif($nd_status==='ditolak'): ?>
      <span style="background:#FEE2E2;color:#991B1B;font-size:.72rem;font-weight:700;padding:3px 12px;border-radius:20px;"><i class="ti ti-x"></i> Ditolak</span>
    <?php else: ?>
      <span style="background:#FEF3C7;color:#92400E;font-size:.72rem;font-weight:700;padding:3px 12px;border-radius:20px;"><i class="ti ti-clock"></i> Menunggu Validasi</span>
    <?php endif; ?>
    <?php endif; ?>
  </div>
  <div class="card-body" style="padding:1.25rem 1.5rem;">
    <?php if(isset($nd_val_ok)): ?>
    <div class="alert alert-success" style="margin-bottom:1rem;"><i class="ti ti-check"></i> <?= htmlspecialchars($nd_val_ok) ?></div>
    <?php endif; ?>
    <?php if(empty($nd_all)): ?>
    <div style="text-align:center;padding:2rem;color:#A0AEC0;font-size:.85rem;">
      <i class="ti ti-star-off" style="font-size:2rem;display:block;margin-bottom:.5rem;"></i>
      Belum ada nilai yang diinput mahasiswa.
    </div>
    <?php else: ?>
    <div style="overflow-x:auto;margin-bottom:1.25rem;">
      <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;color:#64748b;font-weight:600;">Nama</th>
            <th style="padding:8px 6px;text-align:center;border-bottom:2px solid #E2E8F0;color:#64748b;font-size:.72rem;font-weight:600;">Inisiatif<br>/20</th>
            <th style="padding:8px 6px;text-align:center;border-bottom:2px solid #E2E8F0;color:#64748b;font-size:.72rem;font-weight:600;">Tg.Jawab<br>/20</th>
            <th style="padding:8px 6px;text-align:center;border-bottom:2px solid #E2E8F0;color:#64748b;font-size:.72rem;font-weight:600;">Kerjasama<br>/20</th>
            <th style="padding:8px 6px;text-align:center;border-bottom:2px solid #E2E8F0;color:#64748b;font-size:.72rem;font-weight:600;">Kehadiran<br>/20</th>
            <th style="padding:8px 6px;text-align:center;border-bottom:2px solid #E2E8F0;color:#64748b;font-size:.72rem;font-weight:600;">Capaian<br>/20</th>
            <th style="padding:8px 6px;text-align:center;border-bottom:2px solid #E2E8F0;color:#64748b;font-size:.72rem;font-weight:600;">Total<br>/100</th>
          </tr>
        </thead>
        <tbody>
        <?php foreach($nd_all as $ndrow): ?>
        <tr style="border-bottom:1px solid #F5F7FA;">
          <td style="padding:8px 10px;vertical-align:middle;">
            <div style="font-weight:600;color:#0D2E5C;"><?= htmlspecialchars($ndrow['mhs_nama']) ?></div>
            <div style="font-size:.68rem;color:#8A96A8;"><?= $ndrow['nim'] ?></div>
          </td>
          <td style="text-align:center;padding:6px 4px;"><?= $ndrow['n1'] ?></td>
          <td style="text-align:center;padding:6px 4px;"><?= $ndrow['n2'] ?></td>
          <td style="text-align:center;padding:6px 4px;"><?= $ndrow['n3'] ?></td>
          <td style="text-align:center;padding:6px 4px;"><?= $ndrow['n4'] ?></td>
          <td style="text-align:center;padding:6px 4px;"><?= $ndrow['n5'] ?></td>
          <td style="text-align:center;padding:6px 4px;font-weight:700;color:#0D2E5C;"><?= $ndrow['total'] ?></td>
        </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    </div>
    <?php if(!empty($nd_link_bukti)): ?>
    <div style="margin-bottom:1.25rem;font-size:.8rem;">
      <i class="ti ti-file-check" style="color:#1A56A4;"></i>
      <a href="<?= htmlspecialchars($nd_link_bukti) ?>" target="_blank" style="color:#1A56A4;font-weight:600;">
        Lihat Bukti Scan Lembar Penilaian <i class="ti ti-external-link" style="font-size:.7rem;"></i>
      </a>
    </div>
    <?php endif; ?>
    <div style="border:1px solid #E2E8F0;border-radius:8px;padding:1rem 1.25rem;">
      <div style="font-size:.82rem;font-weight:700;color:#0D2E5C;margin-bottom:.875rem;">Validasi Nilai</div>
      <form method="POST">
        <input type="hidden" name="validasi_nilai_desa" value="1">
        <div class="form-group">
          <label style="font-size:.8rem;font-weight:600;">Keputusan</label>
          <div style="display:flex;gap:1rem;margin-top:.375rem;">
            <label style="display:flex;align-items:center;gap:6px;font-size:.82rem;cursor:pointer;">
              <input type="radio" name="nd_status" value="disetujui" <?= $nd_status==='disetujui'?'checked':'' ?>>
              <span style="color:#276749;font-weight:600;">✓ Setuju / Validasi</span>
            </label>
            <label style="display:flex;align-items:center;gap:6px;font-size:.82rem;cursor:pointer;">
              <input type="radio" name="nd_status" value="ditolak" <?= $nd_status==='ditolak'?'checked':'' ?>>
              <span style="color:#C53030;font-weight:600;">✗ Tolak</span>
            </label>
          </div>
        </div>
        <div class="form-group" style="margin:0;">
          <label style="font-size:.8rem;font-weight:600;">Catatan (opsional)</label>
          <textarea name="nd_catatan" rows="2" placeholder="Contoh: Nilai tidak sesuai, mohon dicek ulang..."
            style="margin-top:.375rem;"><?= htmlspecialchars($nd_catatan) ?></textarea>
        </div>
        <button type="submit" class="btn btn-primary" style="margin-top:.75rem;padding:8px 18px;font-size:.82rem;">
          <i class="ti ti-check" aria-hidden="true"></i> Simpan Validasi
        </button>
      </form>
    </div>
    <?php endif; ?>
  </div>
</div>

<?php elseif ($page === 'proker_ind'): ?>
<?php
$all_mhs_dpl    = fetchAll("SELECT m.* FROM kkn_mahasiswa m WHERE m.dpl_id=? ORDER BY m.nama", [$dpl['id']]);
$proker_ind_all = fetchAll("SELECT pi.*, m.nama as mhs_nama, m.nim, m.prodi FROM kkn_proker_individu pi JOIN kkn_mahasiswa m ON m.id=pi.mahasiswa_id WHERE m.dpl_id=? ORDER BY m.nama, pi.created_at", [$dpl['id']]);
$pi_by_mhs      = [];
foreach($proker_ind_all as $pi) $pi_by_mhs[$pi['mahasiswa_id']][] = $pi;
?>
<div class="card">
  <div class="card-header">
    <h3><i class="ti ti-user" aria-hidden="true"></i> Program Kerja Individu — Kec. <?= $dpl['kecamatan'] ?>
      <span style="background:#0D2E5C;color:#fff;padding:2px 9px;border-radius:20px;font-size:.7rem;margin-left:6px;"><?= count($proker_ind_all) ?> proker</span>
    </h3>
  </div>
  <style>.proker-table td{vertical-align:top!important;padding-top:7px;}</style>
  <div class="card-body" style="padding:0;">
    <table class="proker-table">
      <colgroup>
        <col style="width:13%">
        <col style="width:18%">
        <col style="width:28%">
        <col style="width:20%">
        <col style="width:10%">
        <col style="width:11%">
      </colgroup>
      <tr><th>Mahasiswa</th><th>Judul Program Kerja</th><th>Deskripsi</th><th>Sasaran Kegiatan</th><th>Target Luaran</th><th>Waktu Input</th></tr>
      <?php foreach($all_mhs_dpl as $m):
        $pis = $pi_by_mhs[$m['id']] ?? [];
        if(empty($pis)): ?>
      <tr>
        <td style="vertical-align:top;"><strong style="font-size:.78rem;"><?= htmlspecialchars($m['nama']) ?></strong><div style="font-size:.68rem;color:#8A96A8;"><?= $m['nim'] ?></div></td>
        <td colspan="5" style="vertical-align:top;"><span style="color:#F59E0B;font-size:.78rem;"><i class="ti ti-alert-triangle"></i> Belum diisi</span></td>
      </tr>
        <?php else:
        foreach($pis as $pi): ?>
      <tr>
        <td style="vertical-align:top;"><strong style="font-size:.78rem;"><?= htmlspecialchars($m['nama']) ?></strong><div style="font-size:.68rem;color:#8A96A8;"><?= $m['nim'] ?> · <?= htmlspecialchars($m['prodi']) ?></div></td>
        <td style="vertical-align:top;font-size:.78rem;font-weight:600;"><?= htmlspecialchars($pi['judul']) ?></td>
        <td style="vertical-align:top;font-size:.72rem;color:#64748b;min-width:220px;"><?= htmlspecialchars($pi['deskripsi']??'-') ?></td>
        <td style="vertical-align:top;font-size:.75rem;"><?= htmlspecialchars($pi['target']??'-') ?></td>
        <td><?php if($pi['target_luaran']??''): ?><span style="font-size:.75rem;color:#1A56A4;font-weight:500;"><?= htmlspecialchars($pi['target_luaran']) ?></span><?php else: ?>—<?php endif; ?></td>
        <td style="vertical-align:top;font-size:.72rem;color:#8A96A8;"><?php if($pi['created_at']): ?><span style="display:block;"><?= date('d M Y', strtotime($pi['created_at'])) ?></span><span style="display:block;color:#A0AEC0;"><?= date('H:i', strtotime($pi['created_at'])) ?></span><?php else: ?>—<?php endif; ?></td>
      </tr>
        <?php endforeach; endif; ?>
      <?php endforeach; ?>
    </table>
  </div>
</div>

<?php elseif ($page === 'proker_kel'): ?>
<?php
$proker_kel_all = fetchAll("SELECT pk.*, m.nama as input_nama FROM kkn_proker_kelompok pk JOIN kkn_mahasiswa m ON m.id=pk.input_by WHERE pk.dpl_id=? ORDER BY pk.created_at", [$dpl['id']]);
?>
<div class="card">
  <div class="card-header">
    <h3><i class="ti ti-users" aria-hidden="true"></i> Program Kerja Kelompok — Kec. <?= $dpl['kecamatan'] ?>
      <span style="background:#0D2E5C;color:#fff;padding:2px 9px;border-radius:20px;font-size:.7rem;margin-left:6px;"><?= count($proker_kel_all) ?> proker</span>
    </h3>
  </div>
  <?php if($proker_kel_all): ?>
  <div class="card-body" style="padding:0;">
    <table class="proker-table">
      <colgroup>
        <col style="width:4%">
        <col style="width:15%">
        <col style="width:27%">
        <col style="width:20%">
        <col style="width:12%">
        <col style="width:10%">
        <col style="width:12%">
      </colgroup>
      <tr><th>#</th><th>Judul Program Kerja Kelompok</th><th>Deskripsi</th><th>Sasaran Kegiatan</th><th>Target Luaran</th><th>Diinput oleh</th><th>Waktu Input</th></tr>

      <?php foreach($proker_kel_all as $i=>$pk): ?>
      <tr>
        <td style="color:#8A96A8;font-size:.75rem;"><?= $i+1 ?></td>
        <td style="font-size:.78rem;font-weight:600;"><?= htmlspecialchars($pk['judul']) ?></td>
        <td style="font-size:.72rem;color:#64748b;min-width:220px;"><?= htmlspecialchars($pk['deskripsi']??'-') ?></td>
        <td style="font-size:.75rem;"><?= htmlspecialchars($pk['target']??'-') ?></td>
        <td><?php if($pk['target_luaran']??''): ?><span style="font-size:.75rem;color:#1A56A4;font-weight:500;"><?= htmlspecialchars($pk['target_luaran']) ?></span><?php else: ?>—<?php endif; ?></td>
        <td style="font-size:.72rem;color:#8A96A8;"><?= htmlspecialchars($pk['input_nama']) ?></td>
        <td style="font-size:.72rem;color:#8A96A8;"><?php if($pk['created_at']): ?><span style="display:block;"><?= date('d M Y', strtotime($pk['created_at'])) ?></span><span style="display:block;color:#A0AEC0;"><?= date('H:i', strtotime($pk['created_at'])) ?></span><?php else: ?>—<?php endif; ?></td>
      </tr>
      <?php endforeach; ?>
    </table>
  </div>
  <?php else: ?>
  <div style="padding:2rem;text-align:center;color:#8A96A8;font-size:.82rem;"><i class="ti ti-users" style="font-size:2rem;display:block;margin-bottom:.5rem;color:#CBD5E0;"></i>Belum ada program kerja kelompok yang diinput.</div>
  <?php endif; ?>
</div>
<?php endif; ?>

<?php dashClose(); ?>
