<?php
if (!function_exists('renderSmartFieldHtml')) {
    function renderSmartFieldHtml($value) {
        if (is_array($value)) {
            $value = implode("\n", array_map(function($item) {
                return is_array($item) ? json_encode($item) : (string)$item;
            }, $value));
        } elseif (!is_string($value)) {
            $value = (string)$value;
        }
        
        if (empty(trim($value))) return '-';
        
        $lines = explode("\n", trim($value));
        $lines = array_map('trim', $lines);
        $lines = array_filter($lines, fn($l) => $l !== '');
        $lines = array_values($lines);
        if (empty($lines)) return '-';
        
        // If single line is very long, split by specific headings
        if (count($lines) === 1 && strlen($lines[0]) > 200) {
            $s = $lines[0];
            $sp = preg_split('/(?=(?:A\.|B\.|C\.)\s+(?:PILIHAN|URAIAN|PRAKTIK|SOAL|ESAI))/i', $s);
            if (count($sp) > 1) {
                $lines = array_map('trim', $sp);
            } else {
                $sp2 = preg_split('/(?=(?:JUDUL|PETUNJUK|SOAL\/TUGAS|KESIMPULAN):)/i', $s);
                if (count($sp2) > 1) $lines = array_map('trim', $sp2);
            }
        }
        
        // 1. Check for assessment shape + rubric
        $firstLineClean = str_replace('**', '', $lines[0]);
        if (count($lines) >= 3 && preg_match('/^BENTUK ASESMEN/i', $firstLineClean)) {
            $ri = -1;
            foreach ($lines as $i => $l) {
                $lClean = str_replace('**', '', $l);
                if (preg_match('/^RUBRIK PENILAIAN/i', $lClean)) {
                    $ri = $i;
                    break;
                }
            }
            if ($ri > 0) {
                $atas = array_slice($lines, 0, $ri);
                $html = '<table class="data-table"><thead><tr><th width="30%">Item</th><th>Rincian</th></tr></thead><tbody>';
                foreach ($atas as $line) {
                    $lineClean = str_replace('**', '', $line);
                    $p = strpos($lineClean, ':');
                    if ($p !== false) {
                        $html .= '<tr><td style="font-weight:bold; background:#F5F5F5;">' . esc(trim(substr($lineClean, 0, $p))) . '</td><td>' . esc(trim(substr($lineClean, $p + 1))) . '</td></tr>';
                    }
                }
                $html .= '</tbody></table>';
                
                $html .= '<div class="fw-bold mt-3 mb-2" style="font-size:11pt;">RUBRIK PENILAIAN</div>';
                $bawah = array_values(array_filter(array_slice($lines, $ri + 1), fn($l) => trim($l) !== ''));
                if (!empty($bawah)) {
                    $colors = ['Sangat Baik' => '#DBEAFE', 'Baik' => '#D1FAE5', 'Cukup' => '#FEF3C7', 'Kurang' => '#FEE2E2', 'Perlu Bimbingan' => '#FEE2E2'];
                    $html .= '<table class="data-table"><thead><tr><th width="25%">Level</th><th>Deskripsi</th></tr></thead><tbody>';
                    foreach ($bawah as $line) {
                        $lineClean = str_replace('**', '', $line);
                        $p = strpos($lineClean, ':');
                        if ($p === false) $p = strpos($lineClean, "\t");
                        if ($p === false) continue;
                        $lvl = trim(substr($lineClean, 0, $p));
                        $desc = trim(substr($lineClean, $p + 1));
                        $bg = $colors[$lvl] ?? '#FFFFFF';
                        $html .= '<tr><td style="font-weight:bold; background:' . $bg . '; text-align:center; vertical-align:middle; color:#000000 !important;">' . esc($lvl) . '</td><td>' . esc($desc) . '</td></tr>';
                    }
                    $html .= '</tbody></table>';
                }
                return $html;
            }
        }
        
        // 2. Pipe-separated 4 columns (No|Tahap|Kegiatan Guru|Kegiatan Siswa)
        $pipe4Match = false;
        $checkLine = $lines[0] ?? '';
        if (preg_match('/^\d+\|\s*.+\|\s*.+\|\s*.+/', $checkLine)) {
            $pipe4Match = true;
        } elseif (count($lines) >= 2 && preg_match('/^No\|/i', $checkLine) && preg_match('/^\d+\|\s*.+\|\s*.+\|\s*.+/', $lines[1])) {
            $pipe4Match = true;
            array_shift($lines);
        }
        if ($pipe4Match && count(explode('|', $checkLine)) >= 4) {
            $html = '<table class="data-table"><thead><tr><th width="8%">No</th><th width="25%">Tahap</th><th>Kegiatan Guru</th><th>Kegiatan Siswa</th></tr></thead><tbody>';
            foreach ($lines as $line) {
                $parts = explode('|', $line);
                if (count($parts) >= 4) {
                    $html .= '<tr><td class="text-center">' . esc(trim($parts[0])) . '</td><td style="font-weight:bold; background:#F5F5F5;">' . esc(trim($parts[1])) . '</td><td>' . esc(trim($parts[2])) . '</td><td>' . esc(trim($parts[3])) . '</td></tr>';
                }
            }
            $html .= '</tbody></table>';
            return $html;
        }
        
        // 3. Pipe-separated 3 columns (No|Komponen|Deskripsi)
        $pipe3Match = false;
        if (preg_match('/^\d+\|\s*.+\|\s*.+/', $checkLine)) {
            $pipe3Match = true;
        } elseif (count($lines) >= 2 && preg_match('/^No\|\w+/i', $checkLine) && preg_match('/^\d+\|\s*.+\|\s*.+/', $lines[1])) {
            $pipe3Match = true;
            array_shift($lines);
        }
        if ($pipe3Match && count(explode('|', $checkLine)) >= 3) {
            $html = '<table class="data-table"><thead><tr><th width="8%">No</th><th width="25%">Komponen</th><th>Deskripsi</th></tr></thead><tbody>';
            foreach ($lines as $line) {
                $parts = explode('|', $line, 3);
                if (count($parts) >= 3) {
                    $html .= '<tr><td class="text-center">' . esc(trim($parts[0])) . '</td><td style="font-weight:bold; background:#F5F5F5;">' . esc(trim($parts[1])) . '</td><td>' . esc(trim($parts[2])) . '</td></tr>';
                }
            }
            $html .= '</tbody></table>';
            return $html;
        }
        
        // 4. Tahap heading
        if (preg_match('/^TAHAP\s+\d/i', $lines[0])) {
            $html = '';
            foreach ($lines as $line) {
                if (preg_match('/^(TAHAP\s+\d+\s*[-–]\s*[^:]+):(.*)/i', $line, $m)) {
                    $html .= '<p class="mb-2"><strong>' . esc(trim($m[1])) . '</strong>: ' . esc(trim($m[2])) . '</p>';
                } else {
                    $html .= '<p class="mb-2">' . esc($line) . '</p>';
                }
            }
            return $html;
        }
        
        // 5. Rubric levels
        if (preg_match('/^(Sangat Baik|Baik|Cukup|Kurang)\s*:/i', $lines[0])) {
            $colors = ['Sangat Baik' => '#DBEAFE', 'Baik' => '#D1FAE5', 'Cukup' => '#FEF3C7', 'Kurang' => '#FEE2E2'];
            $html = '<table class="data-table"><thead><tr><th width="25%">Level</th><th>Deskripsi</th></tr></thead><tbody>';
            foreach ($lines as $line) {
                $p = strpos($line, ':');
                if ($p === false) continue;
                $l = trim(substr($line, 0, $p));
                $d = trim(substr($line, $p + 1));
                $bg = $colors[$l] ?? '#FFFFFF';
                $html .= '<tr><td style="font-weight:bold; background:' . $bg . '; text-align:center; vertical-align:middle;">' . esc($l) . '</td><td>' . esc($d) . '</td></tr>';
            }
            $html .= '</tbody></table>';
            return $html;
        }
        
        // 6. Numbered + →
        if (preg_match('/^\d+\.\s/', $lines[0]) && strpos($lines[0], '→') !== false) {
            $html = '<table class="data-table"><thead><tr><th width="8%">No</th><th>Pertanyaan</th><th>Respons</th></tr></thead><tbody>';
            $n = 0;
            foreach ($lines as $line) {
                if (preg_match('/^\d+\.\s+(.+?)\s*→\s*(.+)/', $line, $m)) {
                    $n++;
                    $html .= '<tr><td class="text-center">' . $n . '</td><td>' . esc(trim($m[1])) . '</td><td>' . esc(trim($m[2])) . '</td></tr>';
                }
            }
            $html .= '</tbody></table>';
            return $html;
        }
        
        // 7. Numbered + colon → 3 columns
        if (preg_match('/^\d+\.\s+\S+.*:.*\S/', $lines[0])) {
            $html = '<table class="data-table"><thead><tr><th width="8%">No</th><th width="25%">Komponen</th><th>Uraian</th></tr></thead><tbody>';
            $n = 0;
            foreach ($lines as $line) {
                if (preg_match('/^\d+\.\s+([^:]+):\s*(.+)/', $line, $m)) {
                    $n++;
                    $html .= '<tr><td class="text-center">' . $n . '</td><td style="font-weight:bold; background:#F5F5F5;">' . esc(trim($m[1])) . '</td><td>' . esc(trim($m[2])) . '</td></tr>';
                }
            }
            $html .= '</tbody></table>';
            return $html;
        }
        
        // 8. Numbered ordinary
        if (preg_match('/^\d+\.\s/', $lines[0])) {
            $html = '<table class="data-table"><thead><tr><th width="8%">No</th><th>Uraian</th></tr></thead><tbody>';
            $n = 0;
            foreach ($lines as $line) {
                if (preg_match('/^\d+\.\s+(.+)/', $line, $m)) {
                    $n++;
                    $html .= '<tr><td class="text-center">' . $n . '</td><td>' . esc(trim($m[1])) . '</td></tr>';
                }
            }
            $html .= '</tbody></table>';
            return $html;
        }
        
        // 9. Key-value table (contains :)
        $hc = true;
        foreach ($lines as $l) {
            if (strpos($l, ':') === false) {
                $hc = false;
                break;
            }
        }
        if ($hc && !preg_match('/^(Sangat Baik|Baik|Cukup|Kurang|TAHAP|\d+\.)/i', $lines[0])) {
            $three = (substr_count($lines[0], ':') >= 2);
            $html = '<table class="data-table">';
            if ($three) {
                $html .= '<thead><tr><th width="25%">Kategori</th><th>Deskripsi</th><th>Strategi</th></tr></thead><tbody>';
                foreach ($lines as $line) {
                    $parts = explode(':', $line, 3);
                    if (count($parts) >= 3) {
                        $html .= '<tr><td style="font-weight:bold; background:#F5F5F5;">' . esc(trim($parts[0])) . '</td><td>' . esc(trim($parts[1])) . '</td><td>' . esc(trim($parts[2])) . '</td></tr>';
                    }
                }
            } else {
                $html .= '<thead><tr><th width="30%">Item</th><th>Rincian</th></tr></thead><tbody>';
                foreach ($lines as $line) {
                    $p = strpos($line, ':');
                    if ($p !== false) {
                        $html .= '<tr><td style="font-weight:bold; background:#F5F5F5;">' . esc(trim(substr($line, 0, $p))) . '</td><td>' . esc(trim(substr($line, $p + 1))) . '</td></tr>';
                    }
                }
            }
            $html .= '</tbody></table>';
            return $html;
        }
        
        // 10. Default: check if any line starts with bullet indicator '- ' or '* '
        $hasBullet = false;
        foreach ($lines as $line) {
            if (str_starts_with($line, '- ') || str_starts_with($line, '* ')) {
                $hasBullet = true;
                break;
            }
        }
        if ($hasBullet) {
            $html = '<ul class="mb-0">';
            foreach ($lines as $line) {
                $cleanLine = preg_replace('/^[-\*]\s+/', '', $line);
                $html .= '<li class="mb-1">' . esc($cleanLine) . '</li>';
            }
            $html .= '</ul>';
        } else {
            $html = '';
            foreach ($lines as $line) {
                $html .= '<p class="mb-1" style="text-align: justify;">' . esc($line) . '</p>';
            }
        }
        return $html;
    }
}
?><!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= esc($title) ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Times+New+Roman&display=swap');
        
        body {
            background-color: #f1f5f9;
            font-family: 'Inter', sans-serif;
            color: #1e293b;
            margin: 0;
            padding: 0;
        }

        /* Sidebar Navigation */
        .preview-sidebar {
            width: 290px;
            position: fixed;
            top: 0;
            bottom: 0;
            left: 0;
            background: #ffffff;
            border-right: 1px solid #e2e8f0;
            z-index: 100;
            padding: 1.5rem 1rem;
            overflow-y: auto;
        }

        .preview-content {
            margin-left: 290px;
            padding: 2rem;
            min-height: 100vh;
        }

        .nav-doc-link {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 0.75rem 1rem;
            color: #475569;
            text-decoration: none;
            border-radius: 8px;
            font-weight: 500;
            font-size: 0.9rem;
            transition: all 0.2s;
            margin-bottom: 0.25rem;
        }

        .nav-doc-link:hover {
            background-color: #f8fafc;
            color: #4f46e5;
        }

        .nav-doc-link.active {
            background-color: #e0e7ff;
            color: #4f46e5;
        }

        /* A4 Page Container on screen */
        .a4-page {
            width: 21cm;
            min-height: 29.7cm;
            padding: 2cm;
            margin: 0 auto 2rem auto;
            background: #ffffff;
            box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.05), 0 8px 10px -6px rgba(0, 0, 0, 0.05);
            border: 1px solid #e2e8f0;
            border-radius: 4px;
            position: relative;
            font-family: 'Times New Roman', Times, serif;
            font-size: 11pt;
            color: #000;
            line-height: 1.5;
            box-sizing: border-box;
        }

        /* Landscape A4 Page Container */
        .a4-page.landscape {
            width: 29.7cm;
            min-height: 21cm;
            padding: 1.5cm;
        }

        .a4-page-break {
            height: 1px;
            border-bottom: 2px dashed #cbd5e1;
            margin: 2rem 0;
            position: relative;
        }
        
        .a4-page-break::after {
            content: "PEMBERHENTIAN HALAMAN (PAGE BREAK)";
            position: absolute;
            top: -10px;
            left: 50%;
            transform: translateX(-50%);
            background: #f1f5f9;
            padding: 0 10px;
            font-size: 0.75rem;
            color: #64748b;
            font-weight: 600;
            letter-spacing: 1px;
        }

        /* Document Styling */
        .doc-title {
            text-align: center;
            font-size: 14pt;
            font-weight: bold;
            text-transform: uppercase;
            margin-bottom: 20px;
        }

        .info-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
            font-size: 11pt;
        }

        .info-table td {
            padding: 4px 6px;
            vertical-align: top;
            border: 1px solid #ccc;
        }

        .info-table td:first-child {
            width: 200px;
            font-weight: bold;
            background: #f5f5f5;
        }

        table.data-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 10px;
            margin-bottom: 15px;
            font-size: 11pt;
        }

        table.data-table th, table.data-table td {
            border: 1px solid #000;
            padding: 6px 8px;
            vertical-align: top;
        }

        table.data-table th {
            background-color: #e2e8f0 !important;
            color: #000000 !important;
            text-align: center;
            font-weight: bold;
        }

        table.data-table td {
            color: #000000 !important;
        }

        .ttd-table {
            width: 100%;
            text-align: center;
            margin-top: 35px;
            font-size: 11pt;
            page-break-inside: avoid;
        }

        /* Modul Ajar Premium Styles */
        .header-center {
            text-align: center;
            margin-bottom: 20px;
            border-bottom: 3px double #222;
            padding-bottom: 15px;
        }
        .header-center h2 {
            font-size: 16pt;
            font-weight: bold;
            text-transform: uppercase;
            margin-bottom: 5px;
        }
        .header-center h1 {
            font-size: 18pt;
            font-weight: bold;
            text-transform: uppercase;
            margin-bottom: 5px;
        }
        .header-center h3 {
            font-size: 14pt;
            font-weight: bold;
            margin-bottom: 3px;
        }
        .header-center p {
            font-size: 11pt;
            margin-bottom: 2px;
        }
        .section-title-roman {
            font-size: 13pt;
            font-weight: bold;
            text-align: center;
            margin: 25px 0 12px;
            padding: 6px;
            background: #f0f0f0;
            border: 1px solid #999;
            text-transform: uppercase;
        }
        .subsection-title {
            font-size: 11.5pt;
            font-weight: bold;
            margin-top: 15px;
            margin-bottom: 6px;
            padding-left: 10px;
            border-left: 3px solid #555;
        }
        .content-box {
            background: #fafafa;
            border: 1px solid #ddd;
            padding: 10px 12px;
            margin-bottom: 12px;
            border-radius: 2px;
            text-align: justify;
        }
        .content-box p { margin-bottom: 6px; }
        .content-box ul, .content-box ol { padding-left: 20px; margin-bottom: 6px; }
        .content-box li { margin-bottom: 3px; }
        
        .badge-dpl {
            display: inline-block;
            background: #e3f2fd;
            border: 1px solid #90caf9;
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 10pt;
            margin: 2px 3px;
        }
        .badge-kbc {
            display: inline-block;
            background: #fce4ec;
            border: 1px solid #f48fb1;
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 10pt;
            margin: 2px 3px;
        }

        /* Print Media CSS Settings */
        @media print {
            body {
                background: none;
                color: #000;
            }
            .preview-sidebar, .no-print, .a4-page-break {
                display: none !important;
            }
            .preview-content {
                margin-left: 0;
                padding: 0;
            }
            .a4-page {
                width: 100% !important;
                min-height: auto !important;
                margin: 0 !important;
                padding: 1.5cm !important;
                box-shadow: none !important;
                border: none !important;
                border-radius: 0 !important;
                page-break-after: always;
            }
            .a4-page.landscape {
                width: 100% !important;
                min-height: auto !important;
                padding: 1cm !important;
            }
            @page {
                margin: 1.5cm;
            }
            .page-portrait {
                size: portrait;
            }
            .page-landscape {
                size: landscape;
            }
            .section-title-roman {
                background: #f0f0f0 !important;
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
            }
            .content-box {
                background: #fafafa !important;
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
            }
            .badge-dpl {
                background: #e3f2fd !important;
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
            }
            .badge-kbc {
                background: #fce4ec !important;
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
            }
        }
        
        .btn-floating-container {
            display: flex;
            gap: 10px;
            margin-bottom: 1.5rem;
        }
    </style>
</head>
<body>

    <!-- Sidebar Menu (Web view only) -->
    <div class="preview-sidebar d-flex flex-column justify-content-between">
        <div>
            <div class="d-flex align-items-center gap-2 mb-4 px-2">
                <a href="/guru/learning-devices?device_id=<?= $device['id'] ?>" class="btn btn-outline-secondary btn-sm p-1 rounded-circle" title="Kembali ke Dasbor">
                    <i class="bi bi-arrow-left fs-5 d-flex"></i>
                </a>
                <div>
                    <h6 class="fw-bold mb-0">Preview Dokumen</h6>
                    <small class="text-muted text-truncate d-block" style="max-width: 180px;"><?= esc($device['subject_name']) ?></small>
                </div>
            </div>

            <div class="nav flex-column">
                <a href="?type=" class="nav-doc-link <?= empty($singleType) ? 'active' : '' ?>">
                    <i class="bi bi-grid-fill"></i> Tampilkan Semua
                </a>
                <hr class="text-muted my-2">
                <a href="?type=rpe" class="nav-doc-link <?= $singleType === 'rpe' ? 'active' : '' ?>">
                    <i class="bi bi-calendar-event"></i> 1. RPE
                </a>
                <a href="?type=cp" class="nav-doc-link <?= ($singleType === 'cp' || $singleType === 'tp') ? 'active' : '' ?>">
                    <i class="bi bi-file-earmark-ruled"></i> 2. CP & TP
                </a>
                <a href="?type=atp" class="nav-doc-link <?= $singleType === 'atp' ? 'active' : '' ?>">
                    <i class="bi bi-diagram-3"></i> 3. Alur Tujuan Pembel.
                </a>
                <a href="?type=prota" class="nav-doc-link <?= $singleType === 'prota' ? 'active' : '' ?>">
                    <i class="bi bi-calendar-range"></i> 4. Program Tahunan
                </a>
                <a href="?type=promes" class="nav-doc-link <?= $singleType === 'promes' ? 'active' : '' ?>">
                    <i class="bi bi-calendar-check"></i> 5. Program Semester
                </a>
                <a href="?type=kktp" class="nav-doc-link <?= $singleType === 'kktp' ? 'active' : '' ?>">
                    <i class="bi bi-bullseye"></i> 6. KKTP
                </a>
                <a href="?type=rpm" class="nav-doc-link <?= $singleType === 'rpm' ? 'active' : '' ?>">
                    <i class="bi bi-journal-bookmark"></i> 7. Modul Ajar (RPM)
                </a>
            </div>
        </div>

        <div class="mt-auto px-2 d-grid gap-2">
            <!-- Unified DOCX Export Button -->
            <?php if (!empty($singleType)): ?>
                <?php
                $docLink = '#';
                if ($singleType === 'rpe') $docLink = "/guru/learning-devices/export/{$device['id']}/rpe-docx";
                elseif ($singleType === 'cp' || $singleType === 'tp') $docLink = "/guru/learning-devices/tp/download-cp-tp/{$device['id']}";
                elseif ($singleType === 'atp') $docLink = "/guru/learning-devices/atp/download-atp/{$device['id']}";
                elseif ($singleType === 'kktp') $docLink = "/guru/learning-devices/kktp/download-kktp/{$device['id']}";
                elseif ($singleType === 'prota') $docLink = "/guru/learning-devices/export/{$device['id']}/prota-docx";
                elseif ($singleType === 'promes') $docLink = "/guru/learning-devices/export/{$device['id']}/promes-docx";
                elseif ($singleType === 'rpm') $docLink = "/guru/learning-devices/export/{$device['id']}/package-zip";
                ?>
                <a href="<?= $docLink ?>" class="btn btn-outline-primary py-2 fw-semibold d-flex align-items-center justify-content-center gap-2" style="border-radius: 8px;">
                    <i class="bi bi-file-earmark-word"></i> Export Word
                </a>
            <?php else: ?>
                <a href="/guru/learning-devices/export/<?= $device['id'] ?>/package-zip" class="btn btn-outline-primary py-2 fw-semibold d-flex align-items-center justify-content-center gap-2" style="border-radius: 8px;" title="Unduh semua file dalam ZIP">
                    <i class="bi bi-archive-fill"></i> Export Paket (ZIP)
                </a>
            <?php endif; ?>

        </div>
    </div>

    <!-- Main Content Area -->
    <div class="preview-content">
        <!-- Floating controller header -->
        <div class="no-print d-flex justify-content-between align-items-center mb-4 bg-white p-3 shadow-sm rounded-3">
            <div>
                <h5 class="fw-bold mb-0 text-dark">A4 Dokumen Preview</h5>
                <small class="text-muted">Desain pratinjau yang disesuaikan sama persis dengan layout cetak.</small>
            </div>
            <div class="btn-floating-container mb-0">
                <a href="/guru/learning-devices?device_id=<?= $device['id'] ?>" class="btn btn-outline-secondary fw-semibold px-3 py-2 rounded-2">
                    <i class="bi bi-house me-1"></i> Kembali
                </a>
                
                <?php if (!empty($singleType)): ?>
                    <a href="<?= $docLink ?>" class="btn btn-success fw-semibold px-3 py-2 rounded-2">
                        <i class="bi bi-file-earmark-word me-1"></i> Unduh Word
                    </a>
                <?php else: ?>
                    <a href="/guru/learning-devices/export/<?= $device['id'] ?>/package-zip" class="btn btn-success fw-semibold px-3 py-2 rounded-2">
                        <i class="bi bi-archive-fill me-1"></i> Unduh Paket ZIP
                    </a>
                <?php endif; ?>

            </div>
        </div>

        <!-- ========================================== -->
        <!-- 1. RPE SECTION -->
        <!-- ========================================== -->
        <?php if (empty($singleType) || $singleType === 'rpe'): ?>
        <div class="a4-page page-portrait">
            <div class="doc-title">RINCIAN PEKAN EFEKTIF (RPE)</div>
            
            <table class="info-table">
                <tr><td>Nama <?= esc($schoolTypeLabel) ?></td><td><b><?= esc($settings['school_name'] ?? '-') ?></b></td></tr>
                <tr><td>Mata Pelajaran</td><td><b><?= esc($device['subject_name']) ?></b></td></tr>
                <tr><td>Kelas / Fase</td><td><b>Kelas <?= esc($device['grade_name']) ?> / Fase <?= esc($device['phase']) ?></b></td></tr>
                <tr><td>Tahun Ajaran</td><td><b><?= esc($device['academic_year_name']) ?></b></td></tr>
            </table>

            <div class="section-title fw-bold mt-4 mb-2">A. Semester 1 (Ganjil)</div>
            <table class="data-table">
                <thead>
                    <tr>
                        <th width="150">Bulan</th>
                        <th width="120" class="text-center">Jumlah Minggu</th>
                        <th width="120" class="text-center">Minggu Efektif</th>
                        <th width="120" class="text-center">Minggu Tidak Efektif</th>
                        <th>Keterangan Kegiatan / Alasan</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    $tWeeks1 = 0; $eWeeks1 = 0; $neWeeks1 = 0;
                    $monthsS1 = [7 => 'Juli', 8 => 'Agustus', 9 => 'September', 10 => 'Oktober', 11 => 'November', 12 => 'Desember'];
                    foreach ($monthsS1 as $mNum => $mName): 
                        $row = $rpeData['sem1'][$mNum] ?? [
                            'total_weeks' => ($mNum == 8 || $mNum == 11) ? 5 : 4,
                            'effective_weeks' => ($mNum == 7) ? 2 : (($mNum == 12) ? 0 : (($mNum == 8 || $mNum == 11) ? 4 : 4)),
                            'non_effective_weeks' => ($mNum == 7) ? 2 : (($mNum == 12) ? 4 : (($mNum == 8 || $mNum == 11) ? 1 : 0)),
                            'note' => ''
                        ];
                        $tWeeks1 += (int)$row['total_weeks'];
                        $eWeeks1 += (int)$row['effective_weeks'];
                        $neWeeks1 += (int)$row['non_effective_weeks'];
                    ?>
                    <tr>
                        <td><?= $mName ?></td>
                        <td class="text-center"><?= $row['total_weeks'] ?></td>
                        <td class="text-center"><?= $row['effective_weeks'] ?></td>
                        <td class="text-center"><?= $row['non_effective_weeks'] ?></td>
                        <td><?= esc($row['note']) ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
                <tfoot>
                    <tr class="fw-bold" style="background-color: #f8fafc;">
                        <td>Total Pekan</td>
                        <td class="text-center"><?= $tWeeks1 ?></td>
                        <td class="text-center"><?= $eWeeks1 ?></td>
                        <td class="text-center"><?= $neWeeks1 ?></td>
                        <td></td>
                    </tr>
                </tfoot>
            </table>

            <div class="section-title fw-bold mt-4 mb-2">B. Semester 2 (Genap)</div>
            <table class="data-table">
                <thead>
                    <tr>
                        <th width="150">Bulan</th>
                        <th width="120" class="text-center">Jumlah Minggu</th>
                        <th width="120" class="text-center">Minggu Efektif</th>
                        <th width="120" class="text-center">Minggu Tidak Efektif</th>
                        <th>Keterangan Kegiatan / Alasan</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    $tWeeks2 = 0; $eWeeks2 = 0; $neWeeks2 = 0;
                    $monthsS2 = [1 => 'Januari', 2 => 'Februari', 3 => 'Maret', 4 => 'April', 5 => 'Mei', 6 => 'Juni'];
                    foreach ($monthsS2 as $mNum => $mName): 
                        $row = $rpeData['sem2'][$mNum] ?? [
                            'total_weeks' => ($mNum == 3 || $mNum == 6) ? 5 : 4,
                            'effective_weeks' => ($mNum == 3) ? 3 : (($mNum == 4) ? 2 : (($mNum == 6) ? 0 : 4)),
                            'non_effective_weeks' => ($mNum == 3) ? 2 : (($mNum == 4) ? 2 : (($mNum == 6) ? 5 : 0)),
                            'note' => ''
                        ];
                        $tWeeks2 += (int)$row['total_weeks'];
                        $eWeeks2 += (int)$row['effective_weeks'];
                        $neWeeks2 += (int)$row['non_effective_weeks'];
                    ?>
                    <tr>
                        <td><?= $mName ?></td>
                        <td class="text-center"><?= $row['total_weeks'] ?></td>
                        <td class="text-center"><?= $row['effective_weeks'] ?></td>
                        <td class="text-center"><?= $row['non_effective_weeks'] ?></td>
                        <td><?= esc($row['note']) ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
                <tfoot>
                    <tr class="fw-bold" style="background-color: #f8fafc;">
                        <td>Total Pekan</td>
                        <td class="text-center"><?= $tWeeks2 ?></td>
                        <td class="text-center"><?= $eWeeks2 ?></td>
                        <td class="text-center"><?= $neWeeks2 ?></td>
                        <td></td>
                    </tr>
                </tfoot>
            </table>

            <!-- Signatures -->
            <table class="ttd-table">
                <tr>
                    <td style="width: 50%;">Mengetahui,<br><?= ($device['school_type'] === 'madrasah') ? 'Kepala Madrasah' : 'Kepala Sekolah' ?></td>
                    <td style="width: 50%;"><?= esc($settings['city'] ?? 'Kota') ?>, ....................... <?= date('Y') ?><br>Guru Mata Pelajaran</td>
                </tr>
                <tr><td style="height: 60px;"></td><td></td></tr>
                <tr>
                    <td><strong><u><?= esc($settings['principal_name'] ?? $settings['headmaster_name'] ?? '..................................') ?></u></strong><br>NIP. <?= esc($settings['principal_nip'] ?? $settings['headmaster_nip'] ?? '........................') ?></td>
                    <td><strong><u><?= esc($device['teacher_name'] ?? '..................................') ?></u></strong><br><?= esc(guess_id_label($device['teacher_nip'] ?? null)) ?>. <?= esc($device['teacher_nip'] ?? '........................') ?></td>
                </tr>
            </table>
        </div>
        <?php endif; ?>

        <?php if (empty($singleType)): ?><div class="a4-page-break"></div><?php endif; ?>

        <!-- ========================================== -->
        <!-- 2. CP & TP SECTION -->
        <!-- ========================================== -->
        <?php if (empty($singleType) || $singleType === 'cp' || $singleType === 'tp'): ?>
        <div class="a4-page page-portrait">
            <div class="doc-title">CAPAIAN PEMBELAJARAN (CP) & TUJUAN PEMBELAJARAN (TP)</div>
            
            <table class="info-table">
                <tr><td>Nama <?= esc($schoolTypeLabel) ?></td><td><b><?= esc($settings['school_name'] ?? '-') ?></b></td></tr>
                <tr><td>Mata Pelajaran</td><td><b><?= esc($device['subject_name']) ?></b></td></tr>
                <tr><td>Kelas / Fase</td><td><b>Kelas <?= esc($device['grade_name']) ?> / Fase <?= esc($device['phase']) ?></b></td></tr>
                <tr><td>Tahun Ajaran</td><td><b><?= esc($device['academic_year_name']) ?></b></td></tr>
            </table>

            <div class="section-title fw-bold mt-4 mb-2">A. Capaian Pembelajaran (CP)</div>
            <div class="content-box">
                <?php if (!empty($device['cp_content'])): ?>
                    <?= renderSmartFieldHtml($device['cp_content']) ?>
                <?php else: ?>
                    <p class="text-muted italic">Teks Capaian Pembelajaran (CP) umum belum diisi.</p>
                <?php endif; ?>
            </div>

            <div class="section-title fw-bold mt-4 mb-2">B. Capaian Pembelajaran per Elemen</div>
            <table class="data-table">
                <thead>
                    <tr>
                        <th width="150">Nama Elemen</th>
                        <th>Capaian Pembelajaran Elemen</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (!empty($elements)): ?>
                        <?php foreach ($elements as $el): ?>
                        <tr>
                            <td class="fw-bold"><?= esc($el['name'] ?? '-') ?></td>
                            <td style="text-align: justify;"><?= nl2br(esc($el['description'] ?? '-')) ?></td>
                        </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr><td colspan="2" class="text-center text-muted">Belum ada elemen CP yang terdaftar.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>

            <div class="section-title fw-bold mt-4 mb-2">C. Tujuan Pembelajaran (TP) per Bab</div>
            <table class="data-table">
                <thead>
                    <tr>
                        <th width="40">No</th>
                        <th width="130">Materi Pokok / Bab</th>
                        <th width="120">Elemen CP</th>
                        <th width="80">Kode TP</th>
                        <th>Rumusan Tujuan Pembelajaran</th>
                        <th width="50" class="text-center">JP</th>
                        <th width="140">Dimensi Profil Lulusan</th>
                        <?php if ($device['school_type'] === 'madrasah'): ?>
                        <th width="120">Panca Cinta KBC</th>
                        <?php endif; ?>
                    </tr>
                </thead>
                <tbody>
                    <?php if (!empty($tps)):
                        $no = 0;
                        $chIdx = 0;
                        foreach ($chapters as $chap):
                            $chapTps = $tpByChapter[$chap] ?? [];
                            // Elemen CP per bab
                            $chapCp = $chapterCpMap[$chIdx] ?? [];
                            if (empty($chapCp) && !empty($chapterCpMap[(string)$chIdx])) $chapCp = $chapterCpMap[(string)$chIdx];
                            $chapCpText = is_array($chapCp) ? implode(', ', $chapCp) : $chapCp;
                            // DPL per bab
                            $chapDpl = $chapterDplMap[$chIdx] ?? $chapterDplMap[(string)$chIdx] ?? [];
                            if (empty($chapDpl)) $chapDpl = $dplSelected;
                            // KBC per bab
                            $chapKbc = $chapterKbcMap[$chIdx] ?? $chapterKbcMap[(string)$chIdx] ?? [];
                            if (empty($chapKbc)) $chapKbc = $pcSelected;
                    ?>
                            <?php if (empty($chapTps)): $no++; ?>
                            <tr>
                                <td class="text-center"><?= $no ?></td>
                                <td class="fw-bold"><?= esc($chap) ?></td>
                                <td><?= esc($chapCpText) ?></td>
                                <td class="text-center">-</td>
                                <td class="text-muted">Belum ada TP untuk bab ini.</td>
                                <td class="text-center">-</td>
                                <td><?= esc(implode(', ', $chapDpl)) ?></td>
                                <?php if ($device['school_type'] === 'madrasah'): ?>
                                <td><?= esc(implode(', ', $chapKbc)) ?></td>
                                <?php endif; ?>
                            </tr>
                            <?php else: ?>
                                <?php foreach ($chapTps as $ti => $tp): $no++; ?>
                                <tr>
                                    <td class="text-center"><?= $no ?></td>
                                    <?php if ($ti === 0): ?>
                                        <td rowspan="<?= count($chapTps) ?>" class="fw-bold align-middle"><?= esc($chap) ?></td>
                                        <td rowspan="<?= count($chapTps) ?>" class="align-middle" style="font-size:0.85em;"><?= esc($chapCpText) ?></td>
                                    <?php endif; ?>
                                    <td class="text-center fw-semibold"><?= esc($tp['code']) ?></td>
                                    <td><?= esc($tp['description']) ?></td>
                                    <td class="text-center"><?= esc($tp['allocated_hours'] ?? '-') ?></td>
                                    <?php if ($ti === 0): ?>
                                        <td rowspan="<?= count($chapTps) ?>" class="align-middle" style="font-size:0.85em;"><?= esc(implode(', ', $chapDpl)) ?></td>
                                        <?php if ($device['school_type'] === 'madrasah'): ?>
                                        <td rowspan="<?= count($chapTps) ?>" class="align-middle" style="font-size:0.85em;"><?= esc(implode(', ', $chapKbc)) ?></td>
                                        <?php endif; ?>
                                    <?php endif; ?>
                                </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                    <?php $chIdx++; endforeach; ?>
                    <?php else: ?>
                        <tr><td colspan="<?= ($device['school_type'] === 'madrasah') ? 8 : 7 ?>" class="text-center text-muted">Belum ada data Tujuan Pembelajaran.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>

            <!-- Signatures -->
            <table class="ttd-table">
                <tr>
                    <td style="width: 50%;">Mengetahui,<br><?= ($device['school_type'] === 'madrasah') ? 'Kepala Madrasah' : 'Kepala Sekolah' ?></td>
                    <td style="width: 50%;"><?= esc($settings['city'] ?? 'Kota') ?>, ....................... <?= date('Y') ?><br>Guru Mata Pelajaran</td>
                </tr>
                <tr><td style="height: 60px;"></td><td></td></tr>
                <tr>
                    <td><strong><u><?= esc($settings['principal_name'] ?? $settings['headmaster_name'] ?? '..................................') ?></u></strong><br>NIP. <?= esc($settings['principal_nip'] ?? $settings['headmaster_nip'] ?? '........................') ?></td>
                    <td><strong><u><?= esc($device['teacher_name'] ?? '..................................') ?></u></strong><br><?= esc(guess_id_label($device['teacher_nip'] ?? null)) ?>. <?= esc($device['teacher_nip'] ?? '........................') ?></td>
                </tr>
            </table>
        </div>
        <?php endif; ?>

        <?php if (empty($singleType)): ?><div class="a4-page-break"></div><?php endif; ?>

        <!-- ========================================== -->
        <!-- 4. ATP SECTION -->
        <!-- ========================================== -->
        <?php if (empty($singleType) || $singleType === 'atp'): ?>
        <div class="a4-page page-landscape landscape">
            <div class="doc-title">ALUR TUJUAN PEMBELAJARAN (ATP)</div>
            
            <table class="info-table">
                <tr><td>Nama <?= esc($schoolTypeLabel) ?></td><td><b><?= esc($settings['school_name'] ?? '-') ?></b></td></tr>
                <tr><td>Mata Pelajaran</td><td><b><?= esc($device['subject_name']) ?></b></td></tr>
                <tr><td>Kelas / Fase</td><td><b>Kelas <?= esc($device['grade_name']) ?> / Fase <?= esc($device['phase']) ?></b></td></tr>
                <tr><td>Tahun Ajaran</td><td><b><?= esc($device['academic_year_name']) ?></b></td></tr>
            </table>

            <table class="data-table mt-4">
                <thead>
                    <tr>
                        <th style="width: 40px;">No</th>
                        <th style="width: 250px;">Tujuan Pembelajaran</th>
                        <th style="width: 140px;">Materi / Bab</th>
                        <th style="width: 70px;">Semester</th>
                        <th style="width: 60px;">JP</th>
                        <th style="width: 180px;">Dimensi Profil Lulusan</th>
                        <?php if ($device['school_type'] === 'madrasah'): ?>
                        <th style="width: 180px;">Dimensi Panca Cinta</th>
                        <?php endif; ?>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    $no = 0; 
                    $chapterIdx = 0;
                    foreach ($chapters as $chap): 
                        $chapTps = $tpByChapter[$chap] ?? [];
                        // DPL per-bab: fallback ke global jika kosong
                        $chapDpl = $chapterDplMap[$chapterIdx] ?? [];
                        if (empty($chapDpl)) $chapDpl = $dplSelected;
                        // KBC per-bab: fallback ke global jika kosong
                        $chapKbc = $chapterKbcMap[$chapterIdx] ?? [];
                        if (empty($chapKbc)) $chapKbc = $pcSelected;
                    ?>
                        <?php if (!empty($chapTps)): $rowspan = count($chapTps); ?>
                            <?php foreach ($chapTps as $tpi => $tp): $no++; ?>
                            <tr>
                                <td style="text-align: center;"><?= $no ?></td>
                                <td><b><?= esc($tp['code']) ?></b>: <?= esc($tp['description']) ?></td>
                                <?php if ($tpi === 0): ?>
                                    <td rowspan="<?= $rowspan ?>"><b><?= esc($chap) ?></b></td>
                                    <td style="text-align: center;" rowspan="<?= $rowspan ?>">Smt <?= esc($tp['semester'] ?? 1) ?></td>
                                    <td style="text-align: center;" rowspan="<?= $rowspan ?>"><?= esc($tp['allocated_hours'] ?? 0) ?> JP</td>
                                    <td rowspan="<?= $rowspan ?>"><?= esc(implode(', ', $chapDpl)) ?></td>
                                    <?php if ($device['school_type'] === 'madrasah'): ?>
                                    <td rowspan="<?= $rowspan ?>"><?= esc(implode(', ', $chapKbc)) ?></td>
                                    <?php endif; ?>
                                <?php endif; ?>
                            </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    <?php $chapterIdx++; endforeach; if ($no == 0): ?>
                        <tr><td colspan="<?= ($device['school_type'] === 'madrasah') ? 7 : 6 ?>" class="text-center text-muted">Belum ada data untuk Alur Tujuan Pembelajaran.</td></tr>
                    <?php endif; ?>

                </tbody>
            </table>

            <!-- Signatures -->
            <table class="ttd-table">
                <tr>
                    <td style="width: 50%;">Mengetahui,<br><?= ($device['school_type'] === 'madrasah') ? 'Kepala Madrasah' : 'Kepala Sekolah' ?></td>
                    <td style="width: 50%;"><?= esc($settings['city'] ?? 'Kota') ?>, ....................... <?= date('Y') ?><br>Guru Mata Pelajaran</td>
                </tr>
                <tr><td style="height: 60px;"></td><td></td></tr>
                <tr>
                    <td><strong><u><?= esc($settings['principal_name'] ?? $settings['headmaster_name'] ?? '..................................') ?></u></strong><br>NIP. <?= esc($settings['principal_nip'] ?? $settings['headmaster_nip'] ?? '........................') ?></td>
                    <td><strong><u><?= esc($device['teacher_name'] ?? '..................................') ?></u></strong><br><?= esc(guess_id_label($device['teacher_nip'] ?? null)) ?>. <?= esc($device['teacher_nip'] ?? '........................') ?></td>
                </tr>
            </table>
        </div>
        <?php endif; ?>

        <?php if (empty($singleType)): ?><div class="a4-page-break"></div><?php endif; ?>

        <!-- ========================================== -->
        <!-- 5. PROTA SECTION -->
        <!-- ========================================== -->
        <?php if (empty($singleType) || $singleType === 'prota'): ?>
        <div class="a4-page page-portrait">
            <div class="doc-title">PROGRAM TAHUNAN (PROTA)</div>
            
            <table class="info-table">
                <tr><td>Nama <?= esc($schoolTypeLabel) ?></td><td><b><?= esc($settings['school_name'] ?? '-') ?></b></td></tr>
                <tr><td>Mata Pelajaran</td><td><b><?= esc($device['subject_name']) ?></b></td></tr>
                <tr><td>Kelas / Fase</td><td><b>Kelas <?= esc($device['grade_name']) ?> / Fase <?= esc($device['phase']) ?></b></td></tr>
                <tr><td>Tahun Ajaran</td><td><b><?= esc($device['academic_year_name']) ?></b></td></tr>
            </table>

            <table class="data-table mt-4">
                <thead>
                    <tr>
                        <th width="40" class="text-center">No</th>
                        <th width="80" class="text-center">Kode</th>
                        <th>Tujuan Pembelajaran (TP)</th>
                        <th width="100" class="text-center">Semester</th>
                        <th width="100" class="text-center">Alokasi Pekan</th>
                        <th width="100" class="text-center">Alokasi JP</th>
                        <th>Keterangan</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (!empty($tps)): ?>
                        <?php $totalJpProta = 0; $totalWeeksProta = 0; ?>
                        <?php foreach ($tps as $index => $tp): 
                            $tpId = $tp['id'];
                            $pSemester = $protaMap[$tpId]['semester'] ?? (($index < ceil(count($tps)/2)) ? 1 : 2);
                            $pWeeks = $protaMap[$tpId]['allocated_weeks'] ?? ceil($tp['allocated_hours'] / 4);
                            $pHours = $protaMap[$tpId]['allocated_hours'] ?? $tp['allocated_hours'];
                            $pNotes = $protaMap[$tpId]['notes'] ?? '';
                            
                            $totalJpProta += (int)$pHours;
                            $totalWeeksProta += (int)$pWeeks;
                        ?>
                        <tr>
                            <td class="text-center"><?= $index + 1 ?></td>
                            <td class="text-center fw-semibold"><?= esc($tp['code']) ?></td>
                            <td><?= esc($tp['description']) ?></td>
                            <td class="text-center">Sem <?= $pSemester ?></td>
                            <td class="text-center"><?= $pWeeks ?> Pekan</td>
                            <td class="text-center"><?= $pHours ?> JP</td>
                            <td><?= esc($pNotes) ?></td>
                        </tr>
                        <?php endforeach; ?>
                        <tr class="fw-bold" style="background-color: #f8fafc;">
                            <td colspan="4" class="text-end">Jumlah Total</td>
                            <td class="text-center"><?= $totalWeeksProta ?> Pekan</td>
                            <td class="text-center"><?= $totalJpProta ?> JP</td>
                            <td></td>
                        </tr>
                    <?php else: ?>
                        <tr><td colspan="7" class="text-center text-muted">Belum ada data Program Tahunan.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>

            <!-- Signatures -->
            <table class="ttd-table">
                <tr>
                    <td style="width: 50%;">Mengetahui,<br><?= ($device['school_type'] === 'madrasah') ? 'Kepala Madrasah' : 'Kepala Sekolah' ?></td>
                    <td style="width: 50%;"><?= esc($settings['city'] ?? 'Kota') ?>, ....................... <?= date('Y') ?><br>Guru Mata Pelajaran</td>
                </tr>
                <tr><td style="height: 60px;"></td><td></td></tr>
                <tr>
                    <td><strong><u><?= esc($settings['principal_name'] ?? $settings['headmaster_name'] ?? '..................................') ?></u></strong><br>NIP. <?= esc($settings['principal_nip'] ?? $settings['headmaster_nip'] ?? '........................') ?></td>
                    <td><strong><u><?= esc($device['teacher_name'] ?? '..................................') ?></u></strong><br><?= esc(guess_id_label($device['teacher_nip'] ?? null)) ?>. <?= esc($device['teacher_nip'] ?? '........................') ?></td>
                </tr>
            </table>
        </div>
        <?php endif; ?>

        <?php if (empty($singleType)): ?><div class="a4-page-break"></div><?php endif; ?>

        <!-- ========================================== -->
        <!-- 6. PROMES SECTION -->
        <!-- ========================================== -->
        <?php if (empty($singleType) || $singleType === 'promes'): ?>
        <!-- PROMES Ganjil -->
        <div class="a4-page page-landscape landscape">
            <div class="doc-title">PROGRAM SEMESTER (PROMES) - SEMESTER 1 (GANJIL)</div>
            
            <table class="info-table">
                <tr><td>Nama <?= esc($schoolTypeLabel) ?></td><td><b><?= esc($settings['school_name'] ?? '-') ?></b></td></tr>
                <tr><td>Mata Pelajaran</td><td><b><?= esc($device['subject_name']) ?></b></td></tr>
                <tr><td>Kelas / Fase</td><td><b>Kelas <?= esc($device['grade_name']) ?> / Fase <?= esc($device['phase']) ?></b></td></tr>
                <tr><td>Tahun Ajaran</td><td><b><?= esc($device['academic_year_name']) ?></b></td></tr>
            </table>

            <table class="data-table mt-4" style="font-size: 8pt;">
                <thead>
                    <tr>
                        <th rowspan="2" class="text-center align-middle" width="50">Kode</th>
                        <th rowspan="2" class="align-middle">Tujuan Pembelajaran</th>
                        <th rowspan="2" class="text-center align-middle" width="70">Alokasi JP</th>
                        <?php 
                        $monthsS1 = [7 => 'Juli', 8 => 'Agustus', 9 => 'September', 10 => 'Oktober', 11 => 'November', 12 => 'Desember'];
                        foreach ($monthsS1 as $mNum => $mName): ?>
                            <th colspan="5" class="text-center"><?= $mName ?></th>
                        <?php endforeach; ?>
                    </tr>
                    <tr>
                        <?php foreach ($monthsS1 as $mNum => $mName): ?>
                            <?php for ($w = 1; $w <= 5; $w++): ?>
                                <th class="text-center p-0 fw-normal text-muted" style="width: 16px; font-size: 0.65rem;">W<?= $w ?></th>
                            <?php endfor; ?>
                        <?php endforeach; ?>
                    </tr>
                </thead>
                <tbody>
                    <?php if (!empty($tps)): ?>
                        <?php foreach ($tps as $index => $tp): 
                            $tpId = $tp['id'];
                            $pSemester = $protaMap[$tpId]['semester'] ?? (($index < ceil(count($tps)/2)) ? 1 : 2);
                            $pHours = $protaMap[$tpId]['allocated_hours'] ?? $tp['allocated_hours'];
                            if ($pSemester != 1) continue;
                        ?>
                        <tr>
                            <td class="text-center fw-bold"><?= esc($tp['code']) ?></td>
                            <td><?= esc($tp['description']) ?></td>
                            <td class="text-center fw-bold"><?= $pHours ?> JP</td>
                            <?php foreach ($monthsS1 as $mNum => $mName): ?>
                                <?php for ($w = 1; $w <= 5; $w++): 
                                    $val = $promesMap[$tpId][$mNum][$w] ?? '';
                                ?>
                                <td class="text-center p-0 align-middle fw-bold" style="<?= !empty($val) ? 'background-color: #e0e7ff; color: #4f46e5;' : '' ?>">
                                    <?= !empty($val) ? $val : '' ?>
                                </td>
                                <?php endfor; ?>
                            <?php endforeach; ?>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>

            <!-- Signatures -->
            <table class="ttd-table">
                <tr>
                    <td style="width: 50%;">Mengetahui,<br><?= ($device['school_type'] === 'madrasah') ? 'Kepala Madrasah' : 'Kepala Sekolah' ?></td>
                    <td style="width: 50%;"><?= esc($settings['city'] ?? 'Kota') ?>, ....................... <?= date('Y') ?><br>Guru Mata Pelajaran</td>
                </tr>
                <tr><td style="height: 60px;"></td><td></td></tr>
                <tr>
                    <td><strong><u><?= esc($settings['principal_name'] ?? $settings['headmaster_name'] ?? '..................................') ?></u></strong><br>NIP. <?= esc($settings['principal_nip'] ?? $settings['headmaster_nip'] ?? '........................') ?></td>
                    <td><strong><u><?= esc($device['teacher_name'] ?? '..................................') ?></u></strong><br><?= esc(guess_id_label($device['teacher_nip'] ?? null)) ?>. <?= esc($device['teacher_nip'] ?? '........................') ?></td>
                </tr>
            </table>
        </div>
        
        <div class="a4-page-break no-print"></div>
        
        <!-- PROMES Genap -->
        <div class="a4-page page-landscape landscape">
            <div class="doc-title">PROGRAM SEMESTER (PROMES) - SEMESTER 2 (GENAP)</div>
            
            <table class="info-table">
                <tr><td>Nama <?= esc($schoolTypeLabel) ?></td><td><b><?= esc($settings['school_name'] ?? '-') ?></b></td></tr>
                <tr><td>Mata Pelajaran</td><td><b><?= esc($device['subject_name']) ?></b></td></tr>
                <tr><td>Kelas / Fase</td><td><b>Kelas <?= esc($device['grade_name']) ?> / Fase <?= esc($device['phase']) ?></b></td></tr>
                <tr><td>Tahun Ajaran</td><td><b><?= esc($device['academic_year_name']) ?></b></td></tr>
            </table>

            <table class="data-table mt-4" style="font-size: 8pt;">
                <thead>
                    <tr>
                        <th rowspan="2" class="text-center align-middle" width="50">Kode</th>
                        <th rowspan="2" class="align-middle">Tujuan Pembelajaran</th>
                        <th rowspan="2" class="text-center align-middle" width="70">Alokasi JP</th>
                        <?php 
                        $monthsS2 = [1 => 'Januari', 2 => 'Februari', 3 => 'Maret', 4 => 'April', 5 => 'Mei', 6 => 'Juni'];
                        foreach ($monthsS2 as $mNum => $mName): ?>
                            <th colspan="5" class="text-center"><?= $mName ?></th>
                        <?php endforeach; ?>
                    </tr>
                    <tr>
                        <?php foreach ($monthsS2 as $mNum => $mName): ?>
                            <?php for ($w = 1; $w <= 5; $w++): ?>
                                <th class="text-center p-0 fw-normal text-muted" style="width: 16px; font-size: 0.65rem;">W<?= $w ?></th>
                            <?php endfor; ?>
                        <?php endforeach; ?>
                    </tr>
                </thead>
                <tbody>
                    <?php if (!empty($tps)): ?>
                        <?php foreach ($tps as $index => $tp): 
                            $tpId = $tp['id'];
                            $pSemester = $protaMap[$tpId]['semester'] ?? (($index < ceil(count($tps)/2)) ? 1 : 2);
                            $pHours = $protaMap[$tpId]['allocated_hours'] ?? $tp['allocated_hours'];
                            if ($pSemester != 2) continue;
                        ?>
                        <tr>
                            <td class="text-center fw-bold"><?= esc($tp['code']) ?></td>
                            <td><?= esc($tp['description']) ?></td>
                            <td class="text-center fw-bold"><?= $pHours ?> JP</td>
                            <?php foreach ($monthsS2 as $mNum => $mName): ?>
                                <?php for ($w = 1; $w <= 5; $w++): 
                                    $val = $promesMap[$tpId][$mNum][$w] ?? '';
                                ?>
                                <td class="text-center p-0 align-middle fw-bold" style="<?= !empty($val) ? 'background-color: #e0e7ff; color: #4f46e5;' : '' ?>">
                                    <?= !empty($val) ? $val : '' ?>
                                </td>
                                <?php endfor; ?>
                            <?php endforeach; ?>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>

            <!-- Signatures -->
            <table class="ttd-table">
                <tr>
                    <td style="width: 50%;">Mengetahui,<br><?= ($device['school_type'] === 'madrasah') ? 'Kepala Madrasah' : 'Kepala Sekolah' ?></td>
                    <td style="width: 50%;"><?= esc($settings['city'] ?? 'Kota') ?>, ....................... <?= date('Y') ?><br>Guru Mata Pelajaran</td>
                </tr>
                <tr><td style="height: 60px;"></td><td></td></tr>
                <tr>
                    <td><strong><u><?= esc($settings['principal_name'] ?? $settings['headmaster_name'] ?? '..................................') ?></u></strong><br>NIP. <?= esc($settings['principal_nip'] ?? $settings['headmaster_nip'] ?? '........................') ?></td>
                    <td><strong><u><?= esc($device['teacher_name'] ?? '..................................') ?></u></strong><br><?= esc(guess_id_label($device['teacher_nip'] ?? null)) ?>. <?= esc($device['teacher_nip'] ?? '........................') ?></td>
                </tr>
            </table>
        </div>
        <?php endif; ?>

        <?php if (empty($singleType)): ?><div class="a4-page-break"></div><?php endif; ?>

        <!-- ========================================== -->
        <!-- 7. KKTP SECTION -->
        <!-- ========================================== -->
        <?php if (empty($singleType) || $singleType === 'kktp'): ?>
        <div class="a4-page page-portrait">
            <?php
            $bimbinganMax = $intervals['bimbingan'] ?? 59;
            $cukupMin = $bimbinganMax + 1;
            $cukupMax = $intervals['cukup'] ?? 69;
            $baikMin = $cukupMax + 1;
            $baikMax = $intervals['baik'] ?? 84;
            $sangatBaikMin = $baikMax + 1;
            ?>
            <div class="doc-title">KRITERIA KETERCAPAIAN TUJUAN PEMBELAJARAN (KKTP)</div>
            
            <table class="info-table">
                <tr><td>Nama <?= esc($schoolTypeLabel) ?></td><td><b><?= esc($settings['school_name'] ?? '-') ?></b></td></tr>
                <tr><td>Mata Pelajaran</td><td><b><?= esc($device['subject_name']) ?></b></td></tr>
                <tr><td>Kelas / Fase</td><td><b>Kelas <?= esc($device['grade_name']) ?> / Fase <?= esc($device['phase']) ?></b></td></tr>
                <tr><td>Tahun Ajaran</td><td><b><?= esc($device['academic_year_name']) ?></b></td></tr>
            </table>

            <div class="section-title fw-bold mt-4 mb-2">A. Pendekatan dan Interval Nilai KKTP</div>
            <table class="data-table">
                <thead>
                    <tr>
                        <th>Level Pencapaian</th>
                        <th>Interval Nilai</th>
                        <th>Makna Pencapaian</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td><b>Perlu Bimbingan</b></td>
                        <td class="text-center">0 – <?= $bimbinganMax ?></td>
                        <td>Peserta didik belum menguasai indikator TP dan membutuhkan remedial intensif.</td>
                    </tr>
                    <tr>
                        <td><b>Cukup</b></td>
                        <td class="text-center"><?= $cukupMin ?> – <?= $cukupMax ?></td>
                        <td>Peserta didik menguasai sebagian indikator TP, masih butuh bimbingan di bagian tertentu.</td>
                    </tr>
                    <tr>
                        <td><b>Baik</b></td>
                        <td class="text-center"><?= $baikMin ?> – <?= $baikMax ?></td>
                        <td>Peserta didik telah mencapai kriteria ketuntasan minimal Tujuan Pembelajaran.</td>
                    </tr>
                    <tr>
                        <td><b>Sangat Baik</b></td>
                        <td class="text-center"><?= $sangatBaikMin ?> – 100</td>
                        <td>Peserta didik menguasai seluruh aspek TP secara konsisten dan layak diberikan pengayaan.</td>
                    </tr>
                </tbody>
            </table>

            <div class="section-title fw-bold mt-4 mb-2">B. Kriteria Ketercapaian per TP</div>
            <?php if (empty($kktpsData)): ?>
                <p class="text-muted text-center py-3 border border-dashed rounded">Data KKTP belum dibuat.</p>
            <?php else: ?>
                <?php foreach ($kktpsData as $k): ?>
                <div style="margin-bottom: 20px; page-break-inside: avoid;">
                    <div class="fw-bold text-dark" style="border-bottom: 2px solid #000000; padding-bottom: 5px; margin-bottom: 10px; color: #000000 !important; font-size: 11.5pt;">
                        <?= esc($k['code']) ?> : <?= esc($k['tp_description']) ?>
                    </div>
                    <div style="margin-bottom: 8px;">
                        <b>Indikator Ketercapaian:</b>
                        <ol style="margin-bottom: 5px; padding-left: 20px;">
                            <?php $indicatorLines = explode("\n", $k['indicators']); ?>
                            <?php foreach ($indicatorLines as $indLine): $indLine = trim($indLine); if (empty($indLine)) continue; ?>
                                <li><?= esc($indLine) ?></li>
                            <?php endforeach; ?>
                        </ol>
                    </div>
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th width="25%">Perlu Bimbingan (0-<?= $bimbinganMax ?>)</th>
                                <th width="25%">Cukup (<?= $cukupMin ?>-<?= $cukupMax ?>)</th>
                                <th width="25%">Baik (<?= $baikMin ?>-<?= $baikMax ?>)</th>
                                <th width="25%">Sangat Baik (<?= $sangatBaikMin ?>-100)</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td><?= nl2br(esc($k['rubric_bimbingan'])) ?></td>
                                <td><?= nl2br(esc($k['rubric_cukup'])) ?></td>
                                <td><?= nl2br(esc($k['rubric_baik'])) ?></td>
                                <td><?= nl2br(esc($k['rubric_sangat_baik'])) ?></td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                <?php endforeach; ?>
            <?php endif; ?>

            <!-- Signatures -->
            <table class="ttd-table">
                <tr>
                    <td style="width: 50%;">Mengetahui,<br><?= ($device['school_type'] === 'madrasah') ? 'Kepala Madrasah' : 'Kepala Sekolah' ?></td>
                    <td style="width: 50%;"><?= esc($settings['city'] ?? 'Kota') ?>, ....................... <?= date('Y') ?><br>Guru Mata Pelajaran</td>
                </tr>
                <tr><td style="height: 60px;"></td><td></td></tr>
                <tr>
                    <td><strong><u><?= esc($settings['principal_name'] ?? $settings['headmaster_name'] ?? '..................................') ?></u></strong><br>NIP. <?= esc($settings['principal_nip'] ?? $settings['headmaster_nip'] ?? '........................') ?></td>
                    <td><strong><u><?= esc($device['teacher_name'] ?? '..................................') ?></u></strong><br><?= esc(guess_id_label($device['teacher_nip'] ?? null)) ?>. <?= esc($device['teacher_nip'] ?? '........................') ?></td>
                </tr>
            </table>
        </div>
        <?php endif; ?>

        <?php if (empty($singleType)): ?><div class="a4-page-break"></div><?php endif; ?>

        <!-- ========================================== -->
        <!-- 8. RPM (MODUL AJAR) SECTION -->
        <!-- ========================================== -->
        <?php if (empty($singleType) || $singleType === 'rpm'): ?>
        <?php if (empty($modulsData)): ?>
            <div class="a4-page page-portrait">
                <div class="doc-title">RENCANA PELAKSANAAN PEMBELAJARAN (MODUL AJAR)</div>
                <p class="text-muted text-center py-5 border border-dashed rounded">Belum ada modul ajar yang digenerate oleh AI untuk perangkat pembelajaran ini.</p>
            </div>
        <?php else: ?>
            <?php foreach ($modulsData as $mIndex => $mData): 
                $modul = $mData['modul'];
            ?>
            <div class="a4-page page-portrait" style="margin-bottom: 2rem;">
                
                <!-- COVER / BLUE HEADER BANNER -->
                <div style="background-color: #1a3c6e; padding: 12px; text-align: center; border: 2px solid #1a3c6e; border-radius: 4px; margin-bottom: 25px;">
                    <h2 style="color: #ffffff; font-family: 'Times New Roman'; font-size: 13pt; font-weight: bold; margin: 0; text-transform: uppercase;">
                        MODUL AJAR: <?= strtoupper(esc($device['subject_name'] ?? '')) ?>
                    </h2>
                </div>

                <!-- I. INFORMASI UMUM -->
                <div class="section-title-roman">I. INFORMASI UMUM</div>

                <div class="subsection-title">1. Identitas Modul</div>
                <table class="info-table" style="width: 100%; border-collapse: collapse; margin-top: 10px; margin-bottom: 15px;">
                    <tr><td style="width: 30%; background-color: #F5F5F5; font-weight: bold;">Nama Penyusun</td><td><?= esc($device['teacher_name'] ?? '-') ?></td></tr>
                    <tr><td style="width: 30%; background-color: #F5F5F5; font-weight: bold;"><?= esc(guess_id_label($device['teacher_nip'] ?? null)) ?></td><td><?= esc($device['teacher_nip'] ?? '-') ?></td></tr>
                    <tr><td style="width: 30%; background-color: #F5F5F5; font-weight: bold;">Institusi</td><td><?= esc($settings['school_name'] ?? '-') ?></td></tr>
                    <tr><td style="width: 30%; background-color: #F5F5F5; font-weight: bold;">Jenjang</td><td><?= $device['school_type'] === 'madrasah' ? 'Madrasah Tsanawiyah (MTs)' : 'SMP' ?></td></tr>
                    <tr><td style="width: 30%; background-color: #F5F5F5; font-weight: bold;">Mata Pelajaran</td><td><?= esc($device['subject_name'] ?? '-') ?></td></tr>
                    <tr><td style="width: 30%; background-color: #F5F5F5; font-weight: bold;">Fase / Kelas</td><td>Fase <?= esc($device['phase'] ?? '-') ?> / Kelas <?= esc($device['grade_name'] ?? '-') ?></td></tr>
                    <tr><td style="width: 30%; background-color: #F5F5F5; font-weight: bold;">Tahun Ajaran</td><td><?= esc($device['academic_year_name'] ?? '-') ?></td></tr>
                    <tr><td style="width: 30%; background-color: #F5F5F5; font-weight: bold;">Semester</td><td><?= $semester = ($mData['chapterTps'][0]['semester'] ?? 1) == 1 ? 'Ganjil' : 'Genap' ?> (<?= ($mData['chapterTps'][0]['semester'] ?? 1) ?>)</td></tr>
                    <tr><td style="width: 30%; background-color: #F5F5F5; font-weight: bold;">Bab / Materi</td><td><?= esc($mData['chapterName']) ?></td></tr>
                    <tr><td style="width: 30%; background-color: #F5F5F5; font-weight: bold;">Alokasi Waktu</td><td><?= esc($mData['totalJp']) ?> JP (<?= $mData['jumlahPertemuan'] ?> pertemuan)</td></tr>
                    <tr><td style="width: 30%; background-color: #F5F5F5; font-weight: bold;">Profil Lulusan</td><td><?= esc($mData['dplChapterDisplay'] ?: '-') ?></td></tr>
                    <tr><td style="width: 30%; background-color: #F5F5F5; font-weight: bold;">Topik KBC</td><td><?= esc($mData['kbcChapterDisplay'] ?: '-') ?></td></tr>
                    <tr><td style="width: 30%; background-color: #F5F5F5; font-weight: bold;">Elemen CP</td><td><?= esc($mData['cpElementsDisplay'] ?? '-') ?></td></tr>
                </table>

                <div class="subsection-title">2. Kompetensi Awal (Prasyarat)</div>
                <div class="content-box">
                    <?= renderSmartFieldHtml($modul['kompetensi_awal']) ?>
                </div>

                <div class="subsection-title">3. Sarana & Prasarana</div>
                <div class="content-box">
                    <?= renderSmartFieldHtml($modul['sarana_prasarana']) ?>
                </div>

                <div class="subsection-title">4. Target Peserta Didik</div>
                <div class="content-box">
                    <?= renderSmartFieldHtml($modul['target_peserta_didik']) ?>
                </div>

                <div class="subsection-title">5. Model & Pendekatan Pembelajaran</div>
                <div class="content-box">
                    <?= renderSmartFieldHtml($modul['model_pembelajaran']) ?>
                </div>

                <!-- II. KOMPONEN INTI -->
                <div class="section-title-roman">II. KOMPONEN INTI</div>

                <div class="subsection-title">1. Capaian Pembelajaran (CP)</div>
                <div class="content-box">
                    <?php
                    $cpLines = explode("\n", $device['cp_content'] ?? '');
                    $cpLines = array_map('trim', $cpLines);
                    $cpLines = array_filter($cpLines, fn($l) => $l !== '');
                    $cpLines = array_values($cpLines);
                    if (!empty($cpLines)):
                        echo '<p>' . esc($cpLines[0]) . '</p>';
                        $restLines = array_slice($cpLines, 1);
                        if (!empty($restLines) && preg_match('/^\d+\.\s/', $restLines[0])):
                            echo '<table class="data-table"><thead><tr><th width="8%">No</th><th>Capaian Pembelajaran</th></tr></thead><tbody>';
                            $n = 0;
                            foreach ($restLines as $rl):
                                if (preg_match('/^\d+\.\s+(.+)/', $rl, $m)):
                                    $n++;
                                    echo '<tr><td class="text-center">' . $n . '</td><td>' . esc(trim($m[1])) . '</td></tr>';
                                endif;
                            endforeach;
                            echo '</tbody></table>';
                        else:
                            foreach ($restLines as $rl):
                                echo '<p>' . esc($rl) . '</p>';
                            endforeach;
                        endif;
                    endif;
                    ?>
                </div>

                <div class="subsection-title">2. Tujuan Pembelajaran (TP) & Indikator Ketercapaian</div>
                <div class="content-box p-0 border-0 bg-transparent">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th width="15%">Kode</th>
                                <th>Tujuan Pembelajaran</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($mData['chapterTps'] as $ctp): ?>
                            <tr>
                                <td class="text-center fw-bold"><?= esc($ctp['code']) ?></td>
                                <td><?= esc($ctp['description']) ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>

                <div class="subsection-title">3. Pemahaman Bermakna</div>
                <div class="content-box">
                    <?= renderSmartFieldHtml($modul['pemahaman_bermakna']) ?>
                </div>

                <div class="subsection-title">4. Pertanyaan Pemantik</div>
                <div class="content-box">
                    <?= renderSmartFieldHtml($modul['pertanyaan_pemantik']) ?>
                </div>

                <div class="subsection-title">5. Materi Esensial / Pokok</div>
                <div class="content-box">
                    <?= renderSmartFieldHtml($modul['materi_esensial']) ?>
                </div>

                <!-- III. KEGIATAN PEMBELAJARAN -->
                <div class="section-title-roman">III. KEGIATAN PEMBELAJARAN</div>

                <?php if (!empty($mData['skenario'])): foreach ($mData['skenario'] as $sk): 
                    $pert = $sk['pertemuan'] ?? 1;
                ?>
                <div style="margin-bottom: 25px; page-break-inside: avoid;">
                    <div class="fw-bold mb-2" style="font-size:11.5pt;">Pertemuan <?= esc($pert) ?></div>

                    <?php $materi = $sk['sub_materi'] ?? ''; if (!empty($materi)): ?>
                    <div style="margin-bottom: 10px;">
                        <span style="font-weight: bold;">Materi:</span>
                        <p class="mt-1 ps-2"><?= esc($materi) ?></p>
                    </div>
                    <?php endif; ?>

                    <?php $iktps = $sk['iktp'] ?? []; if (!empty($iktps) && is_array($iktps)): ?>
                    <div style="margin-bottom: 10px;">
                        <span style="font-weight: bold;">IKTP Pertemuan <?= esc($pert) ?>:</span>
                        <table class="table table-borderless table-sm mb-2 mt-1">
                            <tbody>
                                <?php $nIktp = 1; foreach ($iktps as $ik): ?>
                                <tr>
                                    <td width="30" class="text-center"><?= $nIktp ?>.</td>
                                    <td><?= esc($ik) ?></td>
                                </tr>
                                <?php $nIktp++; endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <?php endif; ?>

                    <div class="mb-2">
                        <span class="fw-bold">A. Pendahuluan</span>
                        <div class="mt-1"><?= renderSmartFieldHtml($sk['pendahuluan'] ?? '') ?></div>
                    </div>

                    <div class="mb-2">
                        <span class="fw-bold">B. Kegiatan Inti</span>
                        <div class="mt-1"><?= renderSmartFieldHtml($sk['inti'] ?? '') ?></div>
                    </div>

                    <div class="mb-2">
                        <span class="fw-bold">C. Penutup</span>
                        <div class="mt-1"><?= renderSmartFieldHtml($sk['penutup'] ?? '') ?></div>
                    </div>
                </div>
                <?php endforeach; else: ?>
                <p class="text-muted italic ps-3">Belum ada kegiatan pembelajaran.</p>
                <?php endif; ?>

                <!-- IV. ASESMEN -->
                <div class="section-title-roman">IV. ASESMEN (PENILAIAN)</div>

                <div class="subsection-title">1. Asesmen Awal / Diagnostik</div>
                <div class="content-box">
                    <?php
                    $diag = $modul['asesmen_diagnostik'] ?? '';
                    if (empty(trim(is_array($diag) ? '' : $diag)) && !empty($modul['assessment']['diagnostik'])) {
                        $diag = $modul['assessment']['diagnostik'];
                    }
                    echo renderSmartFieldHtml($diag);
                    ?>
                </div>

                <div class="subsection-title">2. Asesmen Formatif (Proses)</div>
                <div class="content-box">
                    <?php
                    $form = $modul['asesmen_formatif'] ?? '';
                    if (empty(trim(is_array($form) ? '' : $form)) && !empty($modul['assessment']['formatif'])) {
                        $form = $modul['assessment']['formatif'];
                    }
                    echo renderSmartFieldHtml($form);
                    ?>
                </div>

                <div class="subsection-title">3. Asesmen Sumatif (Akhir)</div>
                <div class="content-box">
                    <?php
                    $sum = $modul['asesmen_sumatif'] ?? '';
                    if (empty(trim(is_array($sum) ? '' : $sum)) && !empty($modul['assessment']['sumatif'])) {
                        $sum = $modul['assessment']['sumatif'];
                    }
                    echo renderSmartFieldHtml($sum);
                    ?>
                </div>

                <!-- V. PENGAYAAN & REMEDIAL -->
                <div class="section-title-roman">V. PENGAYAAN & REMEDIAL</div>
                <div class="subsection-title">1. Program Pengayaan</div>
                <div class="content-box">
                    <?= renderSmartFieldHtml($modul['pengayaan']) ?>
                </div>
                <div class="subsection-title">2. Program Remedial</div>
                <div class="content-box">
                    <?= renderSmartFieldHtml($modul['remedial']) ?>
                </div>

                <!-- VI. LAMPIRAN -->
                <div class="section-title-roman">VI. LAMPIRAN</div>
                
                <div class="subsection-title">1. Glosarium</div>
                <div class="content-box">
                    <?= renderSmartFieldHtml($modul['glosarium']) ?>
                </div>

                <div class="subsection-title">2. Daftar Pustaka</div>
                <div class="content-box">
                    <?php 
                    $lines = explode("\n", $mData['daftarPustaka'] ?? '');
                    echo '<ul class="mb-0">';
                    foreach ($lines as $l) {
                        if (trim($l) !== '') echo '<li class="mb-1">' . esc(trim($l)) . '</li>';
                    }
                    echo '</ul>';
                    ?>
                </div>

                <!-- LEMBAR KERJA PESERTA DIDIK (LKPD) -->
                <?php if (!empty($mData['skenario'])): ?>
                    <?php foreach ($mData['skenario'] as $sk): 
                        $pert = $sk['pertemuan'] ?? 1;
                        $materi = $sk['sub_materi'] ?? '';
                        $iktps = $sk['iktp'] ?? [];
                    ?>
                    <div style="page-break-before: always; margin-top: 30px;">
                        <div class="text-center fw-bold fs-5 mb-3" style="font-family: 'Times New Roman'; text-transform: uppercase;">LEMBAR KERJA PESERTA DIDIK (LKPD)</div>
                        <div class="fw-bold mb-3" style="font-family: 'Times New Roman';">Pertemuan <?= $pert ?><?= $materi ? ': ' . esc($materi) : '' ?></div>
                        
                        <table class="data-table" style="font-family: 'Times New Roman'; width: 100%; border-collapse: collapse; margin-bottom: 20px;">
                            <tbody>
                                <tr>
                                    <td width="30%" style="background-color: #F5F5F5; font-weight: bold; border: 1px solid #000; padding: 8px;">Identitas</td>
                                    <td style="border: 1px solid #000; padding: 8px; line-height: 1.8;">
                                        Nama          : ........................................<br>
                                        Kelas         : ........................................<br>
                                        Pertemuan ke- : <?= $pert ?>
                                    </td>
                                </tr>
                                <tr>
                                    <td style="background-color: #F5F5F5; font-weight: bold; border: 1px solid #000; padding: 8px;">Tujuan</td>
                                    <td style="border: 1px solid #000; padding: 8px;">
                                        <?php if (!empty($iktps) && is_array($iktps)): ?>
                                            <ul class="ps-3 mb-0">
                                                <?php foreach ($iktps as $ik): ?>
                                                    <li><?= esc($ik) ?></li>
                                                <?php endforeach; ?>
                                            </ul>
                                        <?php else: ?>
                                            ........................................
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                <tr>
                                    <td style="background-color: #F5F5F5; font-weight: bold; border: 1px solid #000; padding: 8px;">Langkah Kegiatan</td>
                                    <td style="border: 1px solid #000; padding: 8px; text-align: justify; vertical-align: top;">
                                        <?= !empty($sk['lkpd_langkah']) ? renderSmartFieldHtml($sk['lkpd_langkah']) : '........................................' ?>
                                    </td>
                                </tr>
                                <tr>
                                    <td style="background-color: #F5F5F5; font-weight: bold; border: 1px solid #000; padding: 8px;">Soal/Tugas</td>
                                    <td style="border: 1px solid #000; padding: 8px; text-align: justify; vertical-align: top;">
                                        <?= !empty($sk['lkpd_soal']) ? renderSmartFieldHtml($sk['lkpd_soal']) : '........................................' ?>
                                    </td>
                                </tr>
                                <tr>
                                    <td colspan="2" style="border: 1px solid #000; padding: 15px; height: 150px; vertical-align: top; color: #aaa;">
                                        <i>Ruang Jawab:</i>
                                    </td>
                                </tr>
                                <tr>
                                    <td style="background-color: #F5F5F5; font-weight: bold; border: 1px solid #000; padding: 8px;">Kesimpulan</td>
                                    <td style="border: 1px solid #000; padding: 8px; text-align: justify; vertical-align: top;">
                                        <?= !empty($sk['lkpd_kesimpulan']) ? renderSmartFieldHtml($sk['lkpd_kesimpulan']) : '........................................' ?>
                                    </td>
                                </tr>
                                <tr>
                                    <td colspan="2" style="border: 1px solid #000; padding: 15px; height: 100px; vertical-align: top; color: #aaa;">
                                        <i>Ruang Refleksi:</i>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                    <?php endforeach; ?>
                <?php endif; ?>

                <!-- LEMBAR PENGESAHAN -->
                <div style="page-break-before: always; margin-top: 30px;">
                    <div style="background-color: #e2e8f0; padding: 8px; text-align: center; border: 1px solid #222; margin-bottom: 25px;">
                        <h3 style="font-family: 'Times New Roman'; font-size: 12pt; font-weight: bold; margin: 0; text-transform: uppercase;">
                            LEMBAR PENGESAHAN MODUL AJAR
                        </h3>
                    </div>
                    <!-- Signatures -->
                    <table class="ttd-table" style="page-break-inside: avoid;">
                        <tr>
                            <td style="width: 50%;">Mengetahui,<br><?= ($device['school_type'] === 'madrasah') ? 'Kepala Madrasah' : 'Kepala Sekolah' ?></td>
                            <td style="width: 50%;"><?= esc($settings['city'] ?? 'Kota') ?>, ....................... <?= date('Y') ?><br>Guru Mata Pelajaran</td>
                        </tr>
                        <tr><td style="height: 60px;"></td><td></td></tr>
                        <tr>
                            <td><strong><u><?= esc($settings['principal_name'] ?? $settings['headmaster_name'] ?? '..................................') ?></u></strong><br>NIP. <?= esc($settings['principal_nip'] ?? $settings['headmaster_nip'] ?? '........................') ?></td>
                            <td><strong><u><?= esc($device['teacher_name'] ?? '..................................') ?></u></strong><br><?= esc(guess_id_label($device['teacher_nip'] ?? null)) ?>. <?= esc($device['teacher_nip'] ?? '........................') ?></td>
                        </tr>
                    </table>
                </div>
            </div>
            
            <?php if (empty($singleType) && ($mIndex < count($modulsData) - 1)): ?>
                <div class="a4-page-break"></div>
            <?php endif; ?>

            <?php endforeach; ?>
        <?php endif; ?>
        <?php endif; ?>

    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
