<?php
// Start session dengan nama yang sama seperti sistem KKN
session_name('kkn_session');
session_start();

require_once dirname(__DIR__) . '/includes/config.php';
require_once dirname(__DIR__) . '/includes/db.php';

// Cek login manual
if (!isset($_SESSION['kkn_user_id']) || ($_SESSION['kkn_role'] ?? '') !== 'admin') {
    http_response_code(403);
    exit('Akses ditolak. Silakan login sebagai admin terlebih dahulu.');
}

$tbl_luaran = fetch("SELECT 1 FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name='kkn_luaran'");
if (!$tbl_luaran) { echo 'Tabel belum ada.'; exit; }

$rows = fetchAll("SELECT m.nama,m.nim,m.prodi,d.kecamatan,d.kabupaten,d.nama as nama_dpl,
    MAX(CASE WHEN l.jenis='artikel_jurnal' THEN l.judul END) as j_jurnal,
    MAX(CASE WHEN l.jenis='artikel_jurnal' THEN l.link_url END) as l_jurnal,
    MAX(CASE WHEN l.jenis='artikel_jurnal' THEN l.filename END) as f_jurnal,
    MAX(CASE WHEN l.jenis='artikel_media' THEN l.judul END) as j_media,
    MAX(CASE WHEN l.jenis='artikel_media' THEN l.link_url END) as l_media,
    MAX(CASE WHEN l.jenis='artikel_media' THEN l.filename END) as f_media
    FROM kkn_mahasiswa m LEFT JOIN kkn_dpl d ON d.id=m.dpl_id
    LEFT JOIN kkn_luaran l ON l.mahasiswa_id=m.id
    GROUP BY m.id ORDER BY d.kecamatan,m.nama");

header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=luaran_individu_'.date('Ymd').'.csv');
header('Cache-Control: no-cache, no-store, must-revalidate');
echo "\xEF\xBB\xBF";
echo "No,Nama,NIM,Prodi,Kecamatan,Kabupaten,DPL,Judul Jurnal,Link Jurnal,Status Jurnal,Judul Media,Link Media,Status Media\n";
$no = 1;
foreach ($rows as $r) {
    echo implode(',', [
        $no++,
        '"'.str_replace('"','""',$r['nama']).'"',
        '"'.$r['nim'].'"',
        '"'.str_replace('"','""',$r['prodi']).'"',
        '"'.$r['kecamatan'].'"',
        '"'.$r['kabupaten'].'"',
        '"'.str_replace('"','""',$r['nama_dpl']).'"',
        '"'.str_replace('"','""',($r['j_jurnal']??'')).'"',
        '"'.str_replace('"','""',($r['l_jurnal']??'')).'"',
        ($r['l_jurnal']||$r['f_jurnal']) ? 'Sudah' : 'Belum',
        '"'.str_replace('"','""',($r['j_media']??'')).'"',
        '"'.str_replace('"','""',($r['l_media']??'')).'"',
        ($r['l_media']||$r['f_media']) ? 'Sudah' : 'Belum',
    ])."\n";
}
exit;
