<?= $this->extend('layouts/main') ?>
<?= $this->section('content') ?>

<?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="container-fluid px-0">
    <!-- Header Aksi -->
    <div class="d-flex align-items-center justify-content-between mb-4">
        <div>
            <h4 class="fw-bold text-dark mb-1">Tinjauan Lembar Buku Induk</h4>
            <span class="text-muted small">Tinjau biodata dan rekap nilai rapor secara lengkap sebelum dicetak.</span>
        </div>
        <div class="d-flex gap-2">
            <a href="/buku-induk/print/<?= $student['id'] ?>" target="_blank" class="btn btn-success rounded-pill px-4 shadow-sm">
                <i class="bi bi-printer me-1"></i> Cetak Lembar Buku Induk
            </a>
            <a href="/buku-induk" class="btn btn-light border text-muted rounded-pill px-3 shadow-sm">
                <i class="bi bi-arrow-left me-1"></i> Kembali
            </a>
        </div>
    </div>

    <div class="card shadow-sm border-0 rounded-3">
        <!-- Tab Navigasi -->
        <div class="card-header bg-white border-0 pt-3 px-4">
            <ul class="nav nav-tabs card-header-tabs" id="bukuIndukTabs" role="tablist">
                <li class="nav-item" role="presentation">
                    <button class="nav-link active fw-bold px-4 py-2" id="biodata-tab" data-bs-toggle="tab" data-bs-target="#biodata-pane" type="button" role="tab" aria-selected="true">
                        <i class="bi bi-person-lines-fill me-1"></i> Halaman 1: Identitas & Orang Tua
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link fw-bold px-4 py-2" id="nilai-tab" data-bs-toggle="tab" data-bs-target="#nilai-pane" type="button" role="tab" aria-selected="false">
                        <i class="bi bi-journal-text me-1"></i> Halaman 2: Rekap Nilai Akademik
                    </button>
                </li>
            </ul>
        </div>

        <div class="card-body p-4">
            <div class="tab-content" id="bukuIndukTabContent">
                
                <!-- ========================================== -->
                <!-- TAB 1: IDENTITAS & ORANG TUA SISWA         -->
                <!-- ========================================== -->
                <div class="tab-pane fade show active" id="biodata-pane" role="tabpanel" aria-labelledby="biodata-tab">
                    
                    <!-- KOP Contoh Tampilan -->
                    <div class="d-flex align-items-center justify-content-between border-bottom pb-3 mb-4">
                        <img src="<?= $logoKemenag ?>" style="height: 60px; object-fit: contain;">
                        <div class="text-center px-3 flex-grow-1">
                            <h5 class="fw-bold m-0 text-dark">LEMBAR BUKU INDUK SISWA</h5>
                            <h6 class="fw-bold m-0 mt-1 text-uppercase text-secondary"><?= esc($settings['school_name'] ?? 'SEKOLAH') ?></h6>
                            <p class="m-0 mt-1 text-muted small"><?= $fullAddress ?></p>
                        </div>
                        <img src="<?= $logoSekolah ?>" style="height: 60px; object-fit: contain;">
                    </div>

                    <div class="row g-4">
                        <!-- Kolom Kiri: Biodata Pribadi -->
                        <div class="col-lg-8">
                            <h6 class="fw-bold border-bottom pb-2 text-primary text-uppercase mb-3">
                                <i class="bi bi-person-vcard me-2"></i>A. Keterangan Pribadi Siswa
                            </h6>
                            <table class="table table-sm table-borderless align-middle mb-4" style="font-size: 14px;">
                                <tr>
                                    <td width="35%" class="text-muted">1. Nama Lengkap</td>
                                    <td width="3%">:</td>
                                    <td class="fw-bold text-dark"><?= esc($student['full_name']) ?></td>
                                </tr>
                                <tr>
                                    <td class="text-muted">2. Nomor Induk Siswa (NIS)</td>
                                    <td>:</td>
                                    <td class="fw-bold"><?= esc($student['nis'] ?? '-') ?></td>
                                </tr>
                                <tr>
                                    <td class="text-muted">3. NISN</td>
                                    <td>:</td>
                                    <td><?= esc($student['nisn'] ?? '-') ?></td>
                                </tr>
                                <tr>
                                    <td class="text-muted">4. NIK (No. KTP)</td>
                                    <td>:</td>
                                    <td><?= esc($student['nik'] ?? '-') ?></td>
                                </tr>
                                <tr>
                                    <td class="text-muted">5. Jenis Kelamin</td>
                                    <td>:</td>
                                    <td><?= $student['gender'] === 'L' ? 'Laki-laki' : 'Perempuan' ?></td>
                                </tr>
                                <tr>
                                    <td class="text-muted">6. Tempat & Tanggal Lahir</td>
                                    <td>:</td>
                                    <td><?= esc($student['birth_place'] ?? '-') ?>, <?= esc($student['birth_date'] ?? '-') ?></td>
                                </tr>
                                <tr>
                                    <td class="text-muted">7. Agama</td>
                                    <td>:</td>
                                    <td><?= esc($student['religion'] ?? '-') ?></td>
                                </tr>
                                <tr>
                                    <td class="text-muted">8. Nomor KIP (jika ada)</td>
                                    <td>:</td>
                                    <td><?= esc($student['kip_no'] ?? '-') ?></td>
                                </tr>
                            </table>

                            <h6 class="fw-bold border-bottom pb-2 text-primary text-uppercase mb-3">
                                <i class="bi bi-geo-alt me-2"></i>B. Keterangan Tempat Tinggal
                            </h6>
                            <table class="table table-sm table-borderless align-middle mb-4" style="font-size: 14px;">
                                <tr>
                                    <td width="35%" class="text-muted">1. Alamat Lengkap</td>
                                    <td width="3%">:</td>
                                    <td><?= esc($student['address'] ?? '-') ?></td>
                                </tr>
                                <tr>
                                    <td class="text-muted">2. RT / RW</td>
                                    <td>:</td>
                                    <td>RT <?= esc($student['rt'] ?? '-') ?> / RW <?= esc($student['rw'] ?? '-') ?></td>
                                </tr>
                                <tr>
                                    <td class="text-muted">3. Kelurahan / Desa</td>
                                    <td>:</td>
                                    <td><?= esc($student['village'] ?? '-') ?></td>
                                </tr>
                                <tr>
                                    <td class="text-muted">4. Kecamatan</td>
                                    <td>:</td>
                                    <td><?= esc($student['district'] ?? '-') ?></td>
                                </tr>
                                <tr>
                                    <td class="text-muted">5. Kota / Kabupaten</td>
                                    <td>:</td>
                                    <td><?= esc($student['city'] ?? '-') ?></td>
                                </tr>
                                <tr>
                                    <td class="text-muted">6. Provinsi</td>
                                    <td>:</td>
                                    <td><?= esc($student['province'] ?? '-') ?></td>
                                </tr>
                                <tr>
                                    <td class="text-muted">7. Kode Pos / HP</td>
                                    <td>:</td>
                                    <td><?= esc($student['postal_code'] ?? '-') ?> / <?= esc($student['phone'] ?? '-') ?></td>
                                </tr>
                            </table>
                        </div>

                        <!-- Kolom Kanan: Pas Foto & Pendaftaran -->
                        <div class="col-lg-4 text-center border-start ps-lg-4">
                            <div class="mb-4">
                                <span class="d-block small fw-bold text-muted mb-2">PAS FOTO 3X4 SISWA</span>
                                <?php if (!empty($student['photo'])): ?>
                                    <img src="<?= \App\Services\StorageService::getUrl($student['photo'], 'students') ?>" class="img-thumbnail" style="width: 3.5cm; height: 4.5cm; object-fit: cover;">
                                <?php else: ?>
                                    <div class="d-flex align-items-center justify-content-center border border-secondary border-dashed mx-auto bg-light text-muted" style="width: 3.5cm; height: 4.5cm;">
                                        <div class="small">Belum Ada<br>Foto</div>
                                    </div>
                                <?php endif; ?>
                            </div>

                            <div class="card bg-light border-0 text-start p-3" style="font-size: 13px;">
                                <div class="fw-bold text-uppercase border-bottom pb-1 mb-2 text-dark">
                                    <i class="bi bi-box-arrow-in-right me-1 text-primary"></i>C. Pendaftaran & 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-2">
                                <div class="mb-1"><strong>Status:</strong> 
                                    <?php
                                    $badge = 'secondary';
                                    if ($student['status'] === 'Aktif') $badge = 'success';
                                    elseif ($student['status'] === 'Alumni') $badge = 'primary';
                                    elseif ($student['status'] === 'Mutasi') $badge = 'warning';
                                    ?>
                                    <span class="badge bg-<?= $badge ?>"><?= esc($student['status']) ?></span>
                                </div>
                                <div class="mb-1"><strong>Tgl Mutasi/Lulus:</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>

                    <!-- Row Bawah: Orang Tua Kandung -->
                    <div class="row g-4 mt-2">
                        <div class="col-12">
                            <h6 class="fw-bold border-bottom pb-2 text-primary text-uppercase mb-3">
                                <i class="bi bi-people-fill me-2"></i>D. Keterangan Orang Tua Kandung
                            </h6>
                            <div class="row g-3">
                                <div class="col-md-6">
                                    <div class="card p-3 border-light bg-light-subtle">
                                        <div class="fw-bold text-center border-bottom pb-2 mb-3 text-secondary text-uppercase">Data Ayah Kandung</div>
                                        <table class="table table-sm table-borderless mb-0" style="font-size: 13px;">
                                            <tr>
                                                <td width="35%" class="text-muted">Nama Lengkap</td>
                                                <td width="3%">:</td>
                                                <td class="fw-bold"><?= esc($student['father_name'] ?? '-') ?></td>
                                            </tr>
                                            <tr>
                                                <td class="text-muted">NIK Ayah</td>
                                                <td>:</td>
                                                <td><?= esc($student['father_nik'] ?? '-') ?></td>
                                            </tr>
                                            <tr>
                                                <td class="text-muted">Tempat, Tgl Lahir</td>
                                                <td>:</td>
                                                <td><?= esc($student['father_birth_place'] ?? '-') ?>, <?= esc($student['father_birth'] ?? '-') ?></td>
                                            </tr>
                                            <tr>
                                                <td class="text-muted">Pendidikan</td>
                                                <td>:</td>
                                                <td><?= esc($student['father_edu'] ?? '-') ?></td>
                                            </tr>
                                            <tr>
                                                <td class="text-muted">Pekerjaan</td>
                                                <td>:</td>
                                                <td><?= esc($student['father_job'] ?? '-') ?></td>
                                            </tr>
                                            <tr>
                                                <td class="text-muted">No. Telepon</td>
                                                <td>:</td>
                                                <td><?= esc($student['father_phone'] ?? '-') ?></td>
                                            </tr>
                                        </table>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="card p-3 border-light bg-light-subtle">
                                        <div class="fw-bold text-center border-bottom pb-2 mb-3 text-secondary text-uppercase">Data Ibu Kandung</div>
                                        <table class="table table-sm table-borderless mb-0" style="font-size: 13px;">
                                            <tr>
                                                <td width="35%" class="text-muted">Nama Lengkap</td>
                                                <td width="3%">:</td>
                                                <td class="fw-bold"><?= esc($student['mother_name'] ?? '-') ?></td>
                                            </tr>
                                            <tr>
                                                <td class="text-muted">NIK Ibu</td>
                                                <td>:</td>
                                                <td><?= esc($student['mother_nik'] ?? '-') ?></td>
                                            </tr>
                                            <tr>
                                                <td class="text-muted">Tempat, Tgl Lahir</td>
                                                <td>:</td>
                                                <td><?= esc($student['mother_birth_place'] ?? '-') ?>, <?= esc($student['mother_birth'] ?? '-') ?></td>
                                            </tr>
                                            <tr>
                                                <td class="text-muted">Pendidikan</td>
                                                <td>:</td>
                                                <td><?= esc($student['mother_edu'] ?? '-') ?></td>
                                            </tr>
                                            <tr>
                                                <td class="text-muted">Pekerjaan</td>
                                                <td>:</td>
                                                <td><?= esc($student['mother_job'] ?? '-') ?></td>
                                            </tr>
                                            <tr>
                                                <td class="text-muted">No. Telepon</td>
                                                <td>:</td>
                                                <td><?= esc($student['mother_phone'] ?? '-') ?></td>
                                            </tr>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Row Bawah: Riwayat Kelas -->
                    <div class="row g-4 mt-2">
                        <div class="col-12">
                            <h6 class="fw-bold border-bottom pb-2 text-primary text-uppercase mb-3">
                                <i class="bi bi-clock-history me-2"></i>E. Riwayat Rombongan Belajar (Kelas)
                            </h6>
                            <table class="table table-sm table-bordered text-center align-middle" style="font-size: 13px;">
                                <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-3">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>
                                                    <span class="badge bg-<?= $h['status'] === 'Naik' ? 'success' : ($h['status'] === 'Tinggal' ? 'danger' : 'primary') ?>">
                                                        <?= esc($h['status']) ?>
                                                    </span>
                                                </td>
                                                <td><?= esc($h['notes'] ?? '-') ?></td>
                                            </tr>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <!-- ========================================== -->
                <!-- TAB 2: REKAP NILAI AKADEMIK                -->
                <!-- ========================================== -->
                <div class="tab-pane fade" id="nilai-pane" role="tabpanel" aria-labelledby="nilai-tab">
                    <!-- KOP Halaman Nilai -->
                    <div class="d-flex align-items-center justify-content-between border-bottom pb-3 mb-3">
                        <img src="<?= $logoKemenag ?>" style="height: 60px; object-fit: contain;">
                        <div class="text-center px-3 flex-grow-1">
                            <h5 class="fw-bold m-0 text-dark">LEMBAR HASIL BELAJAR SISWA (LEGER)</h5>
                            <h6 class="fw-bold m-0 mt-1 text-uppercase text-secondary"><?= esc($settings['school_name'] ?? 'SEKOLAH') ?></h6>
                            <p class="m-0 mt-1 text-muted small"><?= $fullAddress ?></p>
                        </div>
                        <img src="<?= $logoSekolah ?>" style="height: 60px; object-fit: contain;">
                    </div>

                    <!-- Identitas Siswa di bawah Kop -->
                    <div class="card p-3 bg-light border-0 mb-3" style="font-size: 13px;">
                        <div class="row g-2">
                            <div class="col-md-6">
                                <div class="mb-1"><strong>Nama Siswa:</strong> <?= esc($student['full_name']) ?></div>
                                <div class="mb-1"><strong>Nomor Induk Siswa (NIS):</strong> <?= esc($student['nis'] ?? '-') ?></div>
                                <div class="mb-1"><strong>NISN:</strong> <?= esc($student['nisn'] ?? '-') ?></div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-1"><strong>Tempat, Tgl Lahir:</strong> <?= esc($student['birth_place'] ?? '-') ?>, <?= esc($student['birth_date'] ?? '-') ?></div>
                                <div class="mb-1"><strong>Jenis Kelamin:</strong> <?= $student['gender'] === 'L' ? 'Laki-laki' : 'Perempuan' ?></div>
                            </div>
                        </div>
                    </div>

                    <h6 class="fw-bold border-bottom pb-2 text-primary text-uppercase mb-3">
                        <i class="bi bi-bar-chart-steps me-2"></i>F. Rekapitulasi Nilai Akademik per Semester
                    </h6>

                    <?php if (empty($subjects)): ?>
                        <div class="text-center py-5">
                            <div class="text-muted mb-3" style="font-size: 3rem;">
                                <i class="bi bi-folder-x"></i>
                            </div>
                            <h5 class="text-secondary fw-semibold">Tidak Ada Data Nilai</h5>
                            <p class="text-muted small">Data nilai legger untuk siswa ini belum diimpor atau belum diisi dalam sistem.</p>
                        </div>
                    <?php else: ?>
                        <div class="table-responsive">
                            <table class="table table-bordered table-hover align-middle text-center" style="font-size: 13px;">
                                <thead class="table-light">
                                    <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 
                                    $no = 1;
                                    $sumSmt = array_fill(1, 6, 0);
                                    $countSmt = array_fill(1, 6, 0);

                                    foreach ($subjects as $groupName => $groupSubs): 
                                    ?>
                                        <!-- Header Kelompok Mapel (Dinamis menyesuaikan SD/MI, SMP/MTs, SMA/MA) -->
                                        <tr class="table-light text-start fw-bold">
                                            <td colspan="9" class="ps-3 text-secondary text-uppercase"><?= 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 class="fw-semibold"><?= $no++ ?></td>
                                                <td class="text-start fw-medium text-dark"><?= 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-subtle text-primary"><?= $avg ?></td>
                                            </tr>
                                        <?php endforeach; ?>
                                    <?php endforeach; ?>
                                </tbody>
                                <tfoot class="table-light fw-bold" style="border-top: 2px solid #333;">
                                    <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-subtle">-</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>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>

            </div>
        </div>
    </div>
</div>

<?= $this->endSection() ?>
