<?php
if (session_status() === PHP_SESSION_NONE) { session_start(); }
require_once('../koneksi.php');
require_once('../auth.php');
cekAdminAtauGuru();
// Ambil ID Semester yang sedang aktif
$q_sem_aktif = mysqli_query($koneksi, "SELECT id_semester FROM semester WHERE status = 'Aktif' LIMIT 1");
$sem_aktif = mysqli_fetch_array($q_sem_aktif);
$id_sem_aktif = $sem_aktif['id_semester'];

// Ambil Tahun Pelajaran yang sedang aktif
$q_tp_aktif = mysqli_query($koneksi, "SELECT id_tp_tahun FROM tahun_pelajaran WHERE status = 'Aktif' LIMIT 1");
$tp_aktif = mysqli_fetch_array($q_tp_aktif);
$id_tp_aktif = $tp_aktif['id_tp_tahun'];

// 1. Ambil Data Utama
$id_guru = mysqli_fetch_array(mysqli_query($koneksi, "SELECT id_guru FROM users WHERE id_user = '{$_SESSION['id_user']}'"))['id_guru'];
$wali = mysqli_fetch_array(mysqli_query($koneksi, "SELECT id_rombel, kelas FROM rombel WHERE wali_kelas = '$id_guru'"));
$id_rombel = $wali['id_rombel'];

// 2. Ambil Profil & Data Guru
$profil = mysqli_fetch_array(mysqli_query($koneksi, "SELECT kepala_sekolah, nip_kepala FROM profil_sekolah LIMIT 1"));
$guru = mysqli_fetch_array(mysqli_query($koneksi, "SELECT nama, nip FROM master_guru WHERE id_guru = '$id_guru'"));

// 3. Ambil Mapel & Siswa
$mapel = mysqli_fetch_all(mysqli_query($koneksi, "
    SELECT DISTINCT m.id_mapel, m.nama_mapel 
    FROM master_mapel m 
    JOIN tugas_guru tg ON m.id_mapel = tg.id_mapel 
    WHERE tg.id_semester = '$id_sem_aktif' 
    AND tg.id_tp_tahun = '$id_tp_aktif' 
    ORDER BY m.kelompok ASC, m.urutan ASC
"), MYSQLI_ASSOC);

$siswa = mysqli_query($koneksi, "SELECT s.id_siswa, s.nama FROM master_siswa s JOIN anggota_rombel ar ON s.id_siswa = ar.id_siswa WHERE ar.id_rombel = '$id_rombel' AND ar.id_semester = '$id_sem_aktif' AND ar.id_tp_tahun = '$id_tp_aktif' ORDER BY s.nama ASC");
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <title>Leger Nilai - <?= $wali['kelas'] ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body { font-family: 'Arial', sans-serif; padding: 20px; }
        
        @media print {
            @page { size: portrait; margin: 0.5cm; }
            .btn-print { display: none; }
        }

        /* Tabel Utama */
        .table { width: 100%; table-layout: fixed; border-collapse: collapse; }
        .table th, .table td { border: 1px solid #000; padding: 4px; font-size: 10px; }
        .table th { text-align: center; vertical-align: middle; }
        
        /* Header Vertikal */
        .rotate-text { height: 120px; vertical-align: bottom; padding-bottom: 5px; }
        .rotate-text span {
            writing-mode: vertical-rl;
            transform: rotate(180deg);
            display: inline-block;
            white-space: normal;
            text-align: left;
            line-height: 1.2;
            font-weight: bold;
        }

        /* Perataan */
        .col-nama { width: 180px; }
        .col-no { width: 30px; }
        .text-left { text-align: left !important; }
        .text-center { text-align: center !important; }

        /* Tanda Tangan */
        .ttd-table { width: 100%; margin-top: 30px; border: none !important; }
        .ttd-table td { border: none !important; text-align: center; width: 50%; padding: 10px; }
    </style>
</head>
<body onload="window.print()">

    <div class="text-center mb-3">
        <h4>LEGER NILAI SISWA</h4>
        <h5>KELAS: <?= $wali['kelas'] ?></h5>
    </div>

    <table class="table">
        <thead class="table-light">
            <tr>
                <th class="col-no">No</th>
                <th class="col-nama">Nama Siswa</th>
                <?php foreach($mapel as $m) { ?>
                    <th class="rotate-text"><span><?= $m['nama_mapel'] ?></span></th>
                <?php } ?>
                <th class="rotate-text"><span>Rata-rata</span></th>
            </tr>
        </thead>
<tbody>
            <?php 
            $no = 1;
            while($s = mysqli_fetch_array($siswa)) {
                echo "<tr>
                    <td class='text-center'>{$no}</td>
                    <td class='text-left'>{$s['nama']}</td>";
                
                $total = 0; $cnt = 0;
                foreach($mapel as $m) {
                    $r = mysqli_fetch_array(mysqli_query($koneksi, "
                        SELECT AVG(nilai_rapor) as rata 
                        FROM nilai_siswa ns 
                        JOIN tugas_guru tg ON ns.id_tugas = tg.id_tugas 
                        WHERE ns.id_siswa='{$s['id_siswa']}' 
                        AND tg.id_mapel='{$m['id_mapel']}' 
                        AND tg.id_semester = '$id_sem_aktif' 
                        AND tg.id_tp_tahun = '$id_tp_aktif'
                    "));
                    
                    echo "<td class='text-center'>".($r['rata'] ? number_format($r['rata'], 0) : "-")."</td>";
                    
                    if($r['rata']) { 
                        $total += $r['rata']; 
                        $cnt++; 
                    }
                }
                
                // Menutup baris dan kolom rata-rata
                echo "<td class='text-center fw-bold'>".($cnt > 0 ? number_format($total/$cnt, 1) : "-")."</td></tr>";
                
                $no++;
            } // INI ADALAH PENUTUP WHILE YANG HILANG
            ?>
        </tbody>
    </table>

    <table class="ttd-table">
        <tr>
            <td>
                Mengetahui,<br>Kepala Sekolah
                <br><br><br><br>
                <b><u><?= $profil['kepala_sekolah'] ?></u></b><br>
                NIP. <?= $profil['nip_kepala'] ?>
            </td>
            <td>
                <?= date('d F Y') ?>,<br>Guru Kelas
                <br><br><br><br>
                <b><u><?= $guru['nama'] ?? '-' ?></u></b><br>
                NIP. <?= $guru['nip'] ?? '-' ?>
            </td>
        </tr>
    </table>

    <button class="btn btn-secondary btn-print mt-3" onclick="window.history.back()">Kembali</button>
</body>
</html>