<?php
/**
 * SISPENRA - Export Handler
 */
require_once __DIR__ . '/../includes/functions.php';

function exportNilaiToCSV($kelasId, $mapelId, $tahunAjaran, $semester) {
    $mapel = db_fetch("SELECT * FROM mata_pelajaran WHERE id = ?", [$mapelId]);
    $kelas = db_fetch("SELECT * FROM kelas WHERE id = ?", [$kelasId]);

    $siswas = db_fetchAll("
        SELECT s.nis, s.nama, s.jenis_kelamin,
               n.nilai_tugas, n.nilai_harian, n.nilai_uts, n.nilai_uas, n.nilai_akhir, n.predikat
        FROM siswa s
        LEFT JOIN nilai n ON n.siswa_id = s.id AND n.mapel_id = ? AND n.kelas_id = ? AND n.tahun_ajaran = ? AND n.semester = ?
        WHERE s.kelas_id = ? AND s.status = 'aktif'
        ORDER BY s.nama
    ", [$mapelId, $kelasId, $tahunAjaran, $semester, $kelasId]);

    $filename = "nilai_{$kelas['nama_kelas']}_{$mapel['kode_mapel']}_sem{$semester}.csv";

    header('Content-Type: text/csv; charset=utf-8');
    header("Content-Disposition: attachment; filename={$filename}");

    $output = fopen('php://output', 'w');
    fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF)); // UTF-8 BOM

    fputcsv($output, ['NIS', 'Nama', 'L/P', 'Tugas', 'Harian', 'UTS', 'UAS', 'Nilai Akhir', 'Predikat']);

    foreach ($siswas as $s) {
        fputcsv($output, [
            $s['nis'], $s['nama'], $s['jenis_kelamin'],
            $s['nilai_tugas'], $s['nilai_harian'], $s['nilai_uts'], $s['nilai_uas'],
            $s['nilai_akhir'], $s['predikat'],
        ]);
    }

    fclose($output);
    exit;
}

function exportSiswaToCSV($kelasId = null) {
    $where = "WHERE status = 'aktif'";
    $params = [];
    if ($kelasId) { $where .= " AND kelas_id = ?"; $params[] = $kelasId; }

    $siswas = db_fetchAll("
        SELECT s.nis, s.nisn, s.nama, s.jenis_kelamin, s.tempat_lahir, s.tanggal_lahir,
               s.nama_ayah, s.nama_ibu, s.telepon_ortu, k.nama_kelas
        FROM siswa s LEFT JOIN kelas k ON k.id = s.kelas_id $where ORDER BY k.nama_kelas, s.nama
    ", $params);

    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=data_siswa.csv');
    $output = fopen('php://output', 'w');
    fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF));

    fputcsv($output, ['NIS', 'NISN', 'Nama', 'L/P', 'Tempat Lahir', 'Tgl Lahir', 'Nama Ayah', 'Nama Ibu', 'Telepon', 'Kelas']);
    foreach ($siswas as $s) {
        fputcsv($output, array_values($s));
    }
    fclose($output);
    exit;
}

// Handle export request
if (isset($_GET['export'])) {
    requireLogin();
    $type = $_GET['export'];
    $pengaturan = getPengaturan();

    if ($type === 'nilai') {
        $kelasId = intval($_GET['kelas_id'] ?? 0);
        $mapelId = intval($_GET['mapel_id'] ?? 0);
        if ($kelasId && $mapelId) {
            exportNilaiToCSV($kelasId, $mapelId, $pengaturan['tahun_ajaran_aktif'], $pengaturan['semester_aktif']);
        }
    } elseif ($type === 'siswa') {
        requireAdmin();
        $kelasId = intval($_GET['kelas_id'] ?? 0);
        exportSiswaToCSV($kelasId);
    }
}
