<?php
session_start();
require_once '../koneksi.php';
require_once '../auth.php';
cekAdminAtauGuru();
function tentukanFase($nama_kelas) {
    if (strpos($nama_kelas, '1') !== false || strpos($nama_kelas, '2') !== false) return 'A';
    if (strpos($nama_kelas, '3') !== false || strpos($nama_kelas, '4') !== false) return 'B';
    return 'C';
}
$id_siswa = $_GET['id_siswa'] ?? die("Data siswa tidak ditemukan.");

// 1. AMBIL PERIODE & TP
$q_aktif = mysqli_query($koneksi, "SELECT * FROM semester WHERE status = 'Aktif' LIMIT 1");
$aktif = mysqli_fetch_assoc($q_aktif);
$id_sem = $aktif['id_semester'] ?? 0;
$tp_data = mysqli_fetch_assoc(mysqli_query($koneksi, "SELECT tahun_pelajaran FROM tahun_pelajaran WHERE status = 'Aktif' LIMIT 1"));

// 2. QUERY DATA SISWA
$sql_siswa = "SELECT s.nama, s.nisn, s.nis, r.kelas, r.id_rombel 
              FROM master_siswa s 
              JOIN anggota_rombel ar ON s.id_siswa = ar.id_siswa 
              JOIN rombel r ON ar.id_rombel = r.id_rombel 
              WHERE s.id_siswa = '$id_siswa' AND ar.id_semester = '$id_sem' 
              LIMIT 1"; 
$s = mysqli_fetch_array(mysqli_query($koneksi, $sql_siswa));

// 3. QUERY ABSENSI (CARA AMAN)
$q_abs = mysqli_query($koneksi, "SELECT sakit, izin FROM absensi WHERE id_siswa = '$id_siswa' AND id_semester = '$id_sem' AND tanggal = '9999-12-31' LIMIT 1");
$abs = mysqli_fetch_assoc($q_abs);

// Berikan nilai default jika $abs null
$val_sakit = $abs['sakit'] ?? 0;
$val_izin  = $abs['izin'] ?? 0;
$val_alfa  = 0;

$check = mysqli_query($koneksi, "SHOW COLUMNS FROM absensi");
while($col = mysqli_fetch_array($check)) {
    if($col['Field'] == 'alfa' || $col['Field'] == 'alpha') {
        $nm = $col['Field'];
        $res = mysqli_fetch_array(mysqli_query($koneksi, "SELECT $nm FROM absensi WHERE id_siswa = '$id_siswa' AND id_semester = '$id_sem' AND tanggal = '9999-12-31' LIMIT 1"));
        $val_alfa = $res[$nm] ?? 0;
        break; 
    }
}

// 4. QUERY CATATAN WALI (DARI TABEL 'catatan_siswa')
$catatan_wali = '-';
$cat_q = mysqli_query($koneksi, "SELECT deskripsi FROM catatan_siswa WHERE id_siswa = '$id_siswa' AND id_semester = '$id_sem' LIMIT 1");
if ($cat_q && mysqli_num_rows($cat_q) > 0) {
    $data_cat = mysqli_fetch_assoc($cat_q);
    $catatan_wali = $data_cat['deskripsi'];
}

// 5. DATA GURU, PROFIL, EKSKUL
$profil = mysqli_fetch_assoc(mysqli_query($koneksi, "SELECT kepala_sekolah, nip_kepala FROM profil_semester WHERE id_semester = '$id_sem' LIMIT 1"));
$data_sekolah = mysqli_fetch_assoc(mysqli_query($koneksi, "SELECT nama_sekolah FROM profil_sekolah LIMIT 1")) ?? ['nama_sekolah' => 'N/A'];
$id_rombel_siswa = $s['id_rombel'] ?? 0;

$q_guru = mysqli_query($koneksi, "SELECT g.nama, g.nip 
                                  FROM master_guru g 
                                  JOIN rombel r ON g.id_guru = r.wali_kelas 
                                  WHERE r.id_rombel = '$id_rombel_siswa' LIMIT 1");
$guru = mysqli_fetch_array($q_guru) ?? ['nama' => '-', 'nip' => '-'];

$q_ekskul = mysqli_query($koneksi, "SELECT e.nama_ekskul, ne.predikat, ne.deskripsi FROM nilai_ekskul ne JOIN ekstrakurikuler e ON ne.id_ekskul = e.id_ekskul WHERE ne.id_siswa = '$id_siswa'");
$q_ekskul = mysqli_query($koneksi, "SELECT e.nama_ekskul, ne.predikat, ne.deskripsi FROM nilai_ekskul ne JOIN ekstrakurikuler e ON ne.id_ekskul = e.id_ekskul WHERE ne.id_siswa = '$id_siswa'");

function getDeskripsiCetak($koneksi, $id_siswa, $id_mapel, $nama_siswa) {
    $query = "SELECT tp.deskripsi_tp, ns.nilai FROM nilai_siswa ns JOIN tugas_guru tg ON ns.id_tugas = tg.id_tugas JOIN tujuan_pembelajaran tp ON ns.id_tp = tp.id WHERE ns.id_siswa = '$id_siswa' AND tg.id_mapel = '$id_mapel' AND ns.nilai > 0 ORDER BY ns.nilai DESC";
    $result = mysqli_query($koneksi, $query);
    $data = mysqli_fetch_all($result, MYSQLI_ASSOC);
    if (empty($data)) return "Data capaian belum tersedia.";
    $deskripsi = "Ananda " . htmlspecialchars($nama_siswa) . " sangat menguasai dalam " . $data[0]['deskripsi_tp'] . ", ";
    if (count($data) > 1) $deskripsi .= "namun perlu bimbingan dalam " . end($data)['deskripsi_tp'] . ".";
    return $deskripsi;
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <title>Rapor <?= htmlspecialchars($s['nama'] ?? 'Siswa') ?></title>
    <style>
        body { font-family: Arial, sans-serif; font-size: 11pt; }
        .rapor-container { width: 19cm; margin: auto; padding: 1cm; }
        .header-title { text-align: center; font-weight: bold; font-size: 14pt; margin-bottom: 20px; }
        .border { width: 100%; border-collapse: collapse; margin-top: 10px; }
        .border th, .border td { border: 1px solid #000; padding: 6px; }
        .box { border: 1px solid #000; padding: 10px; margin-top: 15px; }
        .ttd-table { width: 100%; margin-top: 30px; text-align: center; }
    </style>
</head>
<body onload="window.print()">
    <div class="rapor-container">
        <div class="header-title">LAPORAN HASIL BELAJAR (RAPOR)</div>
        <table style="width:100%; margin-bottom:20px;">
            <tr><td>Nama Peserta Didik</td><td>: <b><?= strtoupper(htmlspecialchars($s['nama'] ?? '-')) ?></b></td><td>Kelas</td><td>: <b><?= htmlspecialchars($s['kelas'] ?? '-') ?></b></td></tr>
            <tr><td>NISN / NIS</td><td>: <?= htmlspecialchars($s['nisn'] ?? '-') ?> / <?= htmlspecialchars($s['nis'] ?? '-') ?></td><td>Fase</td><td>: <b><?= tentukanFase($s['kelas'] ?? '') ?></b></td></tr>
            <tr><td>Sekolah</td><td>: <?= htmlspecialchars($data_sekolah['nama_sekolah']) ?></td><td>Semester / Tahun</td><td>: <b><?= htmlspecialchars($aktif['nama_semester'] ?? '-') ?> / <?= htmlspecialchars($tp_data['tahun_pelajaran'] ?? '-') ?></b></td></tr>
        </table>
        <table class="border">
            <thead><tr><th width="5%">No</th><th width="30%">Mata Pelajaran</th><th width="10%">Nilai</th><th>Capaian Kompetensi</th></tr></thead>
            <tbody>
            <?php
            foreach(["Wajib", "Mulok"] as $k) {
                echo "<tr><td colspan='4' style='background:#eee; font-weight:bold;'>KELOMPOK $k</td></tr>";
                $q_mapel = mysqli_query($koneksi, "SELECT id_mapel, nama_mapel FROM master_mapel WHERE kelompok = '$k' ORDER BY urutan ASC");
                $no = 1;
                while($m = mysqli_fetch_array($q_mapel)) {
                    $n = mysqli_fetch_assoc(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 = '$id_siswa' AND tg.id_mapel = '{$m['id_mapel']}' AND ns.nilai_rapor > 0"));
                    if($n['rata'] > 0) {
                        echo "<tr><td style='text-align:center;'>$no</td><td>{$m['nama_mapel']}</td><td style='text-align:center;'>" . number_format($n['rata'], 0) . "</td><td>" . getDeskripsiCetak($koneksi, $id_siswa, $m['id_mapel'], $s['nama']) . "</td></tr>";
                        $no++;
                    }
                }
            }
            ?>
            </tbody>
        </table>
        <h5>Ketidakhadiran</h5>
        <table class="border" style="width:300px;">
            <tr><td>Sakit</td><td>: <?= $abs['sakit'] ?? 0 ?> hari</td></tr>
            <tr><td>Izin</td><td>: <?= $abs['izin'] ?? 0 ?> hari</td></tr>
            <tr><td>Tanpa Keterangan</td><td>: <?= $val_alfa ?> hari</td></tr>
        </table>
        <h5>Kegiatan Ekstrakurikuler</h5>
        <table class="border">
            <thead><tr><th>No</th><th>Kegiatan</th><th>Predikat</th><th>Keterangan</th></tr></thead>
            <tbody>
            <?php $no_eks = 1; while($e = mysqli_fetch_array($q_ekskul)) { echo "<tr><td style='text-align:center;'>$no_eks</td><td>{$e['nama_ekskul']}</td><td style='text-align:center;'>{$e['predikat']}</td><td>{$e['deskripsi']}</td></tr>"; $no_eks++; } ?>
            </tbody>
        </table>
        <div class="box"><b>CATATAN WALI:</b><br><?= nl2br(htmlspecialchars($catatan_wali)) ?></div>
        <table class="ttd-table">
            <tr>
                <td>Orang Tua<br><br><br><br>( .................... )</td>
                <td>Kepala Sekolah<br><br><br><b><u><?= htmlspecialchars($profil['kepala_sekolah'] ?? '-') ?></u></b><br>NIP. <?= htmlspecialchars($profil['nip_kepala'] ?? '-') ?></td>
                <td>Guru Kelas<br><br><br><b><u><?= htmlspecialchars($guru['nama'] ?? '-') ?></u></b><br>NIP. <?= htmlspecialchars($guru['nip'] ?? '-') ?></td>
            </tr>
        </table>
    </div>
</body>
</html>