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

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

// Koneksi database
include 'config.php';

// Ambil parameter
$kelas = $_GET['kelas'] ?? '';
$bulan = $_GET['bulan'] ?? date('m');
$tahun = $_GET['tahun'] ?? date('Y');

// Ambil nama 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 wali kelas
$wali_nama = '....................................';
$wali_nip = '........................';
if ($kelas != '') {
    $qWali = mysqli_query($conn, "SELECT nama_wali, nip_wali FROM wali_kelas WHERE kelas = '$kelas' LIMIT 1");
    if ($w = mysqli_fetch_assoc($qWali)) {
        $wali_nama = $w['nama_wali'];
        $wali_nip = $w['nip_wali'];
    }
}

// Ambil data pelanggaran
$pelanggaran = [];
$pelanggaranQuery = "SELECT p.*, s.nis, s.nisn, s.nama, s.kelas 
                     FROM pelanggaran p 
                     JOIN siswa s ON p.siswa_id = s.id 
                     WHERE MONTH(p.tanggal) = '$bulan' 
                       AND YEAR(p.tanggal) = '$tahun'
                       AND s.status='aktif'";
if ($kelas != '') {
    $pelanggaranQuery .= " AND s.kelas = '$kelas'";
}
$pelanggaranQuery .= " ORDER BY s.kelas, s.nama, p.tanggal DESC";
$resultPelanggaran = mysqli_query($conn, $pelanggaranQuery);

// Hitung rekap pelanggaran per siswa
$rekap = [];
$totalGlobal = [
    'total_pelanggaran' => 0,
    'total_poin' => 0,
    'pelanggaran_berat' => 0,
    'pelanggaran_sedang' => 0,
    'pelanggaran_ringan' => 0
];

while ($row = mysqli_fetch_assoc($resultPelanggaran)) {
    $sid = $row['siswa_id'];
    
    if (!isset($rekap[$sid])) {
        $rekap[$sid] = [
            'nis' => $row['nis'],
            'nisn' => $row['nisn'],
            'nama' => $row['nama'],
            'kelas' => $row['kelas'],
            'jumlah_pelanggaran' => 0,
            'total_poin' => 0,
            'pelanggaran_berat' => 0,
            'pelanggaran_sedang' => 0,
            'pelanggaran_ringan' => 0,
            'status_aktif' => 0,
            'status_selesai' => 0,
            'dialihkan' => 0
        ];
    }
    
    $rekap[$sid]['jumlah_pelanggaran']++;
    $rekap[$sid]['total_poin'] += $row['poin'];
    
    // Klasifikasi berdasarkan poin
    if ($row['poin'] >= 50) {
        $rekap[$sid]['pelanggaran_berat']++;
        $totalGlobal['pelanggaran_berat']++;
    } elseif ($row['poin'] >= 25) {
        $rekap[$sid]['pelanggaran_sedang']++;
        $totalGlobal['pelanggaran_sedang']++;
    } else {
        $rekap[$sid]['pelanggaran_ringan']++;
        $totalGlobal['pelanggaran_ringan']++;
    }
    
    // Status
    if ($row['status'] == 'Aktif') {
        $rekap[$sid]['status_aktif']++;
    } else {
        $rekap[$sid]['status_selesai']++;
    }
    
    // Alihkan
    if ($row['status_alihkan'] == 'ya') {
        $rekap[$sid]['dialihkan']++;
    }
    
    $totalGlobal['total_pelanggaran']++;
    $totalGlobal['total_poin'] += $row['poin'];
}

// Hitung statistik tambahan
$rataRataPoin = $totalGlobal['total_pelanggaran'] > 0 ? round($totalGlobal['total_poin'] / $totalGlobal['total_pelanggaran'], 1) : 0;

// Ambil semua pelanggaran untuk ditampilkan di tabel detail
mysqli_data_seek($resultPelanggaran, 0);
$detailPelanggaran = [];
while ($row = mysqli_fetch_assoc($resultPelanggaran)) {
    $detailPelanggaran[] = $row;
}

// Nama bulan dalam bahasa Indonesia
$namaBulan = [
    1 => 'Januari', 2 => 'Februari', 3 => 'Maret', 4 => 'April',
    5 => 'Mei', 6 => 'Juni', 7 => 'Juli', 8 => 'Agustus',
    9 => 'September', 10 => 'Oktober', 11 => 'November', 12 => 'Desember'
];
$bulanTeks = $namaBulan[(int)$bulan];
$judulKelas = $kelas == '' ? 'Semua Kelas' : "Kelas $kelas";

// Tanggal terakhir bulan ini
$tanggal_terakhir = date("j F Y", strtotime("$tahun-$bulan-" . cal_days_in_month(CAL_GREGORIAN, $bulan, $tahun)));

// Buat PDF
class PDF extends FPDF
{
    // Header
    function Header()
    {
        global $nama_sekolah, $bulanTeks, $tahun, $judulKelas;
        
        // Logo (jika ada, bisa ditambahkan)
        // $this->Image('logo.png',10,6,30);
        
        // Judul
        $this->SetFont('Arial', 'B', 16);
        $this->Cell(0, 10, $nama_sekolah, 0, 1, 'C');
        $this->SetFont('Arial', 'B', 14);
        $this->Cell(0, 8, 'REKAP PELANGGARAN BULANAN', 0, 1, 'C');
        $this->SetFont('Arial', 'B', 12);
        $this->Cell(0, 8, "$bulanTeks $tahun", 0, 1, 'C');
        $this->SetFont('Arial', 'I', 11);
        $this->Cell(0, 8, $judulKelas, 0, 1, 'C');
        $this->Ln(5);
        
        // Garis
        $this->Line(10, $this->GetY(), 200, $this->GetY());
        $this->Ln(5);
    }

    // Footer
    function Footer()
    {
        $this->SetY(-15);
        $this->SetFont('Arial', 'I', 8);
        $this->Cell(0, 10, 'Halaman ' . $this->PageNo() . ' / {nb}', 0, 0, 'C');
    }
}

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

// ============================================================
// STATISTIK
// ============================================================
$pdf->SetFont('Arial', 'B', 12);
$pdf->Cell(0, 8, 'A. Statistik Pelanggaran', 0, 1, 'L');
$pdf->Ln(2);

$pdf->SetFont('Arial', '', 10);
$pdf->Cell(45, 7, 'Total Pelanggaran:', 0, 0);
$pdf->Cell(20, 7, $totalGlobal['total_pelanggaran'], 0, 0);
$pdf->Cell(20, 7, '', 0, 0);
$pdf->Cell(45, 7, 'Total Poin:', 0, 0);
$pdf->Cell(20, 7, $totalGlobal['total_poin'], 0, 1);

$pdf->Cell(45, 7, 'Pelanggaran Berat:', 0, 0);
$pdf->Cell(20, 7, $totalGlobal['pelanggaran_berat'], 0, 0);
$pdf->Cell(20, 7, '', 0, 0);
$pdf->Cell(45, 7, 'Pelanggaran Sedang:', 0, 0);
$pdf->Cell(20, 7, $totalGlobal['pelanggaran_sedang'], 0, 1);

$pdf->Cell(45, 7, 'Pelanggaran Ringan:', 0, 0);
$pdf->Cell(20, 7, $totalGlobal['pelanggaran_ringan'], 0, 0);
$pdf->Cell(20, 7, '', 0, 0);
$pdf->Cell(45, 7, 'Rata-rata Poin:', 0, 0);
$pdf->Cell(20, 7, $rataRataPoin, 0, 1);

$pdf->Ln(5);

// ============================================================
// REKAP PER SISWA
// ============================================================
$pdf->SetFont('Arial', 'B', 12);
$pdf->Cell(0, 8, 'B. Rekap Pelanggaran per Siswa', 0, 1, 'L');
$pdf->Ln(2);

// Header tabel
$pdf->SetFont('Arial', 'B', 9);
$pdf->SetFillColor(200, 200, 200);
$pdf->Cell(10, 7, 'No', 1, 0, 'C', true);
$pdf->Cell(25, 7, 'NIS', 1, 0, 'C', true);
$pdf->Cell(30, 7, 'NISN', 1, 0, 'C', true);
$pdf->Cell(45, 7, 'Nama Siswa', 1, 0, 'C', true);
$pdf->Cell(15, 7, 'Kelas', 1, 0, 'C', true);
$pdf->Cell(20, 7, 'Jml', 1, 0, 'C', true);
$pdf->Cell(20, 7, 'Total Poin', 1, 0, 'C', true);
$pdf->Cell(20, 7, 'Kategori', 1, 1, 'C', true);

// Data rekap
$pdf->SetFont('Arial', '', 8);
$no = 1;
foreach ($rekap as $r) {
    // Tentukan kategori siswa berdasarkan total poin
    $kategori = '';
    if ($r['total_poin'] >= 100) {
        $kategori = 'Berat';
    } elseif ($r['total_poin'] >= 50) {
        $kategori = 'Sedang';
    } else {
        $kategori = 'Ringan';
    }

    // Cek apakah perlu halaman baru
    if ($pdf->GetY() > 250) {
        $pdf->AddPage();
        // Header tabel di halaman baru
        $pdf->SetFont('Arial', 'B', 9);
        $pdf->SetFillColor(200, 200, 200);
        $pdf->Cell(10, 7, 'No', 1, 0, 'C', true);
        $pdf->Cell(25, 7, 'NIS', 1, 0, 'C', true);
        $pdf->Cell(30, 7, 'NISN', 1, 0, 'C', true);
        $pdf->Cell(45, 7, 'Nama Siswa', 1, 0, 'C', true);
        $pdf->Cell(15, 7, 'Kelas', 1, 0, 'C', true);
        $pdf->Cell(20, 7, 'Jml', 1, 0, 'C', true);
        $pdf->Cell(20, 7, 'Total Poin', 1, 0, 'C', true);
        $pdf->Cell(20, 7, 'Kategori', 1, 1, 'C', true);
    }

    $pdf->Cell(10, 6, $no++, 1, 0, 'C');
    $pdf->Cell(25, 6, $r['nis'], 1, 0, 'C');
    $pdf->Cell(30, 6, $r['nisn'], 1, 0, 'C');
    $pdf->Cell(45, 6, substr($r['nama'], 0, 25), 1, 0, 'L');
    $pdf->Cell(15, 6, $r['kelas'], 1, 0, 'C');
    $pdf->Cell(20, 6, $r['jumlah_pelanggaran'], 1, 0, 'C');
    $pdf->Cell(20, 6, $r['total_poin'], 1, 0, 'C');
    $pdf->Cell(20, 6, $kategori, 1, 1, 'C');
}

$pdf->Ln(5);

// ============================================================
// DETAIL PELANGGARAN
// ============================================================
$pdf->SetFont('Arial', 'B', 12);
$pdf->Cell(0, 8, 'C. Detail Pelanggaran', 0, 1, 'L');
$pdf->Ln(2);

// Header tabel
$pdf->SetFont('Arial', 'B', 8);
$pdf->SetFillColor(200, 200, 200);
$pdf->Cell(8, 7, 'No', 1, 0, 'C', true);
$pdf->Cell(18, 7, 'Tanggal', 1, 0, 'C', true);
$pdf->Cell(25, 7, 'NISN', 1, 0, 'C', true);
$pdf->Cell(40, 7, 'Nama Siswa', 1, 0, 'C', true);
$pdf->Cell(12, 7, 'Kelas', 1, 0, 'C', true);
$pdf->Cell(40, 7, 'Jenis Pelanggaran', 1, 0, 'C', true);
$pdf->Cell(12, 7, 'Poin', 1, 0, 'C', true);
$pdf->Cell(15, 7, 'Klasifikasi', 1, 0, 'C', true);
$pdf->Cell(15, 7, 'Status', 1, 1, 'C', true);

// Data detail
$pdf->SetFont('Arial', '', 7);
$no = 1;
foreach ($detailPelanggaran as $d) {
    // Klasifikasi berdasarkan poin
    $klasifikasi = '';
    if ($d['poin'] >= 50) {
        $klasifikasi = 'Berat';
    } elseif ($d['poin'] >= 25) {
        $klasifikasi = 'Sedang';
    } else {
        $klasifikasi = 'Ringan';
    }
    
    // Status
    $status = $d['status'];

    // Cek apakah perlu halaman baru
    if ($pdf->GetY() > 250) {
        $pdf->AddPage();
        // Header tabel di halaman baru
        $pdf->SetFont('Arial', 'B', 8);
        $pdf->SetFillColor(200, 200, 200);
        $pdf->Cell(8, 7, 'No', 1, 0, 'C', true);
        $pdf->Cell(18, 7, 'Tanggal', 1, 0, 'C', true);
        $pdf->Cell(25, 7, 'NISN', 1, 0, 'C', true);
        $pdf->Cell(40, 7, 'Nama Siswa', 1, 0, 'C', true);
        $pdf->Cell(12, 7, 'Kelas', 1, 0, 'C', true);
        $pdf->Cell(40, 7, 'Jenis Pelanggaran', 1, 0, 'C', true);
        $pdf->Cell(12, 7, 'Poin', 1, 0, 'C', true);
        $pdf->Cell(15, 7, 'Klasifikasi', 1, 0, 'C', true);
        $pdf->Cell(15, 7, 'Status', 1, 1, 'C', true);
    }

    $pdf->Cell(8, 6, $no++, 1, 0, 'C');
    $pdf->Cell(18, 6, date('d/m/Y', strtotime($d['tanggal'])), 1, 0, 'C');
    $pdf->Cell(25, 6, $d['nisn'], 1, 0, 'C');
    $pdf->Cell(40, 6, substr($d['nama'], 0, 22), 1, 0, 'L');
    $pdf->Cell(12, 6, $d['kelas'], 1, 0, 'C');
    $pdf->Cell(40, 6, substr($d['jenis_pelanggaran'], 0, 25), 1, 0, 'L');
    $pdf->Cell(12, 6, $d['poin'], 1, 0, 'C');
    $pdf->Cell(15, 6, $klasifikasi, 1, 0, 'C');
    $pdf->Cell(15, 6, $status, 1, 1, 'C');
}

$pdf->Ln(10);

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

$pdf->Cell(90, 6, 'Mengetahui,', 0, 0);
$pdf->Cell(90, 6, 'Wali Kelas ' . ($kelas != '' ? $kelas : '(Semua Kelas)'), 0, 1, 'C');
$pdf->Ln(15);

$pdf->Cell(90, 6, 'Kepala Sekolah', 0, 0);
$pdf->Cell(90, 6, '', 0, 1, 'C');
$pdf->Ln(5);

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

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

// Output PDF
$filename = "Rekap_Pelanggaran_" . ($kelas != '' ? "Kelas_$kelas" : "Semua_Kelas") . "_$bulanTeks$tahun.pdf";
$pdf->Output('D', $filename);
?>