<!DOCTYPE html>
<html lang="id">
<head>
    <?php helper('logo'); ?>
    <link rel="icon" type="image/png" href="<?= getLogo('sekolah') ?>">
    <meta charset="UTF-8">
    <title>Leger Nilai — <?= esc($classroom['name'] ?? '') ?></title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: "Bookman Old Style", Bookman, "URW Bookman L", Georgia, serif;
            font-size: 9pt;
            background: #fff;
        }
        @page {
            size: A4 landscape;
            margin: 10mm 8mm;
        }
        @media print {
            body { margin: 0; }
            .no-print { display: none !important; }
        }

        /* Print button */
        .no-print {
            position: fixed; top: 15px; right: 15px;
            display: flex; gap: 8px; z-index: 999;
        }
        .btn-print {
            background: #0d6efd; color: #fff; border: none;
            padding: 8px 18px; border-radius: 6px; cursor: pointer;
            font-size: 13px;
        }
        .btn-back {
            background: #6c757d; color: #fff; border: none;
            padding: 8px 18px; border-radius: 6px; cursor: pointer;
            font-size: 13px; text-decoration: none;
        }

        /* Header surat */
        .kop {
            display: flex;
            align-items: center;
            border-bottom: 3px solid #000;
            padding-bottom: 6px;
            margin-bottom: 8px;
            gap: 12px;
            font-family: Arial, Helvetica, sans-serif !important;
        }
        .kop-logo img { height: 55px; }
        .kop-logo-placeholder {
            width: 55px; height: 55px;
            background: #eee;
            border-radius: 50%;
            display: flex; align-items: center; justify-content: center;
            font-size: 8pt; color: #aaa;
        }
        .kop-text { flex: 1; text-align: center; }
        .kop-text .nama-madrasah { font-size: 14pt; font-weight: bold; line-height: 1.3; }
        .kop-text .alamat { font-size: 8pt; color: #555; line-height: 1.4; font-weight: normal; }

        .judul-section {
            text-align: center;
            margin: 8px 0 6px;
        }
        .judul-section h2 {
            font-size: 12pt;
            font-weight: bold;
            text-transform: uppercase;
            letter-spacing: 1px;
            margin-bottom: 3px;
        }
        .info-kelas {
            display: flex;
            justify-content: center;
            gap: 24px;
            font-size: 9pt;
            margin-bottom: 8px;
        }
        .info-kelas span { display: inline-block; }

        /* Tabel */
        table {
            width: 100%;
            border-collapse: collapse;
            font-size: 8.5pt;
        }
        th, td {
            border: 1px solid #555;
            padding: 3px 4px;
            text-align: center;
            vertical-align: middle;
        }
        th {
            background: #2c3e50;
            color: #fff;
            font-weight: bold;
        }
        th.group-pai { background: #1a3a5c; }
        th.group-mulok { background: #1a3a5c; }
        th.sub-header { background: #3d5a80; font-size: 8pt; }
        th.avg-header { background: #1a5c2a; }

        .text-left { text-align: left !important; }
        .nama-col { text-align: left !important; padding-left: 5px !important; min-width: 130px; }

        tr:nth-child(even) td { background-color: #f9f9f9; }
        tr:hover td { background-color: #e8f0fe; }

        .score-low { background: #ffcccc !important; color: #c0392b; font-weight: bold; }
        .score-high { color: #1a6600; font-weight: bold; }

        .total-col { font-weight: bold; background: #e8f0fe !important; }
        .rank-gold { color: #b8860b; font-weight: bold; }
        .rank-silver { color: #666; font-weight: bold; }
        .rank-bronze { color: #b45309; font-weight: bold; }

        .avg-row td {
            background: #d4edda !important;
            font-weight: bold;
            font-size: 8pt;
        }

        /* TTD section */
        .ttd-section {
            margin-top: 16px;
            display: flex;
            justify-content: space-between;
            gap: 20px;
        }
        .ttd-box { text-align: center; min-width: 160px; }
        .ttd-box .jabatan { font-size: 8.5pt; margin-bottom: 50px; }
        .ttd-box .nama-ttd { font-size: 9pt; font-weight: bold; padding-top: 3px; }
        .ttd-box .nip-ttd { font-size: 8pt; color: #555; }
    </style>
</head>
<body>

<div class="no-print">
    <a href="javascript:history.back()" class="btn-back">← Kembali</a>
    <button class="btn-print" onclick="window.print()">🖨️ Cetak</button>
</div>

<!-- KOP SURAT -->
<div class="kop">
    <?php if (!empty($school['logo_kemenag'])): ?>
        <div class="kop-logo">
            <img src="<?= base_url('uploads/logos/' . $school['logo_kemenag']) ?>">
        </div>
    <?php else: ?>
        <div class="kop-logo-placeholder">Logo</div>
    <?php endif; ?>

    <div class="kop-text">
        <div style="font-size:10pt; text-transform: uppercase;"><?= esc($school['letter_kemenag_office'] ?? 'KEMENTERIAN AGAMA') ?></div>
        <div class="nama-madrasah"><?= esc($school['school_name'] ?? 'MADRASAH') ?></div>
        <div class="alamat">
            <?= esc($school['address'] ?? '') ?>
            <?php if (!empty($school['district'])): ?>, <?= esc($school['district']) ?><?php endif; ?>
            <?php if (!empty($school['city'])): ?>, <?= esc($school['city']) ?><?php endif; ?>
            <?php if (!empty($school['postal_code'])): ?> <?= esc($school['postal_code']) ?><?php endif; ?>
            <?php if (!empty($school['phone'])): ?> | Telp. <?= esc($school['phone']) ?><?php endif; ?>
        </div>
    </div>

    <?php if (!empty($school['logo_sekolah'])): ?>
        <div class="kop-logo">
            <img src="<?= base_url('uploads/logos/' . $school['logo_sekolah']) ?>">
        </div>
    <?php else: ?>
        <div class="kop-logo-placeholder">Logo</div>
    <?php endif; ?>
</div>

<!-- JUDUL -->
<div class="judul-section">
    <h2>Leger Nilai</h2>
</div>

<div class="info-kelas">
    <span>Kelas: <strong><?= esc($classroom['name'] ?? '') ?></strong></span>
    <span>Semester: <strong><?= esc($period['semester'] ?? '') ?></strong></span>
    <span>Tahun Ajaran: <strong><?= esc($academicYear['name'] ?? '') ?></strong></span>
</div>

<?php if ($legerData && !empty($legerData['students'])): ?>

<?php
$students     = $legerData['students'];
$subjectCodes = $legerData['subject_codes']; // [{id,code,name}, ...]
$totalSiswa   = count($students);
$totals       = array_column($students, 'total');
$maxTotal     = max($totals);
$minTotal     = min($totals);
$avgTotal     = array_sum($totals) / $totalSiswa;

// Rata-rata per mapel
$avgBySubject = [];
foreach ($subjectCodes as $s) {
    $vals = array_filter(array_map(fn($row) => $row['grades'][$s['id']] ?? null, $students));
    $avgBySubject[$s['id']] = count($vals) > 0 ? array_sum($vals) / count($vals) : 0;
}

// Ranking
$totalsForRank = array_column($students, 'total');
arsort($totalsForRank);
$ranks = [];
$rank = 1;
foreach ($totalsForRank as $idx => $val) {
    $ranks[$idx] = $rank++;
}

// Group mapel untuk header
$paiCodes   = array_values(array_filter($subjectCodes, fn($s) => in_array($s['code'], ['QH','AA','FIK','SKI'])));
$mulokCodes = array_values(array_filter($subjectCodes, fn($s) => in_array($s['code'], ['BAJ','TAQ'])));
$singleCodes= array_values(array_filter($subjectCodes, fn($s) => !in_array($s['code'], ['QH','AA','FIK','SKI','BAJ','TAQ'])));
?>

<table>
    <thead>
        <!-- Row header 1 -->
        <tr>
            <th rowspan="2" style="width:22px;">#</th>
            <th rowspan="2" style="width:65px;">NIS</th>
            <th rowspan="2" class="nama-col">Nama Siswa</th>
            <th rowspan="2" style="width:28px;">JK</th>

            <?php if (!empty($paiCodes)): ?>
                <th colspan="<?= count($paiCodes) ?>" class="group-pai">PAI</th>
            <?php endif; ?>

            <?php foreach ($singleCodes as $s): ?>
                <th rowspan="2" style="width:38px;" title="<?= esc($s['name']) ?>"><?= esc($s['code']) ?></th>
            <?php endforeach; ?>

            <?php if (!empty($mulokCodes)): ?>
                <th colspan="<?= count($mulokCodes) ?>" class="group-mulok">MULOK</th>
            <?php endif; ?>

            <th rowspan="2" style="width:45px;">Total</th>
            <th rowspan="2" style="width:32px;">Rank</th>
        </tr>
        <!-- Row header 2 (sub) -->
        <tr>
            <?php foreach ($paiCodes as $s): ?>
                <th class="sub-header" style="width:36px;"><?= esc($s['code']) ?></th>
            <?php endforeach; ?>
            <?php foreach ($mulokCodes as $s): ?>
                <th class="sub-header" style="width:36px;"><?= esc($s['code']) ?></th>
            <?php endforeach; ?>
        </tr>

        <!-- Row rata-rata -->
        <tr>
            <td colspan="4" class="avg-row" style="background:#d4edda!important; font-weight:bold;">Rata-rata Kelas</td>
            <?php foreach ($subjectCodes as $s): ?>
                <td class="avg-row"><?= number_format($avgBySubject[$s['id']] ?? 0, 1) ?></td>
            <?php endforeach; ?>
            <td class="avg-row"><?= number_format($avgTotal, 1) ?></td>
            <td class="avg-row"></td>
        </tr>
    </thead>
    <tbody>
        <?php foreach ($students as $idx => $row): ?>
        <tr>
            <td><?= $idx + 1 ?></td>
            <td><?= esc($row['student']['nis']) ?></td>
            <td class="nama-col"><?= esc(format_person_name($row['student']['full_name'])) ?></td>
            <td><?= esc($row['student']['gender']) ?></td>

            <?php foreach ($subjectCodes as $s): ?>
                <?php $score = $row['grades'][$s['id']] ?? null; ?>
                <td class="<?= ($score !== null && $score < 70) ? 'score-low' : '' ?>">
                    <?= $score !== null ? number_format($score, 0) : '-' ?>
                </td>
            <?php endforeach; ?>

            <td class="total-col <?= ($row['total'] >= $maxTotal) ? 'score-high' : '' ?>">
                <?= number_format($row['total'], 0) ?>
            </td>
            <td>
                <?php $r = $ranks[$idx]; ?>
                <span class="<?= $r==1 ? 'rank-gold' : ($r==2 ? 'rank-silver' : ($r==3 ? 'rank-bronze' : '')) ?>">
                    <?= $r ?>
                </span>
            </td>
        </tr>
        <?php endforeach; ?>
    </tbody>
</table>

<!-- TTD -->
<div class="ttd-section">
    <div class="ttd-box">
        <div class="jabatan">Mengetahui,<br>Kepala <?= esc($school['school_name'] ?? 'Sekolah') ?>,</div>
        <div class="nama-ttd">
            <?php if (!empty($school['principal_name'])): ?>
                <u><?= esc(format_person_name($school['principal_name'])) ?></u>
            <?php else: ?>
                ______________________
            <?php endif; ?>
        </div>
        <div class="nip-ttd">NIP. <?= esc($school['principal_nip'] ?? '___________________') ?></div>
    </div>
    <div style="text-align:center; align-self: flex-end; padding-bottom: 4px;">
        <small style="color:#888;">Dicetak: <?= $printDate ?></small>
    </div>
    <div class="ttd-box">
        <div class="jabatan"><?= esc($school['city'] ?? 'Wonogiri') ?>, <?= $printDate ?><br>Wali Kelas,</div>
        <div class="nama-ttd">
            <?php if (!empty($waliKelas['teacher_name'])): ?>
                <u><?= esc(format_person_name($waliKelas['teacher_name'])) ?></u>
            <?php else: ?>
                ______________________
            <?php endif; ?>
        </div>
        <div class="nip-ttd"><?= !empty($waliKelas['teacher_nip']) ? esc(guess_id_label($waliKelas['teacher_nip'])) . '. ' . esc($waliKelas['teacher_nip']) : 'NIP. ___________________' ?></div>
    </div>
</div>

<?php else: ?>
    <p style="text-align:center; color:#888; padding: 30px;">Belum ada data leger untuk dicetak.</p>
<?php endif; ?>

</body>
</html>