<!DOCTYPE html>
<html lang="id">
<head>
    <?php helper('logo'); ?>
    <link rel="icon" type="image/png" href="<?= getLogo('sekolah') ?>">
<meta charset="UTF-8">
<title><?= esc($title) ?> - <?= esc($monthName ?? '') ?> <?= esc($year ?? '') ?></title>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; font-family: Arial, Helvetica, sans-serif !important; }

<?php if ($type === 'portrait'): ?>
@page {
    size: A4 portrait;
    margin: 15mm;
}
body {
    font-family: Arial, sans-serif;
    font-size: var(--sheet-font-size, 8.5pt);
    background: #f0f0f0;
    padding: 10px;
}
.sheet {
    width: 180mm;
    background: #fff;
    margin: 0 auto 16px;
    padding: 0mm;
    box-shadow: 0 4px 16px rgba(0,0,0,.15);
    page-break-after: always;
}
/* Overrides for portrait table columns to maximize space for student names */
.tabel-presensi th.col-no,
.tabel-presensi td.col-no {
    width: 6% !important;
    min-width: 6% !important;
}
.tabel-presensi th.col-nisn,
.tabel-presensi td.col-nisn {
    width: 10% !important;
    min-width: 10% !important;
}
.tabel-presensi th.col-nama,
.tabel-presensi td.col-nama {
    width: 50% !important;
    min-width: 50% !important;
    max-width: 50% !important;
}
.tabel-presensi th.col-lp,
.tabel-presensi td.col-lp {
    width: 6% !important;
    min-width: 6% !important;
}
<?php else: ?>
@page {
    size: 330mm 215mm;
    margin: 7mm;
}
body {
    font-family: Arial, sans-serif;
    font-size: var(--sheet-font-size, 8.2pt);
    background: #f0f0f0;
    padding: 10px;
}
.sheet {
    width: 316mm;
    background: #fff;
    margin: 0 auto 16px;
    padding: 2mm 3mm;
    box-shadow: 0 4px 16px rgba(0,0,0,.15);
    page-break-after: always;
}
<?php endif; ?>

.sheet:last-child {
    page-break-after: avoid;
}

.preview-header {
    background: #1e2a3a;
    color: #fff;
    padding: 10px 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-radius: 8px;
    margin-bottom: 12px;
    position: sticky;
    top: 0;
    z-index: 100;
}
.preview-header h2 { font-size: 13px; font-weight: 600; margin: 0; }
.preview-header p  { font-size: 11px; color: #a0aec0; margin: 2px 0 0; }
.btn-back  { background: #4a5568; color: #fff; border: none; padding: 6px 12px; border-radius: 5px; cursor: pointer; font-size: 12px; margin-right: 6px; }
.btn-print { background: #0d6efd; color: #fff; border: none; padding: 6px 14px; border-radius: 5px; cursor: pointer; font-size: 12px; font-weight: 600; }

/* Tabel */
.tabel-presensi {
    width: 100%;
    border-collapse: collapse;
    font-size: var(--sheet-font-size, 8.2pt);
}

.tabel-presensi th,
.tabel-presensi td {
    border: 0.3mm solid #000;
    text-align: center;
    vertical-align: middle;
    padding: 0;
    line-height: 1.1;
    background: transparent !important;
    color: #000 !important;
}

.tabel-presensi thead tr:first-child th {
    font-size: var(--sheet-font-size, 8.2pt);
    height: var(--sheet-header-height, 6mm);
    font-weight: bold;
}
.tabel-presensi thead tr:nth-child(2) th {
    font-size: var(--sheet-font-size, 8.2pt);
    height: var(--sheet-subheader-height, 4.5mm);
    font-weight: bold;
}

th.col-no,   td.col-no   { width: 7mm; min-width: 7mm; }
th.col-nisn, td.col-nisn { width: 17mm; font-size: var(--sheet-name-font-size, 8.5pt); }
th.col-nama, td.col-nama { 
    text-align: left; 
    padding-left: 1.5mm; 
    font-size: var(--sheet-name-font-size, 8.5pt); 
    width: 55mm; 
    min-width: 55mm; 
    max-width: 55mm; 
    overflow: hidden; 
}
th.col-lp,   td.col-lp   { width: 6.5mm; }
th.col-sia,  td.col-sia  { width: 7mm; }

td.col-tgl, th.col-tgl {
    width: 6mm;
    min-width: 5.5mm;
}

/* Shading Minggu */
.sunday-col {
    background-color: #eaeaea !important;
}

.tabel-presensi tbody tr { height: var(--sheet-row-height, 4.6mm); }

@media print {
    body { background: #fff; padding: 0; margin: 0; }
    .preview-header { display: none !important; }
    .sheet { 
        box-shadow: none; 
        margin: 0 auto; 
        padding: 0; 
        width: 100% !important; 
        page-break-after: always; 
    }
    .sheet:last-child { page-break-after: avoid; }
    * {
        -webkit-print-color-adjust: exact;
        print-color-adjust: exact;
        color-adjust: exact;
    }
}
</style>
</head>
<body>

<div class="preview-header">
    <div>
        <h2>Preview Dokumen — <?= esc($title) ?></h2>
        <p><?= count($sheets) ?> kelas · Kertas: <?= $type === 'portrait' ? 'A4 Portrait' : 'Folio (F4) Landscape' ?> &nbsp;|&nbsp; <strong>Catatan:</strong> Sesuaikan ukuran kertas dan layout pada dialog cetak browser Anda.</p>
    </div>
    <div>
        <button class="btn-back" onclick="window.close()">← Kembali</button>
        <button class="btn-print" onclick="window.print()">🖨 Cetak / PDF</button>
    </div>
</div>

<?php foreach ($sheets as $sheetIndex => $sheet):
    $classroom = $sheet['classroom'];
    $students  = $sheet['students'];
    $studentCount = count($students);

    // Dynamic Sizing based on Document Type & Student Count to prevent page overflow
    if ($type === 'portrait') {
        if ($studentCount <= 30) {
            $fontSize = '9pt';
            $rowHeight = '6.2mm';
            $headerHeight = '8mm';
            $subHeaderHeight = '0mm';
            $nameFontSize = '9.5pt';
        } elseif ($studentCount <= 41) {
            $fontSize = '8.5pt';
            $rowHeight = '4.7mm';
            $headerHeight = '7mm';
            $subHeaderHeight = '0mm';
            $nameFontSize = '8.8pt';
        } else {
            $fontSize = '8pt';
            $rowHeight = '4.2mm';
            $headerHeight = '6.5mm';
            $subHeaderHeight = '0mm';
            $nameFontSize = '8.2pt';
        }
    } else { // Landscape F4
        if ($studentCount <= 30) {
            $fontSize = '8.6pt';
            $rowHeight = '4.5mm';
            $headerHeight = '6.2mm';
            $subHeaderHeight = '4.8mm';
            $nameFontSize = '8.6pt';
        } elseif ($studentCount <= 41) {
            $fontSize = '8.0pt';
            $rowHeight = '3.9mm';
            $headerHeight = '5.8mm';
            $subHeaderHeight = '4.4mm';
            $nameFontSize = '8.0pt';
        } else {
            $fontSize = '7.6pt';
            $rowHeight = '3.5mm';
            $headerHeight = '5.3mm';
            $subHeaderHeight = '4.0mm';
            $nameFontSize = '7.6pt';
        }
    }
?>
<div class="sheet" style="--sheet-font-size: <?= $fontSize ?>; --sheet-row-height: <?= $rowHeight ?>; --sheet-header-height: <?= $headerHeight ?>; --sheet-subheader-height: <?= $subHeaderHeight ?>; --sheet-name-font-size: <?= $nameFontSize ?>;">

    <!-- ===================================================================
         LAYOUT: PORTRAIT A4 (DAFTAR HADIR PORTRAIT)
         =================================================================== -->
    <?php if ($type === 'portrait'): ?>
        <div class="header-presensi-minimal" style="margin-bottom: 2mm; text-align: center;">
            <h3 style="font-size: 11.5pt; font-weight: bold; text-transform: uppercase; margin-bottom: 0.5mm; line-height: 1.2;"><?= esc($activityTitle) ?></h3>
            <?php if (!empty($activitySubtitle)): ?>
            <h4 style="font-size: 10pt; font-weight: bold; text-transform: uppercase; margin-bottom: 1.5mm; line-height: 1.2;"><?= esc($activitySubtitle) ?></h4>
            <?php endif; ?>
            <table style="width: 100%; border: none; font-size: 8.5pt; margin-bottom: 1mm; border-collapse: collapse;">
                <tr style="border: none; background: transparent !important;">
                    <td style="text-align: left; border: none; width: 50%; padding: 0; background: transparent !important; color: #000 !important;"></td>
                    <td style="text-align: right; border: none; width: 50%; font-weight: bold; font-size: 9pt; padding: 0; background: transparent !important; color: #000 !important;">
                        KELAS: <?= esc(strtoupper($classroom['grade_name'] ?? '')) ?> — <?= esc(strtoupper($classroom['name'] ?? '')) ?>
                    </td>
                </tr>
            </table>
        </div>

        <table class="tabel-presensi">
            <thead>
                <tr>
                    <th class="col-no" style="width: 6%; height: var(--sheet-header-height);">No</th>
                    <th class="col-nisn" style="width: 10%;">NIS</th>
                    <th class="col-nama" style="width: 50%; text-align: center; padding-left: 0;">Nama Siswa</th>
                    <th class="col-lp" style="width: 6%;">L/P</th>
                    <th class="col-ttd" colspan="2" style="width: 28%;">Tanda Tangan</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($students)): ?>
                <tr>
                    <td colspan="6" style="padding:4mm;color:#888;text-align:center">
                        Tidak ada siswa di kelas ini pada periode aktif
                    </td>
                </tr>
                <?php else: ?>
                <?php foreach ($students as $i => $student): 
                    $num = $i + 1;
                    $isEven = ($num % 2 === 0);
                    $studentName = esc(format_person_name($student['full_name']));
                    $nameStyle = "display: inline-block; white-space: nowrap;";
                ?>
                <tr>
                    <td class="col-no"><?= $num ?></td>
                    <td class="col-nisn" style="text-align: center;"><?= esc($student['nis'] ?? '-') ?></td>
                    <td class="col-nama">
                        <span style="<?= $nameStyle ?>"><?= $studentName ?></span>
                    </td>
                    <td class="col-lp"><?= esc($student['gender']) ?></td>
                    <?php if (!$isEven): ?>
                    <td style="width: 14%; border-right: none !important; text-align: left; padding-left: 2mm; font-size: 7.5pt; vertical-align: middle;">
                        <?= $num ?>. ....................
                    </td>
                    <td style="width: 14%; border-left: none !important;"></td>
                    <?php else: ?>
                    <td style="width: 14%; border-right: none !important;"></td>
                    <td style="width: 14%; border-left: none !important; text-align: left; padding-left: 2mm; font-size: 7.5pt; vertical-align: middle;">
                        <?= $num ?>. ....................
                    </td>
                    <?php endif; ?>
                </tr>
                <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>

        <!-- Tanda Tangan Portrait A4 -->
        <table style="width: 100%; border: none; margin-top: 4.5mm; font-size: var(--sheet-font-size, 8.5pt); line-height: 1.2; border-collapse: collapse;">
            <tr style="border: none; background: transparent !important;">
                <td style="width: 45%; text-align: center; border: none; padding: 0; background: transparent !important; color: #000 !important; vertical-align: top;">
                    Mengetahui,<br>
                    Kepala <?= esc($school['school_name'] ?? 'Sekolah') ?>,<br><br><br><br><br>
                    <strong>
                        <?php if (!empty($school['principal_name'])): ?>
                            <u><?= esc(format_person_name($school['principal_name'])) ?></u>
                        <?php else: ?>
                            _________________________
                        <?php endif; ?>
                    </strong><br>
                    NIP. <?= esc($school['principal_nip'] ?? '_________________________') ?>
                </td>
                <td style="width: 10%; border: none; background: transparent !important; color: #000 !important;"></td>
                <td style="width: 45%; text-align: center; border: none; padding: 0; background: transparent !important; color: #000 !important; vertical-align: top;">
                    <?= !empty($customDate) ? esc($customDate) : esc($school['city'] ?? 'Wonogiri') . ', ..... .................... ' . date('Y') ?><br>
                    Wali Kelas,<br><br><br><br><br>
                    <strong>
                        <?php if (!empty($sheet['wali_kelas']['name'])): ?>
                            <u><?= esc(format_person_name($sheet['wali_kelas']['name'])) ?></u>
                        <?php else: ?>
                            _________________________
                        <?php endif; ?>
                    </strong><br>
                    <?= !empty($sheet['wali_kelas']['nip']) ? esc(guess_id_label($sheet['wali_kelas']['nip'])) . '. ' . esc($sheet['wali_kelas']['nip']) : '_________________________' ?>
                </td>
            </tr>
        </table>

    <!-- ===================================================================
         LAYOUT: LANDSCAPE F4 (PRESENSI BULANAN KELAS)
         =================================================================== -->
    <?php elseif ($type === 'bulanan'): ?>
        <div class="header-presensi-minimal" style="margin-bottom: 2mm;">
            <table style="width: 100%; border: none; font-size: 8.5pt; margin-bottom: 1mm; border-collapse: collapse;">
                <tr style="border: none; background: transparent !important;">
                    <td style="text-align: left; border: none; width: 60%; font-weight: bold; font-size: 9.5pt; text-transform: uppercase; padding: 0; background: transparent !important; color: #000 !important;">
                        PRESENSI SISWA <?= esc(strtoupper($school['school_name'] ?? 'MADRASAH')) ?>
                    </td>
                    <td style="text-align: right; border: none; width: 40%; font-weight: bold; font-size: 8.5pt; padding: 0; background: transparent !important; color: #000 !important;">
                        BULAN: <?= esc(strtoupper($monthName)) ?> <?= esc($year) ?>
                    </td>
                </tr>
                <tr style="border: none; background: transparent !important;">
                    <td style="text-align: left; border: none; color: #111; font-size: 7.8pt; padding: 0; background: transparent !important;">
                        TAHUN AJARAN: <?= esc($activePeriod['year_name'] ?? '_______________') ?> &nbsp;|&nbsp; SEMESTER: <?= esc($activePeriod['semester'] ?? '') ?>
                    </td>
                    <td style="text-align: right; border: none; color: #111; font-size: 8pt; font-weight: bold; padding: 0; background: transparent !important;">
                        KELAS: <?= esc(strtoupper($classroom['grade_name'] ?? '')) ?> — <?= esc(strtoupper($classroom['name'] ?? '')) ?>
                    </td>
                </tr>
            </table>
        </div>

        <table class="tabel-presensi">
            <thead>
                <tr>
                    <th class="col-no" rowspan="2">No</th>
                    <th class="col-nisn" rowspan="2">NISN</th>
                    <th class="col-nama" rowspan="2">Nama Siswa</th>
                    <th class="col-lp" rowspan="2">L/P</th>
                    <th colspan="<?= $daysInMonth ?>">Tanggal</th>
                    <th class="col-sia" rowspan="2">S</th>
                    <th class="col-sia" rowspan="2">I</th>
                    <th class="col-sia" rowspan="2">A</th>
                </tr>
                <tr>
                    <?php for ($d = 1; $d <= $daysInMonth; $d++): 
                        $isSunday = ($days[$d] == 7);
                    ?>
                    <th class="col-tgl <?= $isSunday ? 'sunday-col' : '' ?>"><?= $d ?></th>
                    <?php endfor; ?>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($students)): ?>
                <tr>
                    <td colspan="<?= 7 + $daysInMonth ?>" style="padding:4mm;color:#888;text-align:center">
                        Tidak ada siswa di kelas ini pada periode aktif
                    </td>
                </tr>
                <?php else: ?>
                <?php foreach ($students as $i => $student): 
                    $studentName = esc(format_person_name($student['full_name']));
                    $nameStyle = "display: inline-block; white-space: nowrap;";
                ?>
                <tr>
                    <td class="col-no"><?= $i + 1 ?></td>
                    <td class="col-nisn" style="text-align: center;"><?= esc($student['nisn'] ?? '-') ?></td>
                    <td class="col-nama">
                        <span style="<?= $nameStyle ?>"><?= $studentName ?></span>
                    </td>
                    <td class="col-lp"><?= esc($student['gender']) ?></td>
                    <?php for ($d = 1; $d <= $daysInMonth; $d++): 
                        $isSunday = ($days[$d] == 7);
                    ?>
                    <td class="col-tgl <?= $isSunday ? 'sunday-col' : '' ?>"></td>
                    <?php endfor; ?>
                    <td class="col-sia"></td>
                    <td class="col-sia"></td>
                    <td class="col-sia"></td>
                </tr>
                <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>

        <!-- Tanda Tangan Bulanan Landscape -->
        <table style="width: 100%; border: none; margin-top: 3.5mm; font-size: var(--sheet-font-size, 8.2pt); line-height: 1.2; border-collapse: collapse;">
            <tr style="border: none; background: transparent !important;">
                <td style="width: 45%; text-align: center; border: none; padding: 0; background: transparent !important; color: #000 !important; vertical-align: top;">
                    Mengetahui,<br>
                    Kepala <?= esc($school['school_name'] ?? 'Madrasah') ?><br><br><br><br>
                    <strong>
                        <?php if (!empty($school['principal_name'])): ?>
                            <u><?= esc(format_person_name($school['principal_name'])) ?></u>
                        <?php else: ?>
                            _________________________
                        <?php endif; ?>
                    </strong><br>
                    NIP. <?= esc($school['principal_nip'] ?? '_________________________') ?>
                </td>
                <td style="width: 10%; border: none; background: transparent !important; color: #000 !important;"></td>
                <td style="width: 45%; text-align: center; border: none; padding: 0; background: transparent !important; color: #000 !important; vertical-align: top;">
                    <?= esc($school['city'] ?? 'Wonogiri') ?>, ..... .................... <?= esc($year) ?><br>
                    Wali Kelas<br><br><br><br>
                    <strong>
                        <?php if (!empty($sheet['wali_kelas']['name'])): ?>
                            <u><?= esc(format_person_name($sheet['wali_kelas']['name'])) ?></u>
                        <?php else: ?>
                            _________________________
                        <?php endif; ?>
                    </strong><br>
                    <?php $wkNip = $sheet['wali_kelas']['nip'] ?? null; ?><?= $wkNip ? esc(guess_id_label($wkNip)) . '. ' . esc($wkNip) : '_________________________' ?>
                </td>
            </tr>
        </table>

    <!-- ===================================================================
         LAYOUT: LANDSCAPE F4 (PRESENSI PERTEMUAN GURU MAPEL)
         =================================================================== -->
    <?php elseif ($type === 'guru'): ?>
        <div class="header-presensi-minimal" style="margin-bottom: 2mm;">
            <table style="width: 100%; border: none; font-size: 8.5pt; margin-bottom: 1mm; border-collapse: collapse;">
                <tr style="border: none; background: transparent !important;">
                    <td style="text-align: left; border: none; width: 55%; font-weight: bold; font-size: 9.5pt; text-transform: uppercase; padding: 0; background: transparent !important; color: #000 !important;">
                        PRESENSI PERTEMUAN GURU - <?= esc(strtoupper($school['school_name'] ?? 'MADRASAH')) ?>
                    </td>
                    <td style="text-align: right; border: none; width: 45%; font-weight: bold; font-size: 8.5pt; padding: 0; background: transparent !important; color: #000 !important;">
                        MAPEL: <?= $selectedSubject ? esc(strtoupper($selectedSubject['name'])) : '..................................................' ?>
                    </td>
                </tr>
                <tr style="border: none; background: transparent !important;">
                    <td style="text-align: left; border: none; color: #111; font-size: 7.8pt; padding: 0; background: transparent !important;">
                        TAHUN AJARAN: <?= esc($activePeriod['year_name'] ?? '_______________') ?> &nbsp;|&nbsp; SEMESTER: <?= esc($activePeriod['semester'] ?? '') ?>
                    </td>
                    <td style="text-align: right; border: none; color: #111; font-size: 8pt; font-weight: bold; padding: 0; background: transparent !important;">
                        KELAS: <?= esc(strtoupper($classroom['grade_name'] ?? '')) ?> — <?= esc(strtoupper($classroom['name'] ?? '')) ?> &nbsp;|&nbsp; GURU: <?= $selectedTeacher ? esc($selectedTeacher['name']) : '..................................................' ?>
                    </td>
                </tr>
            </table>
        </div>

        <table class="tabel-presensi">
            <thead>
                <tr>
                    <th class="col-no" rowspan="2">No</th>
                    <th class="col-nisn" rowspan="2">NIS</th>
                    <th class="col-nama" rowspan="2">Nama Siswa</th>
                    <th class="col-lp" rowspan="2">L/P</th>
                    <th colspan="20">Pertemuan / Tatap Muka Ke-</th>
                    <th class="col-sia" rowspan="2">S</th>
                    <th class="col-sia" rowspan="2">I</th>
                    <th class="col-sia" rowspan="2">A</th>
                </tr>
                <tr>
                    <?php for ($p = 1; $p <= 20; $p++): ?>
                    <th style="width: 7.5mm; min-width: 7.5mm; font-size: 7.5pt;"><?= $p ?></th>
                    <?php endfor; ?>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($students)): ?>
                <tr>
                    <td colspan="27" style="padding:4mm;color:#888;text-align:center">
                        Tidak ada siswa di kelas ini pada periode aktif
                    </td>
                </tr>
                <?php else: ?>
                <?php foreach ($students as $i => $student): 
                    $studentName = esc(format_person_name($student['full_name']));
                    $nameStyle = "display: inline-block; white-space: nowrap;";
                ?>
                <tr>
                    <td class="col-no"><?= $i + 1 ?></td>
                    <td class="col-nisn" style="text-align: center;"><?= esc($student['nis'] ?? '-') ?></td>
                    <td class="col-nama">
                        <span style="<?= $nameStyle ?>"><?= $studentName ?></span>
                    </td>
                    <td class="col-lp"><?= esc($student['gender']) ?></td>
                    <?php for ($p = 1; $p <= 20; $p++): ?>
                    <td></td>
                    <?php endfor; ?>
                    <td class="col-sia"></td>
                    <td class="col-sia"></td>
                    <td class="col-sia"></td>
                </tr>
                <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>

        <!-- Tanda Tangan Presensi Guru Landscape -->
        <table style="width: 100%; border: none; margin-top: 3.5mm; font-size: var(--sheet-font-size, 8.2pt); line-height: 1.2; border-collapse: collapse;">
            <tr style="border: none; background: transparent !important;">
                <td style="width: 45%; text-align: center; border: none; padding: 0; background: transparent !important; color: #000 !important; vertical-align: top;">
                    Mengetahui,<br>
                    Kepala <?= esc($school['school_name'] ?? 'Madrasah') ?><br><br><br><br>
                    <strong>
                        <?php if (!empty($school['principal_name'])): ?>
                            <u><?= esc(format_person_name($school['principal_name'])) ?></u>
                        <?php else: ?>
                            _________________________
                        <?php endif; ?>
                    </strong><br>
                    NIP. <?= esc($school['principal_nip'] ?? '_________________________') ?>
                </td>
                <td style="width: 10%; border: none; background: transparent !important; color: #000 !important;"></td>
                <td style="width: 45%; text-align: center; border: none; padding: 0; background: transparent !important; color: #000 !important; vertical-align: top;">
                    <?= esc($school['city'] ?? 'Wonogiri') ?>, ..... .................... <?= esc($year) ?><br>
                    Guru Mata Pelajaran<br><br><br><br>
                    <strong>
                        <?php if ($selectedTeacher && !empty($selectedTeacher['name'])): ?>
                            <u><?= esc(format_person_name($selectedTeacher['name'])) ?></u>
                        <?php else: ?>
                            _________________________
                        <?php endif; ?>
                    </strong><br>
                    <?= $selectedTeacher ? esc(guess_id_label($selectedTeacher['nip'] ?? null)) . '. ' . esc($selectedTeacher['nip'] ?: '-') : '_________________________' ?>
                </td>
            </tr>
        </table>

    <!-- ===================================================================
         LAYOUT: LANDSCAPE F4 (DAFTAR NILAI GURU MAPEL)
         =================================================================== -->
    <?php elseif ($type === 'nilai'): ?>
        <div class="header-presensi-minimal" style="margin-bottom: 2mm;">
            <table style="width: 100%; border: none; font-size: 8.5pt; margin-bottom: 1mm; border-collapse: collapse;">
                <tr style="border: none; background: transparent !important;">
                    <td style="text-align: left; border: none; width: 55%; font-weight: bold; font-size: 9.5pt; text-transform: uppercase; padding: 0; background: transparent !important; color: #000 !important;">
                        DAFTAR NILAI SISWA - <?= esc(strtoupper($school['school_name'] ?? 'MADRASAH')) ?>
                    </td>
                    <td style="text-align: right; border: none; width: 45%; font-weight: bold; font-size: 8.5pt; padding: 0; background: transparent !important; color: #000 !important;">
                        MAPEL: <?= $selectedSubject ? esc(strtoupper($selectedSubject['name'])) : '..................................................' ?>
                    </td>
                </tr>
                <tr style="border: none; background: transparent !important;">
                    <td style="text-align: left; border: none; color: #111; font-size: 7.8pt; padding: 0; background: transparent !important;">
                        TAHUN AJARAN: <?= esc($activePeriod['year_name'] ?? '_______________') ?> &nbsp;|&nbsp; SEMESTER: <?= esc($activePeriod['semester'] ?? '') ?>
                    </td>
                    <td style="text-align: right; border: none; color: #111; font-size: 8pt; font-weight: bold; padding: 0; background: transparent !important;">
                        KELAS: <?= esc(strtoupper($classroom['grade_name'] ?? '')) ?> — <?= esc(strtoupper($classroom['name'] ?? '')) ?> &nbsp;|&nbsp; GURU: <?= $selectedTeacher ? esc($selectedTeacher['name']) : '..................................................' ?>
                    </td>
                </tr>
            </table>
        </div>

        <table class="tabel-presensi">
            <thead>
                <tr>
                    <th class="col-no" rowspan="2">No</th>
                    <th class="col-nisn" rowspan="2">NIS</th>
                    <th class="col-nama" rowspan="2">Nama Siswa</th>
                    <th class="col-lp" rowspan="2">L/P</th>
                    <th colspan="8">Asesmen Sumatif Harian (ASH) / Nilai Tugas / Harian</th>
                    <th rowspan="2" style="width: 14mm;">ASTS</th>
                    <th rowspan="2" style="width: 14mm;">ASAS</th>
                    <th rowspan="2" style="width: 18mm;">NILAI RAPOR</th>
                </tr>
                <tr>
                    <?php for ($p = 1; $p <= 8; $p++): ?>
                    <th style="width: 12mm; min-width: 12mm; font-size: 7.5pt;">ASH <?= $p ?></th>
                    <?php endfor; ?>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($students)): ?>
                <tr>
                    <td colspan="15" style="padding:4mm;color:#888;text-align:center">
                        Tidak ada siswa di kelas ini pada periode aktif
                    </td>
                </tr>
                <?php else: ?>
                <?php foreach ($students as $i => $student): 
                    $studentName = esc(format_person_name($student['full_name']));
                    $nameStyle = "display: inline-block; white-space: nowrap;";
                ?>
                <tr>
                    <td class="col-no"><?= $i + 1 ?></td>
                    <td class="col-nisn" style="text-align: center;"><?= esc($student['nis'] ?? '-') ?></td>
                    <td class="col-nama">
                        <span style="<?= $nameStyle ?>"><?= $studentName ?></span>
                    </td>
                    <td class="col-lp"><?= esc($student['gender']) ?></td>
                    <?php for ($p = 1; $p <= 8; $p++): ?>
                    <td></td>
                    <?php endfor; ?>
                    <td></td>
                    <td></td>
                    <td></td>
                </tr>
                <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>

        <!-- Tanda Tangan Daftar Nilai Landscape -->
        <table style="width: 100%; border: none; margin-top: 3.5mm; font-size: var(--sheet-font-size, 8.2pt); line-height: 1.2; border-collapse: collapse;">
            <tr style="border: none; background: transparent !important;">
                <td style="width: 45%; text-align: center; border: none; padding: 0; background: transparent !important; color: #000 !important; vertical-align: top;">
                    Mengetahui,<br>
                    Kepala <?= esc($school['school_name'] ?? 'Madrasah') ?><br><br><br><br>
                    <strong>
                        <?php if (!empty($school['principal_name'])): ?>
                            <u><?= esc(format_person_name($school['principal_name'])) ?></u>
                        <?php else: ?>
                            _________________________
                        <?php endif; ?>
                    </strong><br>
                    NIP. <?= esc($school['principal_nip'] ?? '_________________________') ?>
                </td>
                <td style="width: 10%; border: none; background: transparent !important; color: #000 !important;"></td>
                <td style="width: 45%; text-align: center; border: none; padding: 0; background: transparent !important; color: #000 !important; vertical-align: top;">
                    <?= esc($school['city'] ?? 'Wonogiri') ?>, ..... .................... <?= esc($year) ?><br>
                    Guru Mata Pelajaran<br><br><br><br>
                    <strong>
                        <?php if ($selectedTeacher && !empty($selectedTeacher['name'])): ?>
                            <u><?= esc(format_person_name($selectedTeacher['name'])) ?></u>
                        <?php else: ?>
                            _________________________
                        <?php endif; ?>
                    </strong><br>
                    <?= $selectedTeacher ? esc(guess_id_label($selectedTeacher['nip'] ?? null)) . '. ' . esc($selectedTeacher['nip'] ?: '-') : '_________________________' ?>
                </td>
            </tr>
        </table>
    <?php endif; ?>

</div>
<?php endforeach; ?>

<script>
document.addEventListener('keydown', e => {
    if ((e.ctrlKey || e.metaKey) && e.key === 'p') {
        e.preventDefault();
        window.print();
    }
});

function shrinkToFitNames() {
    const cells = document.querySelectorAll('.tabel-presensi td.col-nama');
    cells.forEach(cell => {
        const span = cell.querySelector('span');
        if (!span) return;
        
        // Reset to original style to measure freshly
        span.style.fontSize = '';
        
        // Get cell inner printable width (subtracting padding)
        const cellStyle = window.getComputedStyle(cell);
        const paddingLeft = parseFloat(cellStyle.paddingLeft) || 0;
        const paddingRight = parseFloat(cellStyle.paddingRight) || 0;
        const maxAllowedWidth = cell.clientWidth - paddingLeft - paddingRight - 1.5; // with safety margin
        
        // Measure span width
        let currentWidth = span.offsetWidth;
        if (currentWidth <= maxAllowedWidth) return; // fits perfectly, no shrink needed
        
        // Get default font size
        const computedStyle = window.getComputedStyle(span);
        let fontSize = parseFloat(computedStyle.fontSize);
        
        // Iteratively shrink font size until it fits or reaches a readable minimum
        const minSize = 8.2; // 8.2px is around 6.2pt
        const step = 0.2; // step reduction
        
        while (span.offsetWidth > maxAllowedWidth && fontSize > minSize) {
            fontSize -= step;
            span.style.fontSize = fontSize + 'px';
        }
    });
}

// Run on document load
document.addEventListener('DOMContentLoaded', shrinkToFitNames);
// Run on window load to handle post-rendering fonts accurately
window.addEventListener('load', shrinkToFitNames);
// Run before print to ensure layout is updated for paper printing
window.addEventListener('beforeprint', shrinkToFitNames);
</script>
</body>
</html>