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

include 'config.php';

// Filter data
$filter_tanggal = isset($_GET['tanggal']) ? $_GET['tanggal'] : '';
$filter_kelas = isset($_GET['kelas']) ? $_GET['kelas'] : '';
$filter_status = isset($_GET['status']) ? $_GET['status'] : '';
$filter_siswa = isset($_GET['siswa_id']) ? intval($_GET['siswa_id']) : 0;

// Query data pelanggaran dengan informasi lebih detail
$query = "SELECT p.*, 
                 s.nama as siswa_nama, 
                 s.kelas, 
                 s.nis, 
                 s.nisn,
                 g.nama as guru_nama,
                 g.nip as guru_nip,
                 wk.nama_wali as wali_nama,
                 wk.nip_wali as wali_nip,
                 wkp.nama_wali as wali_pengalih_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
          LEFT JOIN wali_kelas wkp ON s.kelas = wkp.kelas
          WHERE 1=1";

$params = [];
$types = '';

if (!empty($filter_tanggal)) {
    $query .= " AND DATE(p.tanggal) = ?";
    $params[] = $filter_tanggal;
    $types .= 's';
}
if (!empty($filter_kelas)) {
    $query .= " AND s.kelas = ?";
    $params[] = $filter_kelas;
    $types .= 's';
}
if (!empty($filter_status)) {
    $query .= " AND p.status = ?";
    $params[] = $filter_status;
    $types .= 's';
}
if ($filter_siswa > 0) {
    $query .= " AND p.siswa_id = ?";
    $params[] = $filter_siswa;
    $types .= 'i';
}

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

// Eksekusi query
$pelanggaran = [];
if (!empty($params)) {
    $stmt = mysqli_prepare($conn, $query);
    if ($stmt) {
        mysqli_stmt_bind_param($stmt, $types, ...$params);
        mysqli_stmt_execute($stmt);
        $result = mysqli_stmt_get_result($stmt);
        while ($row = mysqli_fetch_assoc($result)) {
            $pelanggaran[] = $row;
        }
    }
} else {
    $result = mysqli_query($conn, $query);
    while ($row = mysqli_fetch_assoc($result)) {
        $pelanggaran[] = $row;
    }
}

// Hitung statistik detail
$total_pelanggaran = count($pelanggaran);
$total_poin = array_sum(array_column($pelanggaran, 'poin'));
$pelanggaran_aktif = count(array_filter($pelanggaran, function($p) {
    return $p['status'] === 'Aktif';
}));
$pelanggaran_selesai = $total_pelanggaran - $pelanggaran_aktif;
$pelanggaran_dialihkan = count(array_filter($pelanggaran, function($p) {
    return $p['status_alihkan'] === 'ya';
}));

// Klasifikasi berdasarkan poin
$berat = count(array_filter($pelanggaran, function($p) {
    return $p['poin'] >= 50;
}));
$sedang = count(array_filter($pelanggaran, function($p) {
    return $p['poin'] >= 25 && $p['poin'] < 50;
}));
$ringan = count(array_filter($pelanggaran, function($p) {
    return $p['poin'] < 25;
}));

// Query untuk filter kelas
$kelas_query = mysqli_query($conn, "SELECT DISTINCT kelas FROM siswa ORDER BY kelas");

// Query untuk filter siswa (berdasarkan kelas yang dipilih)
$siswa_query = null;
if (!empty($filter_kelas)) {
    $siswa_query = mysqli_query($conn, "SELECT id, nama, nis FROM siswa WHERE kelas = '$filter_kelas' AND status = 'aktif' ORDER BY nama");
}

// Query untuk mendapatkan data sekolah
$sekolah_query = mysqli_query($conn, "SELECT nama_sekolah, alamat, kepala_sekolah, nip_kepala FROM profil_sekolah LIMIT 1");
$sekolah_data = mysqli_fetch_assoc($sekolah_query);

// PROSES CETAK PDF - VERSI TABEL YANG LEBIH RAPI
if (isset($_GET['cetak']) && $_GET['cetak'] == 'pdf') {
    require('fpdf/fpdf.php');
    
    class PDF extends FPDF {
        // Header
        function Header() {
            global $sekolah_data, $filter_tanggal, $filter_kelas, $filter_status, $filter_siswa;
            
            // Judul
            $this->SetFont('Arial','B',14);
            $this->Cell(0,6,strtoupper($sekolah_data['nama_sekolah'] ?? 'SEKOLAH'),0,1,'C');
            $this->SetFont('Arial','B',12);
            $this->Cell(0,6,'LAPORAN RIWAYAT PELANGGARAN SISWA',0,1,'C');
            
            // Informasi sekolah
            $this->SetFont('Arial','',9);
            $this->Cell(0,4,'Alamat: ' . ($sekolah_data['alamat'] ?? '-'),0,1,'C');
            
            // Filter info
            $this->SetFont('Arial','I',8);
            $filter_info = 'Periode: ';
            if ($filter_tanggal) {
                $filter_info .= date('d/m/Y', strtotime($filter_tanggal));
            } else {
                $filter_info .= 'Semua Tanggal';
            }
            
            if ($filter_kelas) {
                $filter_info .= ' | Kelas: ' . $filter_kelas;
            }
            if ($filter_status) {
                $filter_info .= ' | Status: ' . $filter_status;
            }
            
            $this->Cell(0,4,$filter_info,0,1,'C');
            $this->Ln(5);
        }
        
        // Footer
        function Footer() {
            $this->SetY(-15);
            $this->SetFont('Arial','I',8);
            $this->Cell(0,10,'Halaman ' . $this->PageNo() . ' dari {nb}',0,0,'C');
        }
        
        // Function untuk membuat tabel dengan border yang rapi
        function ImprovedTable($header, $data) {
            // Lebar kolom (landscape)
            $w = array(8, 15, 35, 10, 30, 35, 8, 20, 35, 15, 15);
            
            // Header
            $this->SetFillColor(220, 220, 220);
            $this->SetTextColor(0);
            $this->SetDrawColor(150, 150, 150);
            $this->SetLineWidth(.3);
            $this->SetFont('Arial','B',7);
            
            for($i=0;$i<count($header);$i++)
                $this->Cell($w[$i],7,$header[$i],1,0,'C',true);
            $this->Ln();
            
            // Data
            $this->SetFillColor(255, 255, 255);
            $this->SetTextColor(0);
            $this->SetFont('Arial','',6);
            
            $fill = false;
            $row_height = 5;
            
            foreach($data as $row) {
                // Cek jika halaman penuh
                if($this->GetY() > 180) {
                    $this->AddPage();
                    // Header tabel baru
                    $this->SetFillColor(220, 220, 220);
                    $this->SetFont('Arial','B',7);
                    for($i=0;$i<count($header);$i++)
                        $this->Cell($w[$i],7,$header[$i],1,0,'C',true);
                    $this->Ln();
                    $this->SetFont('Arial','',6);
                }
                
                // Hitung tinggi baris berdasarkan konten
                $nb = 1;
                $h = $row_height * $nb;
                
                // Baris pertama
                $x = $this->GetX();
                $y = $this->GetY();
                
                // Cell 1: No
                $this->MultiCell($w[0], $h, $row[0], 1, 'C', $fill);
                $this->SetXY($x + $w[0], $y);
                
                // Cell 2: Tanggal
                $this->MultiCell($w[1], $h, $row[1], 1, 'C', $fill);
                $this->SetXY($x + $w[0] + $w[1], $y);
                
                // Cell 3: Siswa
                $this->MultiCell($w[2], $h, $row[2], 1, 'L', $fill);
                $this->SetXY($x + $w[0] + $w[1] + $w[2], $y);
                
                // Cell 4: Kelas
                $this->MultiCell($w[3], $h, $row[3], 1, 'C', $fill);
                $this->SetXY($x + $w[0] + $w[1] + $w[2] + $w[3], $y);
                
                // Cell 5: Jenis
                $this->MultiCell($w[4], $h, $row[4], 1, 'L', $fill);
                $this->SetXY($x + $w[0] + $w[1] + $w[2] + $w[3] + $w[4], $y);
                
                // Cell 6: Keterangan
                $this->MultiCell($w[5], $h, $row[5], 1, 'L', $fill);
                $this->SetXY($x + $w[0] + $w[1] + $w[2] + $w[3] + $w[4] + $w[5], $y);
                
                // Cell 7: Poin
                $this->MultiCell($w[6], $h, $row[6], 1, 'C', $fill);
                $this->SetXY($x + $w[0] + $w[1] + $w[2] + $w[3] + $w[4] + $w[5] + $w[6], $y);
                
                // Cell 8: Klasifikasi
                $this->MultiCell($w[7], $h, $row[7], 1, 'C', $fill);
                $this->SetXY($x + $w[0] + $w[1] + $w[2] + $w[3] + $w[4] + $w[5] + $w[6] + $w[7], $y);
                
                // Cell 9: Pelapor
                $this->MultiCell($w[8], $h, $row[8], 1, 'L', $fill);
                $this->SetXY($x + $w[0] + $w[1] + $w[2] + $w[3] + $w[4] + $w[5] + $w[6] + $w[7] + $w[8], $y);
                
                // Cell 10: Status
                $this->MultiCell($w[9], $h, $row[9], 1, 'C', $fill);
                $this->SetXY($x + $w[0] + $w[1] + $w[2] + $w[3] + $w[4] + $w[5] + $w[6] + $w[7] + $w[8] + $w[9], $y);
                
                // Cell 11: Dialihkan
                $this->MultiCell($w[10], $h, $row[10], 1, 'C', $fill);
                
                $this->SetXY($x, $y + $h);
                $fill = !$fill;
            }
        }
    }
    
    // Buat PDF dengan orientasi landscape
    $pdf = new PDF('L','mm','A4');
    $pdf->AliasNbPages();
    $pdf->AddPage();
    
    // Header informasi
    $pdf->SetFont('Arial','B',10);
    $pdf->Cell(0,8,'STATISTIK:',0,1,'L');
    $pdf->SetFont('Arial','',9);
    $pdf->Cell(0,6,'Total Pelanggaran: ' . $total_pelanggaran . ' | Total Poin: ' . $total_poin,0,1,'L');
    $pdf->Cell(0,6,'Aktif: ' . $pelanggaran_aktif . ' | Selesai: ' . $pelanggaran_selesai . ' | Dialihkan: ' . $pelanggaran_dialihkan,0,1,'L');
    $pdf->Cell(0,6,'Klasifikasi - Berat: ' . $berat . ' | Sedang: ' . $sedang . ' | Ringan: ' . $ringan,0,1,'L');
    $pdf->Cell(0,6,'Dicetak pada: ' . date('d/m/Y H:i:s') . ' oleh ' . $_SESSION['username'],0,1,'L');
    $pdf->Ln(5);
    
    // Header tabel
    $header = array('No', 'Tanggal', 'Siswa (NIS)', 'Kls', 'Jenis', 'Keterangan', 'Poin', 'Klas', 'Pelapor', 'Status', 'Alih');
    
    // Siapkan data untuk tabel
    $data = array();
    $no = 1;
    
    foreach ($pelanggaran as $row) {
        $siswa_info = $row['siswa_nama'] . ' (' . $row['nis'] . ')';
        
        // Klasifikasi
        if ($row['poin'] >= 50) {
            $klasifikasi = 'Berat';
        } elseif ($row['poin'] >= 25) {
            $klasifikasi = 'Sedang';
        } else {
            $klasifikasi = 'Ringan';
        }
        
        // Pelapor
        if ($row['guru_nama']) {
            $pelapor = 'Guru: ' . $row['guru_nama'];
        } elseif ($row['wali_nama']) {
            $pelapor = 'Wali: ' . $row['wali_nama'];
        } else {
            $pelapor = 'System';
        }
        
        // Status alihkan
        $dialihkan = $row['status_alihkan'] == 'ya' ? 'Ya' : 'Tidak';
        if ($row['status_alihkan'] == 'ya' && $row['wali_nama']) {
            $dialihkan .= "\nke: " . $row['wali_nama'];
        }
        
        // Batasi panjang teks
        $jenis = (strlen($row['jenis_pelanggaran']) > 20) ? substr($row['jenis_pelanggaran'], 0, 17) . '...' : $row['jenis_pelanggaran'];
        $keterangan = (strlen($row['keterangan']) > 25) ? substr($row['keterangan'], 0, 22) . '...' : $row['keterangan'];
        
        $data[] = array(
            $no++,
            date('d/m/Y', strtotime($row['tanggal'])),
            $siswa_info,
            $row['kelas'],
            $jenis,
            $keterangan,
            $row['poin'],
            $klasifikasi,
            $pelapor,
            $row['status'],
            $dialihkan
        );
    }
    
    // Buat tabel
    $pdf->ImprovedTable($header, $data);
    
    // Tanda tangan
    $pdf->Ln(10);
    $pdf->SetFont('Arial','',9);
    $pdf->Cell(0,5,'Mengetahui,',0,1,'R');
    $pdf->Ln(15);
    $pdf->SetFont('Arial','B',10);
    $pdf->Cell(0,5,'(' . ($sekolah_data['kepala_sekolah'] ?? 'Kepala Sekolah') . ')',0,1,'R');
    
    // Output PDF
    $pdf->Output('Laporan_Pelanggaran_' . date('Ymd_His') . '.pdf', 'D');
    exit;
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Riwayat Pelanggaran - Admin</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css">
    <style>
        .table-responsive {
            max-height: 600px;
            overflow-y: auto;
        }
        .badge-berat {
            background: #ef4444;
            color: white;
            font-weight: 600;
        }
        .badge-sedang {
            background: #f59e0b;
            color: white;
            font-weight: 600;
        }
        .badge-ringan {
            background: #10b981;
            color: white;
            font-weight: 600;
        }
        .badge-aktif {
            background: #ef4444;
            color: white;
        }
        .badge-selesai {
            background: #10b981;
            color: white;
        }
        .badge-dialihkan {
            background: #f59e0b;
            color: white;
        }
        .stat-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }
        .stat-card-success {
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
        }
        .stat-card-warning {
            background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
        }
        .stat-card-danger {
            background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
        }
        .stat-card-info {
            background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
        }
        .print-header {
            display: none;
        }
        @media print {
            .no-print {
                display: none !important;
            }
            .print-header {
                display: block;
                text-align: center;
                margin-bottom: 20px;
                border-bottom: 2px solid #000;
                padding-bottom: 10px;
            }
            .table {
                font-size: 11px;
            }
            .table th, .table td {
                padding: 4px;
            }
        }
        .btn-pdf {
            background: linear-gradient(135deg, #dc3545 0%, #c82333 100%);
            border: none;
            color: white;
        }
        .btn-pdf:hover {
            background: linear-gradient(135deg, #c82333 0%, #bd2130 100%);
            color: white;
        }
        .table-striped tbody tr:nth-of-type(odd) {
            background-color: rgba(0,0,0,.02);
        }
        .table-hover tbody tr:hover {
            background-color: rgba(0,123,255,.1);
        }
        .detail-info {
            font-size: 0.85rem;
            color: #6c757d;
        }
        .detail-info i {
            width: 16px;
            margin-right: 4px;
        }
        .filter-section {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
            border: 1px solid #dee2e6;
        }
    </style>
</head>
<body class="container py-4">
    <div class="print-header">
        <h2><?php echo $sekolah_data['nama_sekolah'] ?? 'Sekolah'; ?></h2>
        <h4>Laporan Riwayat Pelanggaran Siswa</h4>
        <p>Alamat: <?php echo $sekolah_data['alamat'] ?? '-'; ?></p>
        <p>Periode: <?php 
            if($filter_tanggal) {
                echo date('d/m/Y', strtotime($filter_tanggal));
            } elseif($filter_kelas || $filter_status) {
                echo 'Filter: ';
                if($filter_kelas) echo "Kelas $filter_kelas ";
                if($filter_status) echo "Status $filter_status";
            } else {
                echo 'Semua Data';
            }
        ?></p>
        <p>Dicetak: <?php echo date('d/m/Y H:i:s'); ?></p>
    </div>

    <h2 class="text-center mb-4"><i class="fas fa-exclamation-triangle text-danger"></i> Riwayat Pelanggaran Siswa</h2>

    <div class="no-print">
        <a href="dashboard.php" class="btn btn-secondary mb-3"><i class="fas fa-arrow-left"></i> Kembali ke Dashboard</a>
        
        <!-- Tombol Cetak -->
        <div class="mb-3">
            <button onclick="window.print()" class="btn btn-primary">
                <i class="fas fa-print"></i> Cetak Halaman
            </button>
            <a href="?cetak=pdf&tanggal=<?php echo $filter_tanggal; ?>&kelas=<?php echo $filter_kelas; ?>&status=<?php echo $filter_status; ?>&siswa_id=<?php echo $filter_siswa; ?>" 
               class="btn btn-pdf">
                <i class="fas fa-file-pdf"></i> Cetak PDF
            </a>
            <span class="ms-3 text-muted">
                <i class="fas fa-info-circle"></i> Total: <?php echo $total_pelanggaran; ?> data pelanggaran
            </span>
        </div>
    </div>

    <!-- Statistik Detail -->
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="stat-card">
                <div class="row">
                    <div class="col-8">
                        <h3><?php echo $total_pelanggaran; ?></h3>
                        <p>Total Pelanggaran</p>
                    </div>
                    <div class="col-4 text-end">
                        <i class="fas fa-clipboard-list fa-3x"></i>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stat-card stat-card-success">
                <div class="row">
                    <div class="col-8">
                        <h3><?php echo $total_poin; ?></h3>
                        <p>Total Poin</p>
                    </div>
                    <div class="col-4 text-end">
                        <i class="fas fa-weight-hanging fa-3x"></i>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stat-card stat-card-warning">
                <div class="row">
                    <div class="col-8">
                        <h3><?php echo $pelanggaran_aktif; ?> / <?php echo $pelanggaran_selesai; ?></h3>
                        <p>Aktif / Selesai</p>
                    </div>
                    <div class="col-4 text-end">
                        <i class="fas fa-clock fa-3x"></i>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stat-card stat-card-danger">
                <div class="row">
                    <div class="col-8">
                        <h3><?php echo $berat; ?> / <?php echo $sedang; ?> / <?php echo $ringan; ?></h3>
                        <p>Berat / Sedang / Ringan</p>
                    </div>
                    <div class="col-4 text-end">
                        <i class="fas fa-balance-scale fa-3x"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Filter Form -->
    <div class="filter-section no-print">
        <h5 class="mb-3"><i class="fas fa-filter"></i> Filter Data</h5>
        <form method="GET" class="row g-3">
            <div class="col-md-2">
                <label for="tanggal" class="form-label">Tanggal</label>
                <input type="date" class="form-control" id="tanggal" name="tanggal" 
                       value="<?php echo $filter_tanggal; ?>">
            </div>
            <div class="col-md-2">
                <label for="kelas" class="form-label">Kelas</label>
                <select class="form-select" id="kelas" name="kelas" onchange="this.form.submit()">
                    <option value="">Semua Kelas</option>
                    <?php 
                    mysqli_data_seek($kelas_query, 0);
                    while($kelas = mysqli_fetch_assoc($kelas_query)): ?>
                        <option value="<?php echo $kelas['kelas']; ?>" 
                                <?php echo $filter_kelas == $kelas['kelas'] ? 'selected' : ''; ?>>
                            <?php echo $kelas['kelas']; ?>
                        </option>
                    <?php endwhile; ?>
                </select>
            </div>
            <div class="col-md-2">
                <label for="siswa_id" class="form-label">Siswa</label>
                <select class="form-select" id="siswa_id" name="siswa_id">
                    <option value="">Semua Siswa</option>
                    <?php if ($siswa_query): 
                        while($siswa = mysqli_fetch_assoc($siswa_query)): ?>
                            <option value="<?php echo $siswa['id']; ?>" 
                                    <?php echo $filter_siswa == $siswa['id'] ? 'selected' : ''; ?>>
                                <?php echo $siswa['nama']; ?> (<?php echo $siswa['nis']; ?>)
                            </option>
                    <?php endwhile; endif; ?>
                </select>
            </div>
            <div class="col-md-2">
                <label for="status" class="form-label">Status</label>
                <select class="form-select" id="status" name="status">
                    <option value="">Semua Status</option>
                    <option value="Aktif" <?php echo $filter_status == 'Aktif' ? 'selected' : ''; ?>>Aktif</option>
                    <option value="Selesai" <?php echo $filter_status == 'Selesai' ? 'selected' : ''; ?>>Selesai</option>
                </select>
            </div>
            <div class="col-md-2 d-flex align-items-end">
                <button type="submit" class="btn btn-primary w-100">
                    <i class="fas fa-search"></i> Filter
                </button>
            </div>
            <div class="col-md-2 d-flex align-items-end">
                <a href="riwayat_pelanggaran.php" class="btn btn-secondary w-100">
                    <i class="fas fa-redo-alt"></i> Reset
                </a>
            </div>
        </form>
        <?php if($filter_tanggal || $filter_kelas || $filter_status || $filter_siswa): ?>
        <div class="mt-2">
            <small class="text-muted">
                <i class="fas fa-info-circle"></i> Filter aktif: 
                <?php if($filter_tanggal) echo "Tanggal: " . date('d/m/Y', strtotime($filter_tanggal)) . " "; ?>
                <?php if($filter_kelas) echo "Kelas: $filter_kelas "; ?>
                <?php if($filter_siswa) echo "Siswa ID: $filter_siswa "; ?>
                <?php if($filter_status) echo "Status: $filter_status"; ?>
            </small>
        </div>
        <?php endif; ?>
    </div>

    <!-- Tabel Riwayat Pelanggaran -->
    <div class="card">
        <div class="card-header bg-warning text-dark d-flex justify-content-between align-items-center">
            <div>
                <i class="fas fa-history"></i> <strong>Data Pelanggaran</strong>
                <span class="badge bg-dark ms-2"><?php echo $total_pelanggaran; ?> Data</span>
            </div>
            <div class="text-muted small">
                <i class="fas fa-clock"></i> <?php echo date('d/m/Y H:i:s'); ?>
            </div>
        </div>
        <div class="card-body p-0">
            <?php if (empty($pelanggaran)): ?>
                <div class="text-center text-success py-4">
                    <i class="fas fa-check-circle fa-2x mb-2"></i><br>
                    <strong>Tidak ada data pelanggaran</strong>
                    <p class="text-muted mt-2">Coba gunakan filter yang berbeda</p>
                </div>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-bordered table-striped table-hover table-sm mb-0">
                        <thead class="table-light">
                            <tr>
                                <th width="3%">No</th>
                                <th width="8%">Tanggal</th>
                                <th width="12%">Siswa</th>
                                <th width="5%">Kls</th>
                                <th width="10%">Jenis</th>
                                <th width="15%">Keterangan</th>
                                <th width="5%">Poin</th>
                                <th width="7%">Klasifikasi</th>
                                <th width="12%">Pelapor</th>
                                <th width="8%">Status</th>
                                <th width="8%">Dialihkan</th>
                                <th width="7%" class="no-print">Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($pelanggaran as $index => $data): 
                                // Klasifikasi
                                if ($data['poin'] >= 50) {
                                    $klasifikasi = 'Berat';
                                    $klasifikasiClass = 'badge-berat';
                                } elseif ($data['poin'] >= 25) {
                                    $klasifikasi = 'Sedang';
                                    $klasifikasiClass = 'badge-sedang';
                                } else {
                                    $klasifikasi = 'Ringan';
                                    $klasifikasiClass = 'badge-ringan';
                                }
                                
                                // Pelapor
                                if ($data['guru_nama']) {
                                    $pelapor = '<i class="fas fa-user-tie text-primary" title="Guru"></i> ' . $data['guru_nama'];
                                    $pelapor_detail = 'Guru: ' . $data['guru_nama'] . ' (' . ($data['guru_nip'] ?? '-') . ')';
                                } elseif ($data['wali_nama']) {
                                    $pelapor = '<i class="fas fa-chalkboard-teacher text-warning" title="Wali Kelas"></i> ' . $data['wali_nama'];
                                    $pelapor_detail = 'Wali Kelas: ' . $data['wali_nama'] . ' (' . ($data['wali_nip'] ?? '-') . ')';
                                } else {
                                    $pelapor = '<i class="fas fa-robot text-secondary" title="System"></i> System';
                                    $pelapor_detail = 'System';
                                }
                            ?>
                                <tr>
                                    <td class="text-center"><?php echo $index + 1; ?></td>
                                    <td>
                                        <?php echo date('d/m/Y', strtotime($data['tanggal'])); ?>
                                        <br><small class="detail-info"><i class="fas fa-clock"></i> <?php echo date('H:i', strtotime($data['created_at'])); ?></small>
                                    </td>
                                    <td>
                                        <strong><?php echo $data['siswa_nama']; ?></strong>
                                        <br><small class="detail-info"><i class="fas fa-id-card"></i> NIS: <?php echo $data['nis']; ?></small>
                                        <br><small class="detail-info"><i class="fas fa-qrcode"></i> NISN: <?php echo $data['nisn'] ?? '-'; ?></small>
                                    </td>
                                    <td><span class="badge bg-info"><?php echo $data['kelas']; ?></span></td>
                                    <td><?php echo htmlspecialchars($data['jenis_pelanggaran']); ?></td>
                                    <td>
                                        <small><?php echo htmlspecialchars($data['keterangan']); ?></small>
                                    </td>
                                    <td class="text-center">
                                        <span class="badge <?php echo $klasifikasiClass; ?> p-2">
                                            <?php echo $data['poin']; ?>
                                        </span>
                                    </td>
                                    <td class="text-center">
                                        <span class="badge <?php echo $klasifikasiClass; ?>">
                                            <?php echo $klasifikasi; ?>
                                        </span>
                                    </td>
                                    <td>
                                        <?php echo $pelapor; ?>
                                        <?php if (!empty($data['catatan_penanganan'])): ?>
                                            <br><small class="detail-info" title="<?php echo htmlspecialchars($data['catatan_penanganan']); ?>">
                                                <i class="fas fa-clipboard"></i> Ada catatan
                                            </small>
                                        <?php endif; ?>
                                    </td>
                                    <td class="text-center">
                                        <span class="badge <?php echo $data['status'] === 'Selesai' ? 'badge-selesai' : 'badge-aktif'; ?>">
                                            <i class="fas <?php echo $data['status'] === 'Selesai' ? 'fa-check-circle' : 'fa-clock'; ?>"></i>
                                            <?php echo $data['status']; ?>
                                        </span>
                                        <?php if (!empty($data['tindakan'])): ?>
                                            <br><small class="detail-info"><i class="fas fa-gavel"></i> <?php echo $data['tindakan']; ?></small>
                                        <?php endif; ?>
                                    </td>
                                    <td class="text-center">
                                        <?php if ($data['status_alihkan'] == 'ya'): ?>
                                            <span class="badge badge-dialihkan">
                                                <i class="fas fa-share-alt"></i> Ya
                                            </span>
                                            <?php if (!empty($data['wali_nama'])): ?>
                                                <br><small class="detail-info"><i class="fas fa-user"></i> <?php echo $data['wali_nama']; ?></small>
                                            <?php endif; ?>
                                            <?php if (!empty($data['catatan_alihkan'])): ?>
                                                <br><small class="detail-info" title="<?php echo htmlspecialchars($data['catatan_alihkan']); ?>">
                                                    <i class="fas fa-comment"></i> Ada catatan
                                                </small>
                                            <?php endif; ?>
                                        <?php else: ?>
                                            <span class="badge bg-secondary">Tidak</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="text-center no-print">
                                        <div class="btn-group btn-group-sm" role="group">
                                            <a href="detail_pelanggaran.php?id=<?php echo $data['id']; ?>" class="btn btn-info" title="Lihat Detail">
                                                <i class="fas fa-eye"></i>
                                            </a>
                                            <button type="button" class="btn btn-warning" 
                                                    onclick="alert('Edit pelanggaran ID: <?php echo $data['id']; ?>\nFitur dalam pengembangan.')"
                                                    title="Edit">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
        <div class="card-footer text-muted no-print">
            <small><i class="fas fa-info-circle"></i> Menampilkan <?php echo count($pelanggaran); ?> dari <?php echo $total_pelanggaran; ?> data pelanggaran</small>
        </div>
    </div>

    <div class="mt-4 no-print">
        <div class="alert alert-info">
            <h5><i class="fas fa-file-pdf"></i> Informasi Cetak PDF:</h5>
            <ul class="mb-0">
                <li>PDF akan dibuat dalam format landscape A4</li>
                <li>File PDF akan otomatis terdownload dengan format: <code>Laporan_Pelanggaran_TGL_JAM.pdf</code></li>
                <li>Data yang dicetak sesuai dengan filter yang diterapkan</li>
            </ul>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Auto submit form ketika kelas dipilih
        document.getElementById('kelas').addEventListener('change', function() {
            this.form.submit();
        });
        
        // Auto submit form ketika siswa dipilih
        document.getElementById('siswa_id').addEventListener('change', function() {
            this.form.submit();
        });
        
        // Auto submit form ketika status dipilih
        document.getElementById('status').addEventListener('change', function() {
            this.form.submit();
        });
        
        // Alert sebelum cetak PDF
        document.querySelector('a[href*="cetak=pdf"]').addEventListener('click', function(e) {
            if(!confirm('PDF akan segera dibuat. Proses ini mungkin membutuhkan beberapa saat untuk data yang banyak.\n\nLanjutkan?')) {
                e.preventDefault();
            }
        });
        
        // Tooltip untuk detail informasi
        var tooltipTriggerList = [].slice.call(document.querySelectorAll('[title]'));
        var tooltipList = tooltipTriggerList.map(function(tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl);
        });
    </script>
</body>
</html>