<?php
session_start();
if (!isset($_SESSION['username']) || !in_array($_SESSION['role'], ['admin', 'guru', 'wali_kelas'])) {
    header("Location: index.php");
    exit;
}

// Sertakan file FPDF dari folder fpdf
require_once('fpdf/fpdf.php');

// Koneksi database
include 'config.php';

// Ambil data wali kelas yang login
$username = $_SESSION['username'];

// Ambil data wali kelas
$qWaliKelas = mysqli_query($conn, "SELECT id, kelas, nama_wali FROM wali_kelas WHERE nip_wali='$username' LIMIT 1");
if (!$qWaliKelas || mysqli_num_rows($qWaliKelas) === 0) {
    die("Data wali kelas tidak ditemukan.");
}
$wali_kelas = mysqli_fetch_assoc($qWaliKelas);
$kelas_diampu = $wali_kelas['kelas'];
$wali_kelas_id = $wali_kelas['id'];
$nama_wali = $wali_kelas['nama_wali'];

// Ambil parameter filter
$siswa_id = isset($_GET['siswa_id']) ? intval($_GET['siswa_id']) : 0;
$status = isset($_GET['status']) ? $_GET['status'] : '';
$dari_tanggal = isset($_GET['dari_tanggal']) ? $_GET['dari_tanggal'] : '';
$sampai_tanggal = isset($_GET['sampai_tanggal']) ? $_GET['sampai_tanggal'] : '';

// Ambil nama sekolah dan kepala sekolah
$profil = mysqli_fetch_assoc(mysqli_query($conn, "SELECT nama_sekolah, kepala_sekolah, nip_kepala FROM profil_sekolah LIMIT 1"));
$nama_sekolah = $profil['nama_sekolah'] ?? 'Nama Sekolah';
$kepala_sekolah = $profil['kepala_sekolah'] ?? '....................................';
$nip_kepala = $profil['nip_kepala'] ?? '........................';

// Ambil data siswa jika filter siswa dipilih
$siswa_terpilih = null;
if ($siswa_id > 0) {
    $qSiswa = mysqli_query($conn, "SELECT nama, nis, nisn FROM siswa WHERE id = $siswa_id");
    $siswa_terpilih = mysqli_fetch_assoc($qSiswa);
}

// Bangun query untuk mengambil riwayat pelanggaran
$query = "
    SELECT 
        p.*, 
        s.nama as siswa_nama, 
        s.nis, 
        s.nisn,
        g.nama as guru_nama,
        wk.nama_wali as wali_nama
    FROM pelanggaran p 
    JOIN siswa s ON p.siswa_id = s.id 
    LEFT JOIN guru g ON p.guru_id = g.id
    LEFT JOIN wali_kelas wk ON p.wali_kelas_id = wk.id
    WHERE s.kelas = '$kelas_diampu'";

if ($siswa_id > 0) {
    $query .= " AND p.siswa_id = $siswa_id";
}

if (!empty($status)) {
    $query .= " AND p.status = '$status'";
}

if (!empty($dari_tanggal)) {
    $query .= " AND p.tanggal >= '$dari_tanggal'";
}

if (!empty($sampai_tanggal)) {
    $query .= " AND p.tanggal <= '$sampai_tanggal'";
}

$query .= " ORDER BY p.tanggal DESC, p.created_at DESC";

$result = mysqli_query($conn, $query);
$pelanggaran_list = [];
while ($row = mysqli_fetch_assoc($result)) {
    $pelanggaran_list[] = $row;
}

// Hitung statistik
$total = count($pelanggaran_list);
$aktif = 0;
$selesai = 0;
$berat = 0;
$sedang = 0;
$ringan = 0;
$total_poin = 0;

foreach ($pelanggaran_list as $p) {
    if ($p['status'] == 'Aktif') $aktif++;
    else $selesai++;
    
    if ($p['poin'] >= 50) $berat++;
    elseif ($p['poin'] >= 25) $sedang++;
    else $ringan++;
    
    $total_poin += $p['poin'];
}

// Format tanggal untuk judul
$tanggal_cetak = date('d F Y');

// Buat teks filter
$filter_text = "Kelas: $kelas_diampu";
if ($siswa_terpilih) {
    $filter_text .= " | Siswa: " . $siswa_terpilih['nama'];
}
if (!empty($status)) {
    $filter_text .= " | Status: $status";
}
if (!empty($dari_tanggal)) {
    $filter_text .= " | Dari: " . date('d/m/Y', strtotime($dari_tanggal));
}
if (!empty($sampai_tanggal)) {
    $filter_text .= " | Sampai: " . date('d/m/Y', strtotime($sampai_tanggal));
}

// Buat PDF Portrait A4
class PDF extends FPDF
{
    function Header()
    {
        global $nama_sekolah, $kelas_diampu, $filter_text, $tanggal_cetak;
        
        // Kop Surat
        $this->SetFont('Times', 'B', 16);
        $this->Cell(0, 8, $nama_sekolah, 0, 1, 'C');
        $this->SetFont('Times', 'B', 14);
        $this->Cell(0, 8, 'RIWAYAT PELANGGARAN SISWA', 0, 1, 'C');
        $this->SetFont('Times', '', 11);
        $this->Cell(0, 6, 'Kelas: ' . $kelas_diampu, 0, 1, 'C');
        
        // Filter info
        $this->SetFont('Times', 'I', 10);
        $this->Cell(0, 6, $filter_text, 0, 1, 'C');
        
        $this->SetFont('Times', '', 10);
        $this->Cell(0, 6, 'Tanggal Cetak: ' . $tanggal_cetak, 0, 1, 'C');
        
        // Garis
        $this->Line(10, $this->GetY() + 2, 200, $this->GetY() + 2);
        $this->Ln(8);
    }

    function Footer()
    {
        $this->SetY(-15);
        $this->SetFont('Times', 'I', 8);
        $this->Cell(0, 10, 'Halaman ' . $this->PageNo() . ' / {nb}', 0, 0, 'C');
    }
    
    function FancyTable($header, $data, $w)
    {
        // Header
        $this->SetFont('Times', 'B', 9);
        $this->SetFillColor(220, 220, 220);
        for($i = 0; $i < count($header); $i++) {
            $this->Cell($w[$i], 7, $header[$i], 1, 0, 'C', true);
        }
        $this->Ln();
        
        // Data
        $this->SetFont('Times', '', 8);
        $fill = false;
        $no = 1;
        
        if (empty($data)) {
            $this->Cell(array_sum($w), 7, 'TIDAK ADA DATA', 1, 1, 'C', $fill);
        } else {
            foreach($data as $row) {
                // Klasifikasi
                if ($row['poin'] >= 50) {
                    $klasifikasi = 'Berat';
                } elseif ($row['poin'] >= 25) {
                    $klasifikasi = 'Sedang';
                } else {
                    $klasifikasi = 'Ringan';
                }
                
                // Status
                $status = $row['status'];
                
                // Pelapor
                if ($row['guru_id']) {
                    $pelapor = 'Guru';
                } elseif ($row['wali_kelas_id']) {
                    $pelapor = 'Wali';
                } else {
                    $pelapor = '-';
                }
                
                // Dialihkan
                $dialihkan = $row['status_alihkan'] == 'ya' ? 'Ya' : 'Tidak';
                
                // Cek page break
                if ($this->GetY() > 250) {
                    $this->AddPage();
                    $this->SetFont('Times', 'B', 9);
                    $this->SetFillColor(220, 220, 220);
                    for($i = 0; $i < count($header); $i++) {
                        $this->Cell($w[$i], 7, $header[$i], 1, 0, 'C', true);
                    }
                    $this->Ln();
                    $this->SetFont('Times', '', 8);
                }
                
                $this->Cell($w[0], 6, $no++, 'LR', 0, 'C', $fill);
                $this->Cell($w[1], 6, date('d/m/Y', strtotime($row['tanggal'])), 'LR', 0, 'C', $fill);
                $this->Cell($w[2], 6, $row['nis'], 'LR', 0, 'C', $fill);
                $this->Cell($w[3], 6, substr($row['siswa_nama'], 0, 20), 'LR', 0, 'L', $fill);
                $this->Cell($w[4], 6, substr($row['jenis_pelanggaran'], 0, 20), 'LR', 0, 'L', $fill);
                $this->Cell($w[5], 6, $row['poin'], 'LR', 0, 'C', $fill);
                $this->Cell($w[6], 6, $klasifikasi, 'LR', 0, 'C', $fill);
                $this->Cell($w[7], 6, $status, 'LR', 0, 'C', $fill);
                $this->Cell($w[8], 6, $dialihkan, 'LR', 0, 'C', $fill);
                $this->Cell($w[9], 6, $pelapor, 'LR', 0, 'C', $fill);
                $this->Ln();
                $fill = !$fill;
            }
            $this->Cell(array_sum($w), 0, '', 'T');
        }
    }
    
    function StatistikRapi($total, $aktif, $selesai, $berat, $sedang, $ringan, $total_poin)
    {
        $this->SetFont('Times', 'B', 11);
        $this->Cell(0, 7, 'STATISTIK PELANGGARAN', 0, 1);
        $this->Ln(2);
        
        $this->SetFont('Times', '', 10);
        $this->Cell(50, 6, 'Total Pelanggaran:', 0, 0);
        $this->Cell(30, 6, $total, 0, 0);
        $this->Cell(20, 6, '', 0, 0);
        $this->Cell(50, 6, 'Total Poin:', 0, 0);
        $this->Cell(30, 6, $total_poin, 0, 1);
        
        $this->Cell(50, 6, 'Pelanggaran Aktif:', 0, 0);
        $this->Cell(30, 6, $aktif, 0, 0);
        $this->Cell(20, 6, '', 0, 0);
        $this->Cell(50, 6, 'Pelanggaran Selesai:', 0, 0);
        $this->Cell(30, 6, $selesai, 0, 1);
        
        $this->Cell(50, 6, 'Klasifikasi Berat:', 0, 0);
        $this->Cell(30, 6, $berat, 0, 0);
        $this->Cell(20, 6, '', 0, 0);
        $this->Cell(50, 6, 'Klasifikasi Sedang:', 0, 0);
        $this->Cell(30, 6, $sedang, 0, 1);
        
        $this->Cell(50, 6, 'Klasifikasi Ringan:', 0, 0);
        $this->Cell(30, 6, $ringan, 0, 0);
        $this->Cell(20, 6, '', 0, 0);
        $this->Cell(50, 6, 'Rata-rata Poin:', 0, 0);
        $rata2 = $total > 0 ? round($total_poin / $total, 1) : 0;
        $this->Cell(30, 6, $rata2, 0, 1);
        
        $this->Ln(5);
    }
}

// Inisialisasi PDF
$pdf = new PDF();
$pdf->AliasNbPages();
$pdf->AddPage();

// ============================================================
// STATISTIK
// ============================================================
$pdf->StatistikRapi($total, $aktif, $selesai, $berat, $sedang, $ringan, $total_poin);

// ============================================================
// TABEL DATA
// ============================================================
$pdf->SetFont('Times', 'B', 11);
$pdf->Cell(0, 7, 'DATA PELANGGARAN', 0, 1);
$pdf->Ln(2);

// Lebar kolom
$w = array(8, 18, 20, 40, 40, 10, 18, 15, 12, 12);
$header = array('No', 'Tanggal', 'NIS', 'Nama', 'Jenis', 'Poin', 'Klasifikasi', 'Status', 'Alih', 'Pelapor');

$pdf->FancyTable($header, $pelanggaran_list, $w);

$pdf->Ln(10);

// ============================================================
// TANDA TANGAN
// ============================================================
$pdf->Cell(90, 6, '', 0, 0);
$pdf->Cell(90, 6, $tanggal_cetak, 0, 1, 'C');
$pdf->Ln(5);

$pdf->Cell(90, 6, 'Mengetahui,', 0, 0);
$pdf->Cell(90, 6, 'Wali Kelas,', 0, 1, 'C');
$pdf->Ln(15);

$pdf->SetFont('Times', 'BU', 11);
$pdf->Cell(90, 6, $kepala_sekolah, 0, 0, 'L');
$pdf->Cell(90, 6, $nama_wali, 0, 1, 'C');

$pdf->SetFont('Times', '', 10);
$pdf->Cell(90, 6, 'NIP. ' . $nip_kepala, 0, 0, 'L');
$pdf->Cell(90, 6, 'NIP. ........................', 0, 1, 'C');

// ============================================================
// OUTPUT PDF
// ============================================================
$filename = "Riwayat_Pelanggaran_Kelas_" . $kelas_diampu;
if ($siswa_id > 0 && $siswa_terpilih) {
    $filename .= "_" . str_replace(' ', '_', $siswa_terpilih['nama']);
}
$filename .= "_" . date('Y-m-d') . ".pdf";

$pdf->Output('D', $filename);
?>