<?php
session_start();
if (empty($_SESSION['login'])) { header('Location: ../index.php'); exit; }
require_once '../config/koneksi.php';

if (!function_exists('e')) {
    function e($value) { return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8'); }
}

function logo_src($nama_file, $default = '')
{
    $nama_file = trim((string)$nama_file);
    if ($nama_file === '') { $nama_file = $default; }
    if ($nama_file === '') { return ''; }

    $path = '../assets/uploads/' . $nama_file;
    return is_file(__DIR__ . '/../assets/uploads/' . $nama_file) ? $path : '';
}

function tgl_indo($tanggal)
{
    if (!$tanggal || $tanggal === '0000-00-00') { return '-'; }
    $bulan = [1=>'Januari','Februari','Maret','April','Mei','Juni','Juli','Agustus','September','Oktober','November','Desember'];
    $ts = strtotime($tanggal);
    return date('j', $ts) . ' ' . $bulan[(int)date('n', $ts)] . ' ' . date('Y', $ts);
}

function hitung_rata_ujian($conn, $siswa_id, $tahun)
{
    $stmt = $conn->prepare('SELECT AVG(nilai) AS rata FROM nilai WHERE siswa_id=? AND tahun_pelajaran=?');
    $stmt->bind_param('is', $siswa_id, $tahun);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc();
    return $row && $row['rata'] !== null ? round((float)$row['rata'], 2) : 0;
}

$profil = $conn->query('SELECT * FROM profil_sekolah LIMIT 1')->fetch_assoc();
$tahun = $_GET['tahun'] ?? ($profil['tahun_pelajaran'] ?? '2025/2026');
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if (($_SESSION['role'] ?? '') === 'siswa') {
    $id = (int)($_SESSION['siswa_id'] ?? 0);
}

$kelas = $_GET['kelas'] ?? '';

$mapels = [];
$qm = $conn->query('SELECT * FROM mapel ORDER BY urutan ASC, nama_mapel ASC');
while ($m = $qm->fetch_assoc()) { $mapels[] = $m; }

$where = '1=1';
$params = [];
$types = '';
if ($id > 0) {
    $where = 'id=?';
    $params[] = $id;
    $types .= 'i';
} elseif ($kelas !== '') {
    $where = 'kelas=?';
    $params[] = $kelas;
    $types .= 's';
}
$stmt = $conn->prepare("SELECT * FROM siswa WHERE $where ORDER BY kelas ASC, nama ASC");
if ($params) { $stmt->bind_param($types, ...$params); }
$stmt->execute();
$siswaQ = $stmt->get_result();
?>
<!doctype html>
<html lang="id">
<head>
<meta charset="utf-8">
<title>Cetak Nilai Siswa</title>
<style>
@page{size:A4 portrait;margin:12mm}body{font-family:Arial,sans-serif;color:#111}.toolbar{margin-bottom:12px}.btn{padding:8px 14px;border:0;border-radius:6px;background:#16a34a;color:white;font-weight:bold;cursor:pointer}.page{page-break-after:always}.page:last-child{page-break-after:auto}.kop{display:grid;grid-template-columns:95px 1fr 95px;align-items:center;border-bottom:3px double #111;padding-bottom:8px;margin-bottom:12px;column-gap:10px}.logo-kop{text-align:center}.logo-kop img{width:82px;height:82px;object-fit:contain}.logo-placeholder{width:82px;height:82px;display:inline-block}.kop .txt{text-align:center}.kop h2,.kop h3,.kop p{margin:1px 0}.kop h3{font-size:15px}.kop h2{font-size:19px}.judul{text-align:center;text-decoration:underline;margin:18px 0 10px}.biodata{font-size:13px;margin-bottom:12px}.biodata td{padding:3px 5px}table.nilai{border-collapse:collapse;width:100%;font-size:12px}table.nilai th,table.nilai td{border:1px solid #333;padding:6px}table.nilai th{background:#e5e7eb;text-align:center}td.center{text-align:center}td.right{text-align:right}.ttd{width:290px;float:right;text-align:center;margin-top:28px;font-size:13px}.space{height:70px}.catatan{font-size:12px;margin-top:12px}@media print{.toolbar{display:none}body{-webkit-print-color-adjust:exact;print-color-adjust:exact}}
</style>
</head>
<body>
<div class="toolbar"><button class="btn" onclick="window.print()">Cetak</button></div>
<?php while ($s = $siswaQ->fetch_assoc()): ?>
<?php
$nilai = [];
$jumlah = 0;
$isi = 0;
foreach ($mapels as $m) {
    $st = $conn->prepare('SELECT nilai FROM nilai WHERE siswa_id=? AND mapel_id=? AND tahun_pelajaran=? LIMIT 1');
    $st->bind_param('iis', $s['id'], $m['id'], $tahun);
    $st->execute();
    $n = $st->get_result()->fetch_assoc();
    $val = $n ? (float)$n['nilai'] : null;
    $nilai[$m['id']] = $val;
    if ($val !== null) { $jumlah += $val; $isi++; }
}
$rataUjian = $isi ? round($jumlah / $isi, 2) : hitung_rata_ujian($conn, (int)$s['id'], $tahun);
$k5s1 = (float)($s['nilai_k5_s1'] ?? 0);
$k5s2 = (float)($s['nilai_k5_s2'] ?? 0);
$k6s1 = (float)($s['nilai_k6_s1'] ?? 0);
$rataRaport = round(($k5s1 + $k5s2 + $k6s1) / 3, 2);
$nilaiAkhir = round(($rataRaport * 0.70) + ($rataUjian * 0.30), 2);
?>
<div class="page">
    <?php
    $logoDinas = logo_src($profil['logo_kabupaten'] ?? '');
    $logoSekolah = logo_src($profil['logo'] ?? '', 'logo.png');
    ?>
    <div class="kop">
        <div class="logo-kop">
            <?php if ($logoDinas !== ''): ?>
                <img src="<?= e($logoDinas) ?>" alt="Logo Dinas">
            <?php else: ?>
                <span class="logo-placeholder"></span>
            <?php endif; ?>
        </div>
        <div class="txt">
            <h3>PEMERINTAH KABUPATEN <?= e(strtoupper($profil['nama_kabupaten'] ?? '')) ?></h3>
            <h3>DINAS PENDIDIKAN DAN KEBUDAYAAN</h3>
            <h2><?= e(strtoupper($profil['nama_sekolah'] ?? '')) ?></h2>
            <p><?= e($profil['alamat'] ?? '') ?></p>
        </div>
        <div class="logo-kop">
            <?php if ($logoSekolah !== ''): ?>
                <img src="<?= e($logoSekolah) ?>" alt="Logo Sekolah">
            <?php else: ?>
                <span class="logo-placeholder"></span>
            <?php endif; ?>
        </div>
    </div>

    <h3 class="judul">DAFTAR NILAI SISWA</h3>

    <table class="biodata">
        <tr><td>Nama Siswa</td><td>:</td><td><b><?= e($s['nama'] ?? '-') ?></b></td></tr>
        <tr><td>NISN</td><td>:</td><td><?= e($s['nisn'] ?? '-') ?></td></tr>
        <tr><td>No. Ujian</td><td>:</td><td><?= e($s['no_ujian'] ?? '-') ?></td></tr>
        <tr><td>Kelas</td><td>:</td><td><?= e($s['kelas'] ?? '-') ?></td></tr>
        <tr><td>Tahun Pelajaran</td><td>:</td><td><?= e($tahun) ?></td></tr>
    </table>

    <table class="nilai">
        <thead><tr><th width="40">No</th><th>Mata Pelajaran</th><th width="120">Nilai Ujian</th></tr></thead>
        <tbody>
        <?php $no=1; foreach ($mapels as $m): ?>
            <tr><td class="center"><?= $no++ ?></td><td><?= e($m['nama_mapel']) ?></td><td class="center"><?= $nilai[$m['id']] === null ? '-' : e(number_format($nilai[$m['id']], 2, ',', '.')) ?></td></tr>
        <?php endforeach; ?>
            <tr><td colspan="2" class="right"><b>Jumlah Nilai Ujian</b></td><td class="center"><b><?= e(number_format($jumlah, 2, ',', '.')) ?></b></td></tr>
            <tr><td colspan="2" class="right"><b>Rata-rata Ujian</b></td><td class="center"><b><?= e(number_format($rataUjian, 2, ',', '.')) ?></b></td></tr>
            <tr><td colspan="2" class="right">Rata-rata Raport</td><td class="center"><?= e(number_format($rataRaport, 2, ',', '.')) ?></td></tr>
            <tr><td colspan="2" class="right"><b>Nilai Akhir</b></td><td class="center"><b><?= e(number_format($nilaiAkhir, 2, ',', '.')) ?></b></td></tr>
        </tbody>
    </table>

    <div class="catatan">Keterangan: Nilai akhir dihitung dari 70% rata-rata raport dan 30% rata-rata ujian.</div>

    <div class="ttd">
        <p><?= e($profil['nama_kabupaten'] ?? '') ?>, <?= e(tgl_indo(date('Y-m-d'))) ?></p>
        <p>Kepala Sekolah</p>
        <div class="space"></div>
        <b><u><?= e($profil['kepala_sekolah'] ?? '') ?></u></b><br>
        NIP. <?= e($profil['nip_kepsek'] ?? '') ?>
    </div>
</div>
<?php endwhile; ?>
</body>
</html>
