<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Buku Induk - <?= esc($student['full_name']) ?></title>
    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <style>
        /* Desain Khusus Buku Induk Formal */
        body {
            background-color: #f8f9fa; /* Latar abu-abu di browser agar terlihat seperti lembaran kertas */
            color: #000000;
            padding-top: 30px;
            padding-bottom: 30px;
        }

        .buku-induk-container {
            background: #ffffff;
            font-family: "Times New Roman", Times, serif;
            line-height: 1.4;
            margin: 0 auto;
            max-width: 900px;
        }

        .header-induk {
            border-bottom: 3px double #000000;
            padding-bottom: 8px;
            margin-bottom: 15px;
        }

        .table-induk {
            width: 100%;
            margin-bottom: 12px;
            border-collapse: collapse;
        }

        .table-induk td {
            padding: 3px 5px;
            vertical-align: top;
            font-size: 13px;
        }

        .section-title {
            font-weight: bold;
            font-size: 14px;
            text-transform: uppercase;
            margin-top: 10px;
            margin-bottom: 5px;
            border-bottom: 1px solid #000;
            padding-bottom: 2px;
        }

        .photo-box {
            width: 3cm;
            height: 4cm;
            border: 1px solid #000;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
            text-align: center;
            background-color: #ffffff;
        }

        .signature-area {
            font-size: 13px;
        }

        /* Pembatas halaman print untuk memisahkan Halaman 1 & Halaman 2 */
        .page-break {
            page-break-before: always;
        }

        /* Aturan Print */
        @media print {
            body {
                background: none;
                color: #000;
                padding: 0 !important;
            }
            .buku-induk-container {
                width: 100%;
                margin: 0;
                padding: 0;
                box-shadow: none !important;
                border: none !important;
            }
            @page {
                size: A4 portrait;
                margin: 1.5cm;
            }
            .page-break {
                page-break-before: always;
            }
        }
    </style>
</head>
<body>

    <?php
    helper('logo');
    $logoKemenag = getLogo('kemenag');
    $logoSekolah = getLogo('sekolah');

    // Susun alamat lengkap sekolah
    $fullAddress = esc($settings['address'] ?? '');
    if (!empty($settings['village'])) $fullAddress .= ' Kel. ' . esc($settings['village']);
    if (!empty($settings['district'])) $fullAddress .= ', Kec. ' . esc($settings['district']);
    if (!empty($settings['city'])) $fullAddress .= ', Kab/Kota. ' . esc($settings['city']);
    if (!empty($settings['province'])) $fullAddress .= ', Prov. ' . esc($settings['province']);
    if (!empty($settings['postal_code'])) $fullAddress .= ' - ' . esc($settings['postal_code']);
    if (!empty($settings['phone'])) $fullAddress .= ' Telp: ' . esc($settings['phone']);
    if (!empty($settings['email'])) $fullAddress .= ' Email: ' . esc($settings['email']);
    ?>

    <div class="buku-induk-container">
        
        <!-- ========================================== -->
        <!-- HALAMAN 1: BIODATA SISWA                   -->
        <!-- ========================================== -->
        
        <!-- Kop Surat Buku Induk / Nama Sekolah -->
        <div class="header-induk d-flex align-items-center justify-content-between pb-2 mb-3">
            <img src="<?= $logoKemenag ?>" style="height: 60px; object-fit: contain;">
            <div class="text-center px-3 flex-grow-1">
                <h4 class="fw-bold m-0" style="font-family: Arial, sans-serif; letter-spacing: 1px; font-size: 17px;">LEMBAR BUKU INDUK SISWA</h4>
                <h5 class="fw-bold m-0 mt-1 text-uppercase" style="font-family: Arial, sans-serif; font-size: 15px;">
                    <?= esc($settings['school_name'] ?? 'SEKOLAH') ?>
                </h5>
                <p class="m-0 mt-1 text-muted" style="font-family: Arial, sans-serif; font-size: 10px;">
                    <?= $fullAddress ?>
                </p>
            </div>
            <img src="<?= $logoSekolah ?>" style="height: 60px; object-fit: contain;">
        </div>

        <div class="row">
            <!-- Sisi Kiri: Biodata Lengkap -->
            <div class="col-8">
                <!-- A. DATA PRIBADI -->
                <div class="section-title">A. Keterangan Pribadi Siswa</div>
                <table class="table-induk">
                    <tr>
                        <td width="35%">1. Nama Lengkap</td>
                        <td width="3%">:</td>
                        <td class="fw-bold"><?= esc($student['full_name']) ?></td>
                    </tr>
                    <tr>
                        <td>2. Nomor Induk Siswa (NIS)</td>
                        <td>:</td>
                        <td class="fw-bold"><?= esc($student['nis'] ?? '-') ?></td>
                    </tr>
                    <tr>
                        <td>3. NISN</td>
                        <td>:</td>
                        <td><?= esc($student['nisn'] ?? '-') ?></td>
                    </tr>
                    <tr>
                        <td>4. NIK (No. KTP)</td>
                        <td>:</td>
                        <td><?= esc($student['nik'] ?? '-') ?></td>
                    </tr>
                    <tr>
                        <td>5. Jenis Kelamin</td>
                        <td>:</td>
                        <td><?= $student['gender'] === 'L' ? 'Laki-laki' : 'Perempuan' ?></td>
                    </tr>
                    <tr>
                        <td>6. Tempat & Tgl Lahir</td>
                        <td>:</td>
                        <td><?= esc($student['birth_place'] ?? '-') ?>, <?= esc($student['birth_date'] ?? '-') ?></td>
                    </tr>
                    <tr>
                        <td>7. Agama</td>
                        <td>:</td>
                        <td><?= esc($student['religion'] ?? '-') ?></td>
                    </tr>
                    <tr>
                        <td>8. Nomor KIP (jika ada)</td>
                        <td>:</td>
                        <td><?= esc($student['kip_no'] ?? '-') ?></td>
                    </tr>
                </table>

                <!-- B. ALAMAT TINGGAL -->
                <div class="section-title">B. Keterangan Tempat Tinggal</div>
                <table class="table-induk">
                    <tr>
                        <td width="35%">1. Alamat Rumah</td>
                        <td width="3%">:</td>
                        <td><?= esc($student['address'] ?? '-') ?></td>
                    </tr>
                    <tr>
                        <td>2. RT / RW</td>
                        <td>:</td>
                        <td>RT <?= esc($student['rt'] ?? '-') ?> / RW <?= esc($student['rw'] ?? '-') ?></td>
                    </tr>
                    <tr>
                        <td>3. Desa / Kelurahan</td>
                        <td>:</td>
                        <td><?= esc($student['village'] ?? '-') ?></td>
                    </tr>
                    <tr>
                        <td>4. Kecamatan</td>
                        <td>:</td>
                        <td><?= esc($student['district'] ?? '-') ?></td>
                    </tr>
                    <tr>
                        <td>5. Kota / Kabupaten</td>
                        <td>:</td>
                        <td><?= esc($student['city'] ?? '-') ?></td>
                    </tr>
                    <tr>
                        <td>6. Provinsi</td>
                        <td>:</td>
                        <td><?= esc($student['province'] ?? '-') ?></td>
                    </tr>
                    <tr>
                        <td>7. Kode Pos / No. HP</td>
                        <td>:</td>
                        <td><?= esc($student['postal_code'] ?? '-') ?> / <?= esc($student['phone'] ?? '-') ?></td>
                    </tr>
                </table>
            </div>

            <!-- Sisi Kanan: Foto, Info Pendaftaran & Keluar -->
            <div class="col-4 d-flex flex-column align-items-center">
                <div class="mb-3 text-center">
                    <span class="d-block text-muted mb-1" style="font-size: 11px;">PAS FOTO 3x4</span>
                    <?php if (!empty($student['photo'])): ?>
                        <img src="<?= \App\Services\StorageService::getUrl($student['photo'], 'students') ?>" style="width: 3cm; height: 4cm; object-fit: cover; border: 1px solid #000;">
                    <?php else: ?>
                        <div class="photo-box mx-auto">
                            <span>FOTO SISWA</span>
                        </div>
                    <?php endif; ?>
                </div>

                <div class="w-100 border p-2 rounded bg-light" style="font-size: 11px;">
                    <div class="fw-bold border-bottom pb-1 mb-2 text-center text-uppercase">C. Masuk & Keluar</div>
                    <div class="mb-1"><strong>Tgl Masuk:</strong> <?= $student['entry_date'] ? date('d M Y', strtotime($student['entry_date'])) : '-' ?></div>
                    <div class="mb-1"><strong>Tahun Masuk:</strong> <?= esc($student['entry_year'] ?? '-') ?></div>
                    <div class="mb-1"><strong>Sekolah Asal:</strong> <?= esc($student['origin_school'] ?? '-') ?></div>
                    <div class="mb-1"><strong>No Seri Ijazah:</strong> <?= esc($student['graduation_certificate_no'] ?? '-') ?></div>
                    <hr class="my-1">
                    <div class="mb-1"><strong>Status:</strong> <strong><?= esc($student['status']) ?></strong></div>
                    <div class="mb-1"><strong>Tgl Keluar:</strong> <?= $student['exit_date'] ? date('d M Y', strtotime($student['exit_date'])) : '-' ?></div>
                    <div class="mb-1"><strong>Alasan Keluar:</strong> <?= esc($student['exit_reason'] ?? '-') ?></div>
                </div>
            </div>
        </div>

        <div class="row mt-1">
            <div class="col-12">
                <!-- D. ORANG TUA KANDUNG -->
                <div class="section-title">D. Keterangan Orang Tua Kandung</div>
                <div class="row mb-3">
                    <div class="col-6">
                        <table class="table-induk table-bordered" style="border: 1px solid #000;">
                            <thead>
                                <tr class="table-light">
                                    <th colspan="3" class="p-1 ps-2 fw-bold text-center text-uppercase" style="font-size: 12px; border-bottom: 1px solid #000;">Data Ayah Kandung</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td width="38%">Nama Lengkap</td>
                                    <td width="5%">:</td>
                                    <td class="fw-bold"><?= esc($student['father_name'] ?? '-') ?></td>
                                </tr>
                                <tr>
                                    <td>NIK Ayah</td>
                                    <td>:</td>
                                    <td><?= esc($student['father_nik'] ?? '-') ?></td>
                                </tr>
                                <tr>
                                    <td>TTL</td>
                                    <td>:</td>
                                    <td><?= esc($student['father_birth_place'] ?? '-') ?>, <?= esc($student['father_birth'] ?? '-') ?></td>
                                </tr>
                                <tr>
                                    <td>Pendidikan</td>
                                    <td>:</td>
                                    <td><?= esc($student['father_edu'] ?? '-') ?></td>
                                </tr>
                                <tr>
                                    <td>Pekerjaan</td>
                                    <td>:</td>
                                    <td><?= esc($student['father_job'] ?? '-') ?></td>
                                </tr>
                                <tr>
                                    <td>No. Telepon</td>
                                    <td>:</td>
                                    <td><?= esc($student['father_phone'] ?? '-') ?></td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                    <div class="col-6">
                        <table class="table-induk table-bordered" style="border: 1px solid #000;">
                            <thead>
                                <tr class="table-light">
                                    <th colspan="3" class="p-1 ps-2 fw-bold text-center text-uppercase" style="font-size: 12px; border-bottom: 1px solid #000;">Data Ibu Kandung</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td width="38%">Nama Lengkap</td>
                                    <td width="5%">:</td>
                                    <td class="fw-bold"><?= esc($student['mother_name'] ?? '-') ?></td>
                                </tr>
                                <tr>
                                    <td>NIK Ibu</td>
                                    <td>:</td>
                                    <td><?= esc($student['mother_nik'] ?? '-') ?></td>
                                </tr>
                                <tr>
                                    <td>TTL</td>
                                    <td>:</td>
                                    <td><?= esc($student['mother_birth_place'] ?? '-') ?>, <?= esc($student['mother_birth'] ?? '-') ?></td>
                                </tr>
                                <tr>
                                    <td>Pendidikan</td>
                                    <td>:</td>
                                    <td><?= esc($student['mother_edu'] ?? '-') ?></td>
                                </tr>
                                <tr>
                                    <td>Pekerjaan</td>
                                    <td>:</td>
                                    <td><?= esc($student['mother_job'] ?? '-') ?></td>
                                </tr>
                                <tr>
                                    <td>No. Telepon</td>
                                    <td>:</td>
                                    <td><?= esc($student['mother_phone'] ?? '-') ?></td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>

                <!-- E. RIWAYAT KELAS -->
                <div class="section-title">E. Riwayat Rombongan Belajar (Kelas)</div>
                <table class="table table-sm table-bordered text-center align-middle" style="font-size: 12px; margin-bottom: 5px; border: 1px solid #000;">
                    <thead class="table-light">
                        <tr>
                            <th>Tahun Ajaran</th>
                            <th>Fase / Tingkat</th>
                            <th>Kelas (Rombel)</th>
                            <th>Status Kenaikan</th>
                            <th>Catatan</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($histories)): ?>
                            <tr>
                                <td colspan="5" class="text-muted py-2">Belum ada riwayat kelas terdaftar.</td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($histories as $h): ?>
                                <tr>
                                    <td><?= esc($h['year_name']) ?></td>
                                    <td>Fase <?= esc($h['grade_name']) ?></td>
                                    <td class="fw-bold"><?= esc($h['classroom_name']) ?></td>
                                    <td><?= esc($h['status']) ?></td>
                                    <td><?= esc($h['notes'] ?? '-') ?></td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>


        <!-- ========================================== -->
        <!-- HALAMAN 2: LEMBAR NILAI REKAPITULASI       -->
        <!-- ========================================== -->
        <div class="page-break"></div>

        <!-- Kop Halaman Nilai -->
        <div class="header-induk d-flex align-items-center justify-content-between pb-2 mb-3">
            <img src="<?= $logoKemenag ?>" style="height: 60px; object-fit: contain;">
            <div class="text-center px-3 flex-grow-1">
                <h4 class="fw-bold m-0" style="font-family: Arial, sans-serif; letter-spacing: 1px; font-size: 17px;">LEMBAR HASIL BELAJAR SISWA (LEGER)</h4>
                <h5 class="fw-bold m-0 mt-1 text-uppercase" style="font-family: Arial, sans-serif; font-size: 15px;">
                    <?= esc($settings['school_name'] ?? 'SEKOLAH') ?>
                </h5>
                <p class="m-0 mt-1 text-muted" style="font-family: Arial, sans-serif; font-size: 10px;">
                    <?= $fullAddress ?>
                </p>
            </div>
            <img src="<?= $logoSekolah ?>" style="height: 60px; object-fit: contain;">
        </div>

        <!-- Identitas Siswa Halaman Nilai di bawah Kop -->
        <table class="table-induk mb-3 border p-2 bg-light rounded" style="font-size: 12px; border: 1px solid #ddd;">
            <tr>
                <td width="20%"><strong>Nama Siswa</strong></td>
                <td width="3%">:</td>
                <td class="fw-bold" width="37%"><?= esc($student['full_name']) ?></td>
                <td width="20%"><strong>Tempat, Tgl Lahir</strong></td>
                <td width="3%">:</td>
                <td width="17%"><?= esc($student['birth_place'] ?? '-') ?>, <?= esc($student['birth_date'] ?? '-') ?></td>
            </tr>
            <tr>
                <td><strong>NIS / NISN</strong></td>
                <td>:</td>
                <td><?= esc($student['nis'] ?? '-') ?> / <?= esc($student['nisn'] ?? '-') ?></td>
                <td><strong>Jenis Kelamin</strong></td>
                <td>:</td>
                <td><?= $student['gender'] === 'L' ? 'Laki-laki' : 'Perempuan' ?></td>
            </tr>
        </table>

        <div class="section-title">F. Rekapitulasi Nilai Akademik per Semester</div>
        
        <!-- Tabel Nilai Sem 1 - Sem 6 -->
        <table class="table table-bordered table-sm align-middle text-center" style="font-size: 12px; border: 1px solid #000; margin-bottom: 20px;">
            <thead class="table-light text-uppercase" style="border-bottom: 2px solid #000;">
                <tr>
                    <th rowspan="2" width="5%" class="align-middle">No</th>
                    <th rowspan="2" class="text-start align-middle" width="35%">Mata Pelajaran</th>
                    <th colspan="2">Kelas <?= esc($gradeHeader1) ?></th>
                    <th colspan="2">Kelas <?= esc($gradeHeader2) ?></th>
                    <th colspan="2">Kelas <?= esc($gradeHeader3) ?></th>
                    <th rowspan="2" width="12%" class="align-middle">Rata-Rata</th>
                </tr>
                <tr>
                    <th width="8%">Smt 1</th>
                    <th width="8%">Smt 2</th>
                    <th width="8%">Smt 3</th>
                    <th width="8%">Smt 4</th>
                    <th width="8%">Smt 5</th>
                    <th width="8%">Smt 6</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($subjects)): ?>
                    <tr>
                        <td colspan="9" class="text-muted py-5 text-center">Belum ada rekapitulasi nilai rapor di database.</td>
                    </tr>
                <?php else: ?>
                    <?php 
                    $noIdx = 1;
                    $sumSmt = array_fill(1, 6, 0);
                    $countSmt = array_fill(1, 6, 0);

                    foreach ($subjects as $groupName => $groupSubs): 
                    ?>
                        <!-- Header Kelompok Mapel dinamis (Kelompok A, B, C / Mulok) -->
                        <tr class="table-light text-start fw-bold" style="border-top: 1px solid #000; border-bottom: 1px solid #000;">
                            <td colspan="9" class="ps-2 text-secondary text-uppercase" style="font-size: 11px;"><?= esc($groupName) ?></td>
                        </tr>

                        <?php foreach ($groupSubs as $sub): 
                            $scores = [];
                            for ($i = 1; $i <= 6; $i++) {
                                $val = $sub['semesters'][$i];
                                if (is_numeric($val)) {
                                    $scores[] = $val;
                                    $sumSmt[$i] += $val;
                                    $countSmt[$i]++;
                                }
                            }
                            $avg = !empty($scores) ? round(array_sum($scores) / count($scores), 2) : '-';
                        ?>
                            <tr>
                                <td><?= $noIdx++ ?></td>
                                <td class="text-start fw-medium"><?= esc($sub['name']) ?></td>
                                <?php for ($i = 1; $i <= 6; $i++): ?>
                                    <td><?= esc($sub['semesters'][$i]) ?></td>
                                <?php endfor; ?>
                                <td class="fw-bold bg-light text-dark"><?= $avg ?></td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
            
            <?php if (!empty($subjects)): ?>
                <tfoot class="table-light fw-bold" style="border-top: 2px solid #000;">
                    <tr>
                        <td colspan="2" class="text-end pe-3">Jumlah Nilai</td>
                        <?php for ($i = 1; $i <= 6; $i++): ?>
                            <td><?= $countSmt[$i] > 0 ? $sumSmt[$i] : '-' ?></td>
                        <?php endfor; ?>
                        <td class="bg-light">-</td>
                    </tr>
                    <tr>
                        <td colspan="2" class="text-end pe-3">Rata-Rata Rapor</td>
                        <?php 
                        $grandTotalAvg = [];
                        for ($i = 1; $i <= 6; $i++): 
                            $avgSmt = $countSmt[$i] > 0 ? round($sumSmt[$i] / $countSmt[$i], 2) : '-';
                            if (is_numeric($avgSmt)) $grandTotalAvg[] = $avgSmt;
                        ?>
                            <td><?= $avgSmt ?></td>
                        <?php endfor; ?>
                        <td class="bg-dark text-white fw-bold">
                            <?= !empty($grandTotalAvg) ? round(array_sum($grandTotalAvg) / count($grandTotalAvg), 2) : '-' ?>
                        </td>
                    </tr>
                </tfoot>
            <?php endif; ?>
        </table>

        <!-- Tanda Tangan & Pengesahan Lembar Nilai -->
        <?php
        $principalName = $settings['principal_name'] ?? '[Nama Kepala Sekolah]';
        $principalNip = $settings['principal_nip'] ?? '-';
        $city = $settings['letter_city'] ?? $settings['city'] ?? '........................';
        if (empty(trim($city, '. '))) {
            $city = '........................';
        }
        $schoolTypeLabel = ($settings['school_type'] ?? 'madrasah') === 'madrasah' ? 'Kepala Madrasah' : 'Kepala Sekolah';
        ?>
        <div class="row signature-area mt-4">
            <div class="col-6">
                <!-- Sisi Kiri Sengaja Dikosongkan Tanpa Wali Kelas -->
            </div>
            <div class="col-6 text-center">
                <p class="m-0"><?= esc($city) ?>, ......................................</p>
                <p class="m-0"><?= $schoolTypeLabel ?>,</p>
                <div style="height: 1.8cm;"></div>
                <p class="m-0 fw-bold text-decoration-underline"><?= esc($principalName) ?></p>
                <p class="m-0">NIP. <?= esc($principalNip) ?></p>
            </div>
        </div>

    </div>

    <!-- Pemicu dialog cetak otomatis saat halaman dibuka -->
    <script>
        window.addEventListener('DOMContentLoaded', () => {
            setTimeout(() => {
                window.print();
            }, 500);
        });
    </script>
</body>
</html>
