<?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 ID
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($id <= 0) {
    header("Location: dashboard_guru_piket.php");
    exit;
}

// Ambil data pelanggaran
$query = "SELECT p.*, 
                 s.nama as nama_siswa, 
                 s.nisn, 
                 s.kelas, 
                 s.no_wa,
                 g.nama as nama_guru_pelapor,
                 g.nip as nip_guru_pelapor,
                 w.nama_wali as nama_wali_kelas,
                 w.kelas as kelas_wali
          FROM pelanggaran p 
          LEFT JOIN siswa s ON p.siswa_id = s.id 
          LEFT JOIN guru g ON p.guru_id = g.id
          LEFT JOIN wali_kelas w ON p.wali_kelas_id = w.id
          WHERE p.id = $id";

$result = mysqli_query($conn, $query);

if (!$result || mysqli_num_rows($result) == 0) {
    header("Location: dashboard_guru_piket.php");
    exit;
}

$pelanggaran = mysqli_fetch_assoc($result);

// 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 guru yang login untuk tanda tangan
$username = $_SESSION['username'];
$guru_nama = '';
$query = "SELECT * FROM guru WHERE nip = '$username' LIMIT 1";
$result = mysqli_query($conn, $query);
if ($result && mysqli_num_rows($result) > 0) {
    $guru = mysqli_fetch_assoc($result);
    $guru_nama = $guru['nama'];
} else {
    $query_user = "SELECT * FROM users WHERE username = '$username' AND role = 'guru' LIMIT 1";
    $result_user = mysqli_query($conn, $query_user);
    if ($result_user && mysqli_num_rows($result_user) > 0) {
        $user = mysqli_fetch_assoc($result_user);
        $guru_nama = $user['nama'] ?? $username;
    }
}

// Format tanggal
$tanggal_laporan = date('d F Y', strtotime($pelanggaran['tanggal']));
$tanggal_dibuat = !empty($pelanggaran['created_at']) ? date('d F Y', strtotime($pelanggaran['created_at'])) : '-';
$tanggal_diupdate = !empty($pelanggaran['updated_at']) ? date('d F Y', strtotime($pelanggaran['updated_at'])) : '-';
$tanggal_dialihkan = !empty($pelanggaran['tanggal_alihkan']) ? date('d F Y', strtotime($pelanggaran['tanggal_alihkan'])) : '-';
$tanggal_cetak = date('d F Y');

// Tentukan klasifikasi
if ($pelanggaran['poin'] >= 50) {
    $klasifikasi = 'BERAT';
    $warna = '#ef4444';
} elseif ($pelanggaran['poin'] >= 25) {
    $klasifikasi = 'SEDANG';
    $warna = '#f59e0b';
} else {
    $klasifikasi = 'RINGAN';
    $warna = '#10b981';
}

// Buat PDF Portrait A4
class PDF extends FPDF
{
    function Header()
    {
        global $nama_sekolah;
        
        // Kop Surat
        $this->SetFont('Times', 'B', 16);
        $this->Cell(0, 8, $nama_sekolah, 0, 1, 'C');
        $this->SetFont('Times', '', 10);
        $this->Cell(0, 5, 'Jalan Pendidikan No. 123, Telp. (021) 1234567', 0, 1, 'C');
        $this->Cell(0, 5, 'Email: info@sekolah.sch.id | Website: www.sekolah.sch.id', 0, 1, 'C');
        
        $this->SetFont('Times', 'B', 14);
        $this->Cell(0, 10, 'DETAIL PELANGGARAN SISWA', 0, 1, 'C');
        $this->SetFont('Times', '', 11);
        $this->Cell(0, 6, 'Nomor: DP/' . date('Y') . '/' . str_pad($GLOBALS['id'], 4, '0', STR_PAD_LEFT), 0, 1, 'C');
        
        // Garis
        $this->Line(10, $this->GetY(), 200, $this->GetY());
        $this->Ln(8);
    }

    function Footer()
    {
        $this->SetY(-15);
        $this->SetFont('Times', 'I', 8);
        $this->Cell(0, 10, 'Halaman ' . $this->PageNo(), 0, 0, 'C');
    }
    
    // Fungsi untuk membuat cell dengan border dan background
    function LabelCell($label, $value, $isBold = false)
    {
        $this->SetFont('Times', 'B', 11);
        $this->Cell(45, 7, $label, 0, 0);
        $this->SetFont('Times', '', 11);
        $this->Cell(5, 7, ':', 0, 0);
        
        if ($isBold) {
            $this->SetFont('Times', 'B', 11);
        }
        $this->MultiCell(0, 7, $value, 0, 'L');
        $this->SetFont('Times', '', 11);
    }
    
    function LabelCellInline($label, $value, $x, $y)
    {
        $this->SetXY($x, $y);
        $this->SetFont('Times', 'B', 11);
        $this->Cell(40, 7, $label, 0, 0);
        $this->SetFont('Times', '', 11);
        $this->Cell(5, 7, ':', 0, 0);
        $this->Cell(60, 7, $value, 0, 1);
    }
}

// Inisialisasi PDF
$pdf = new PDF();
$pdf->AddPage();
$pdf->SetAutoPageBreak(true, 20); // Auto page break dengan margin bawah 20mm

// ============================================================
// INFORMASI SISWA (2 KOLOM)
// ============================================================
$pdf->SetFont('Times', 'B', 12);
$pdf->Cell(0, 8, 'A. INFORMASI SISWA', 0, 1);
$pdf->Ln(2);

// Kolom kiri
$y = $pdf->GetY();
$pdf->SetFont('Times', 'B', 11);
$pdf->Cell(45, 7, 'NISN', 0, 0);
$pdf->SetFont('Times', '', 11);
$pdf->Cell(5, 7, ':', 0, 0);
$pdf->Cell(50, 7, $pelanggaran['nisn'] ?? '-', 0, 0);

$pdf->SetX(120);
$pdf->SetFont('Times', 'B', 11);
$pdf->Cell(45, 7, 'Nama Siswa', 0, 0);
$pdf->SetFont('Times', '', 11);
$pdf->Cell(5, 7, ':', 0, 0);
$pdf->Cell(0, 7, $pelanggaran['nama_siswa'] ?? '-', 0, 1);

// Baris 2
$pdf->SetFont('Times', 'B', 11);
$pdf->Cell(45, 7, 'Kelas', 0, 0);
$pdf->SetFont('Times', '', 11);
$pdf->Cell(5, 7, ':', 0, 0);
$pdf->Cell(50, 7, $pelanggaran['kelas'] ?? '-', 0, 0);

$pdf->SetX(120);
$pdf->SetFont('Times', 'B', 11);
$pdf->Cell(45, 7, 'No. WhatsApp', 0, 0);
$pdf->SetFont('Times', '', 11);
$pdf->Cell(5, 7, ':', 0, 0);
$pdf->Cell(0, 7, $pelanggaran['no_wa'] ?? '-', 0, 1);

$pdf->Ln(5);

// ============================================================
// DETAIL PELANGGARAN (2 KOLOM)
// ============================================================
$pdf->SetFont('Times', 'B', 12);
$pdf->Cell(0, 8, 'B. DETAIL PELANGGARAN', 0, 1);
$pdf->Ln(2);

// Baris 1
$pdf->SetFont('Times', 'B', 11);
$pdf->Cell(45, 7, 'Tanggal Kejadian', 0, 0);
$pdf->SetFont('Times', '', 11);
$pdf->Cell(5, 7, ':', 0, 0);
$pdf->Cell(50, 7, $tanggal_laporan, 0, 0);

$pdf->SetX(120);
$pdf->SetFont('Times', 'B', 11);
$pdf->Cell(45, 7, 'Jenis Pelanggaran', 0, 0);
$pdf->SetFont('Times', '', 11);
$pdf->Cell(5, 7, ':', 0, 0);
$pdf->Cell(0, 7, $pelanggaran['jenis_pelanggaran'], 0, 1);

// Baris 2
$pdf->SetFont('Times', 'B', 11);
$pdf->Cell(45, 7, 'Poin Pelanggaran', 0, 0);
$pdf->SetFont('Times', '', 11);
$pdf->Cell(5, 7, ':', 0, 0);
$pdf->Cell(50, 7, $pelanggaran['poin'] . ' Poin', 0, 0);

$pdf->SetX(120);
$pdf->SetFont('Times', 'B', 11);
$pdf->Cell(45, 7, 'Klasifikasi', 0, 0);
$pdf->SetFont('Times', '', 11);
$pdf->Cell(5, 7, ':', 0, 0);
$pdf->SetTextColor(hexdec(substr($warna, 1, 2)), hexdec(substr($warna, 3, 2)), hexdec(substr($warna, 5, 2)));
$pdf->Cell(0, 7, $klasifikasi, 0, 1);
$pdf->SetTextColor(0, 0, 0); // Kembalikan ke hitam

// Baris 3
$pdf->SetFont('Times', 'B', 11);
$pdf->Cell(45, 7, 'Status', 0, 0);
$pdf->SetFont('Times', '', 11);
$pdf->Cell(5, 7, ':', 0, 0);
$pdf->Cell(50, 7, $pelanggaran['status'], 0, 1);

$pdf->Ln(2);

// Keterangan (full width)
$pdf->SetFont('Times', 'B', 11);
$pdf->Cell(45, 7, 'Keterangan', 0, 0);
$pdf->Cell(5, 7, ':', 0, 1);
$pdf->SetFont('Times', '', 11);
$pdf->MultiCell(0, 6, $pelanggaran['keterangan'], 0, 'L');
$pdf->Ln(5);

// ============================================================
// INFORMASI LAINNYA (2 KOLOM)
// ============================================================
$pdf->SetFont('Times', 'B', 12);
$pdf->Cell(0, 8, 'C. INFORMASI LAINNYA', 0, 1);
$pdf->Ln(2);

// Baris 1
$pdf->SetFont('Times', 'B', 11);
$pdf->Cell(45, 7, 'Dilaporkan Oleh', 0, 0);
$pdf->SetFont('Times', '', 11);
$pdf->Cell(5, 7, ':', 0, 0);
$pdf->Cell(50, 7, $pelanggaran['nama_guru_pelapor'] ?? 'Guru Piket', 0, 0);

$pdf->SetX(120);
$pdf->SetFont('Times', 'B', 11);
$pdf->Cell(45, 7, 'NIP Pelapor', 0, 0);
$pdf->SetFont('Times', '', 11);
$pdf->Cell(5, 7, ':', 0, 0);
$pdf->Cell(0, 7, $pelanggaran['nip_guru_pelapor'] ?? '-', 0, 1);

// Baris 2
$pdf->SetFont('Times', 'B', 11);
$pdf->Cell(45, 7, 'Tanggal Lapor', 0, 0);
$pdf->SetFont('Times', '', 11);
$pdf->Cell(5, 7, ':', 0, 0);
$pdf->Cell(50, 7, $tanggal_dibuat, 0, 0);

$pdf->SetX(120);
$pdf->SetFont('Times', 'B', 11);
$pdf->Cell(45, 7, 'Terakhir Update', 0, 0);
$pdf->SetFont('Times', '', 11);
$pdf->Cell(5, 7, ':', 0, 0);
$pdf->Cell(0, 7, $tanggal_diupdate, 0, 1);

$pdf->Ln(5);

// ============================================================
// INFORMASI ALIHAN (JIKA ADA)
// ============================================================
if (!empty($pelanggaran['status_alihkan']) && $pelanggaran['status_alihkan'] == 'ya') {
    $pdf->SetFont('Times', 'B', 12);
    $pdf->Cell(0, 8, 'D. INFORMASI ALIHAN', 0, 1);
    $pdf->Ln(2);

    // Baris 1
    $pdf->SetFont('Times', 'B', 11);
    $pdf->Cell(45, 7, 'Wali Kelas Tujuan', 0, 0);
    $pdf->SetFont('Times', '', 11);
    $pdf->Cell(5, 7, ':', 0, 0);
    $pdf->Cell(50, 7, $pelanggaran['nama_wali_kelas'] ?? '-', 0, 0);

    $pdf->SetX(120);
    $pdf->SetFont('Times', 'B', 11);
    $pdf->Cell(45, 7, 'Kelas Wali', 0, 0);
    $pdf->SetFont('Times', '', 11);
    $pdf->Cell(5, 7, ':', 0, 0);
    $pdf->Cell(0, 7, $pelanggaran['kelas_wali'] ?? '-', 0, 1);

    // Baris 2
    $pdf->SetFont('Times', 'B', 11);
    $pdf->Cell(45, 7, 'Tanggal Dialihkan', 0, 0);
    $pdf->SetFont('Times', '', 11);
    $pdf->Cell(5, 7, ':', 0, 0);
    $pdf->Cell(50, 7, $tanggal_dialihkan, 0, 1);

    if (!empty($pelanggaran['catatan_alihkan'])) {
        $pdf->Ln(2);
        $pdf->SetFont('Times', 'B', 11);
        $pdf->Cell(45, 7, 'Catatan Alihan', 0, 0);
        $pdf->Cell(5, 7, ':', 0, 1);
        $pdf->SetFont('Times', '', 11);
        $pdf->MultiCell(0, 6, $pelanggaran['catatan_alihkan'], 0, 'L');
    }
    $pdf->Ln(5);
}

// ============================================================
// PENANGANAN (JIKA ADA)
// ============================================================
if (!empty($pelanggaran['tindakan']) || !empty($pelanggaran['catatan_penanganan'])) {
    $pdf->SetFont('Times', 'B', 12);
    $pdf->Cell(0, 8, 'E. PENANGANAN PELANGGARAN', 0, 1);
    $pdf->Ln(2);

    if (!empty($pelanggaran['tindakan'])) {
        $pdf->SetFont('Times', 'B', 11);
        $pdf->Cell(45, 7, 'Tindakan', 0, 0);
        $pdf->SetFont('Times', '', 11);
        $pdf->Cell(5, 7, ':', 0, 0);
        $pdf->Cell(0, 7, $pelanggaran['tindakan'], 0, 1);
    }

    if (!empty($pelanggaran['catatan_penanganan'])) {
        $pdf->Ln(2);
        $pdf->SetFont('Times', 'B', 11);
        $pdf->Cell(45, 7, 'Catatan', 0, 0);
        $pdf->Cell(5, 7, ':', 0, 1);
        $pdf->SetFont('Times', '', 11);
        $pdf->MultiCell(0, 6, $pelanggaran['catatan_penanganan'], 0, 'L');
    }
    $pdf->Ln(5);
}

// ============================================================
// TANDA TANGAN (Selalu di bagian bawah)
// ============================================================
// Cek apakah masih ada ruang untuk tanda tangan, jika tidak tambah halaman baru
if ($pdf->GetY() > 220) {
    $pdf->AddPage();
}

$pdf->Ln(5);
$pdf->SetFont('Times', '', 11);
$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, 'Guru Piket,', 0, 1, 'C');
$pdf->Ln(15);

$pdf->SetFont('Times', 'BU', 11);
$pdf->Cell(90, 6, $kepala_sekolah, 0, 0, 'L');
$pdf->Cell(90, 6, $guru_nama, 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 = "Detail_Pelanggaran_" . str_pad($id, 4, '0', STR_PAD_LEFT) . "_" . date('Y-m-d') . ".pdf";
$pdf->Output('D', $filename);
?>