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

include 'config.php';

$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 daftar siswa untuk filter
$qSiswa = mysqli_query($conn, "
    SELECT id, nama, nis, nisn 
    FROM siswa 
    WHERE kelas = '$kelas_diampu' 
    AND status = 'aktif'
    ORDER BY nama
");
$daftar_siswa = [];
while ($row = mysqli_fetch_assoc($qSiswa)) {
    $daftar_siswa[] = $row;
}

// 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";

$qRiwayat = mysqli_query($conn, $query);
$riwayat_pelanggaran = [];
if ($qRiwayat) {
    while ($row = mysqli_fetch_assoc($qRiwayat)) {
        $riwayat_pelanggaran[] = $row;
    }
}

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

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

// Ambil nama sekolah
$profil = mysqli_fetch_assoc(mysqli_query($conn, "SELECT nama_sekolah FROM profil_sekolah LIMIT 1"));
$nama_sekolah = $profil['nama_sekolah'] ?? 'Sistem Pelanggaran Siswa';
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Riwayat Pelanggaran - Wali Kelas</title>
    
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css">
    
    <!-- Bootstrap 5 -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <!-- DataTables -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">
    
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Inter', sans-serif;
            background: #f8f9fa;
            color: #333;
            line-height: 1.6;
            padding: 20px;
        }

        /* Header */
        .header {
            background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
            color: white;
            padding: 1rem 2rem;
            border-radius: 8px;
            margin-bottom: 20px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 15px;
        }

        .logo h2 {
            font-size: 1.5rem;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .logo p {
            font-size: 0.875rem;
            opacity: 0.9;
            margin-top: 5px;
        }

        .user-info {
            display: flex;
            align-items: center;
            gap: 15px;
            background: rgba(255,255,255,0.15);
            padding: 8px 15px;
            border-radius: 50px;
            backdrop-filter: blur(10px);
        }

        .user-avatar {
            width: 40px;
            height: 40px;
            background: rgba(255,255,255,0.2);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
        }

        .user-details .name {
            font-weight: 600;
            font-size: 0.95rem;
        }

        .user-details .role {
            font-size: 0.75rem;
            opacity: 0.8;
        }

        .btn-back {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 8px 16px;
            background: #6c757d;
            color: white;
            text-decoration: none;
            border-radius: 6px;
            font-size: 0.9rem;
            margin-bottom: 20px;
            transition: background 0.3s;
        }

        .btn-back:hover {
            background: #5a6268;
            color: white;
        }

        .btn-print {
            background: #28a745;
            color: white;
            padding: 8px 16px;
            border-radius: 6px;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            font-size: 0.9rem;
            transition: background 0.3s;
        }

        .btn-print:hover {
            background: #218838;
            color: white;
        }

        .filter-card {
            background: white;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        .filter-form {
            display: flex;
            gap: 15px;
            flex-wrap: wrap;
            align-items: flex-end;
        }

        .filter-group {
            flex: 1;
            min-width: 150px;
        }

        .filter-group label {
            display: block;
            font-weight: 500;
            margin-bottom: 5px;
            color: #555;
            font-size: 0.875rem;
        }

        .filter-control {
            width: 100%;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 0.875rem;
        }

        .filter-control:focus {
            outline: none;
            border-color: #6366f1;
        }

        .btn-filter {
            background: #6366f1;
            color: white;
            border: none;
            padding: 8px 20px;
            border-radius: 4px;
            font-weight: 500;
            cursor: pointer;
            display: inline-flex;
            align-items: center;
            gap: 5px;
        }

        .btn-filter:hover {
            background: #4f46e5;
        }

        .btn-reset {
            background: #6c757d;
            color: white;
            border: none;
            padding: 8px 20px;
            border-radius: 4px;
            font-weight: 500;
            cursor: pointer;
            display: inline-flex;
            align-items: center;
            gap: 5px;
            text-decoration: none;
        }

        .btn-reset:hover {
            background: #5a6268;
            color: white;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-bottom: 20px;
        }

        .stat-card {
            background: white;
            border-radius: 8px;
            padding: 15px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            border-left: 4px solid;
        }

        .stat-card.total {
            border-left-color: #6366f1;
        }
        .stat-card.aktif {
            border-left-color: #ef4444;
        }
        .stat-card.selesai {
            border-left-color: #10b981;
        }
        .stat-card.poin {
            border-left-color: #f59e0b;
        }
        .stat-card.berat {
            border-left-color: #ef4444;
        }
        .stat-card.sedang {
            border-left-color: #f59e0b;
        }
        .stat-card.ringan {
            border-left-color: #10b981;
        }

        .stat-number {
            font-size: 1.75rem;
            font-weight: 700;
            color: #333;
            margin-bottom: 5px;
        }

        .stat-label {
            font-size: 0.875rem;
            color: #6c757d;
        }

        .card {
            background: white;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }

        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }

        .card-header h3 {
            font-size: 1.1rem;
            font-weight: 600;
            color: #333;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .table {
            width: 100%;
            border-collapse: collapse;
            font-size: 0.875rem;
        }

        .table th {
            background: #f8f9fa;
            padding: 12px 8px;
            border-bottom: 2px solid #dee2e6;
            font-weight: 600;
            color: #333;
            white-space: nowrap;
        }

        .table td {
            padding: 10px 8px;
            border-bottom: 1px solid #dee2e6;
            vertical-align: middle;
        }

        .table tbody tr:hover {
            background-color: #f8f9fa;
        }

        .text-center {
            text-align: center;
        }

        .text-start {
            text-align: left;
        }

        .badge {
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 0.75rem;
            font-weight: 500;
        }

        .badge-berat {
            background: #ef4444;
            color: white;
        }

        .badge-sedang {
            background: #f59e0b;
            color: white;
        }

        .badge-ringan {
            background: #10b981;
            color: white;
        }

        .badge-aktif {
            background: #ef4444;
            color: white;
        }

        .badge-selesai {
            background: #10b981;
            color: white;
        }

        .badge-dialihkan {
            background: #f59e0b;
            color: white;
        }

        .badge-info {
            background: #17a2b8;
            color: white;
        }

        .badge-warning {
            background: #ffc107;
            color: #333;
        }

        .badge-secondary {
            background: #6c757d;
            color: white;
        }

        .no-data {
            text-align: center;
            padding: 40px;
            color: #6c757d;
        }

        .no-data i {
            font-size: 3rem;
            color: #dee2e6;
            margin-bottom: 10px;
        }

        .footer {
            margin-top: 30px;
            display: flex;
            gap: 10px;
            justify-content: center;
            flex-wrap: wrap;
        }

        .footer a {
            padding: 8px 16px;
            background: #6c757d;
            color: white;
            text-decoration: none;
            border-radius: 4px;
            display: inline-flex;
            align-items: center;
            gap: 5px;
            font-size: 0.875rem;
        }

        .footer a:hover {
            background: #5a6268;
        }

        .footer a.primary {
            background: #6366f1;
        }

        .footer a.primary:hover {
            background: #4f46e5;
        }

        .footer a.warning {
            background: #f59e0b;
        }

        .footer a.warning:hover {
            background: #e06b0c;
        }

        @media (max-width: 768px) {
            .filter-form {
                flex-direction: column;
            }
            
            .filter-group {
                width: 100%;
            }
            
            .stats-grid {
                grid-template-columns: 1fr;
            }
            
            .table {
                font-size: 0.8rem;
            }
        }
    </style>
</head>
<body>
    <!-- Header -->
    <div class="header">
        <div class="logo">
            <h2>
                <i class="fas fa-history"></i>
                Riwayat Pelanggaran
            </h2>
            <p><?= $nama_sekolah ?> | Wali Kelas: <?= htmlspecialchars($nama_wali) ?> (Kelas <?= $kelas_diampu ?>)</p>
        </div>
        
        <div class="user-info">
            <div class="user-avatar">
                <?= strtoupper(substr($nama_wali, 0, 1)) ?>
            </div>
            <div class="user-details">
                <div class="name"><?= htmlspecialchars($nama_wali) ?></div>
                <div class="role">Wali Kelas <?= $kelas_diampu ?></div>
            </div>
        </div>
    </div>

    <!-- Tombol Kembali -->
    <a href="dashboard_wali_kelas.php" class="btn-back">
        <i class="fas fa-arrow-left"></i> Kembali ke Dashboard
    </a>

    <!-- Filter Card -->
    <div class="filter-card">
        <form method="get" class="filter-form">
            <div class="filter-group">
                <label>Siswa</label>
                <select name="siswa_id" class="filter-control">
                    <option value="">Semua Siswa</option>
                    <?php foreach ($daftar_siswa as $siswa): ?>
                        <option value="<?= $siswa['id'] ?>" <?= $siswa_id == $siswa['id'] ? 'selected' : '' ?>>
                            <?= htmlspecialchars($siswa['nama']) ?> (<?= $siswa['nis'] ?>)
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div class="filter-group">
                <label>Status</label>
                <select name="status" class="filter-control">
                    <option value="">Semua Status</option>
                    <option value="Aktif" <?= $status == 'Aktif' ? 'selected' : '' ?>>Aktif</option>
                    <option value="Selesai" <?= $status == 'Selesai' ? 'selected' : '' ?>>Selesai</option>
                </select>
            </div>
            
            <div class="filter-group">
                <label>Dari Tanggal</label>
                <input type="date" name="dari_tanggal" class="filter-control" value="<?= $dari_tanggal ?>">
            </div>
            
            <div class="filter-group">
                <label>Sampai Tanggal</label>
                <input type="date" name="sampai_tanggal" class="filter-control" value="<?= $sampai_tanggal ?>">
            </div>
            
            <div class="filter-group" style="display: flex; gap: 10px;">
                <button type="submit" class="btn-filter">
                    <i class="fas fa-search"></i> Filter
                </button>
                <a href="riwayat_pelanggaran_wali.php" class="btn-reset">
                    <i class="fas fa-redo-alt"></i> Reset
                </a>
            </div>
            
            <div class="filter-group">
                <a href="cetak_riwayat_pelanggaran_wali.php?<?= http_build_query($_GET) ?>" target="_blank" class="btn-print">
                    <i class="fas fa-print"></i> Cetak PDF
                </a>
            </div>
        </form>
    </div>

    <!-- Statistik -->
    <div class="stats-grid">
        <div class="stat-card total">
            <div class="stat-number"><?= $total_pelanggaran ?></div>
            <div class="stat-label">Total Pelanggaran</div>
        </div>
        <div class="stat-card aktif">
            <div class="stat-number"><?= $pelanggaran_aktif ?></div>
            <div class="stat-label">Pelanggaran Aktif</div>
        </div>
        <div class="stat-card selesai">
            <div class="stat-number"><?= $pelanggaran_selesai ?></div>
            <div class="stat-label">Pelanggaran Selesai</div>
        </div>
        <div class="stat-card poin">
            <div class="stat-number"><?= $total_poin ?></div>
            <div class="stat-label">Total Poin</div>
        </div>
        <div class="stat-card berat">
            <div class="stat-number"><?= $berat ?></div>
            <div class="stat-label">Berat (≥50)</div>
        </div>
        <div class="stat-card sedang">
            <div class="stat-number"><?= $sedang ?></div>
            <div class="stat-label">Sedang (25-49)</div>
        </div>
        <div class="stat-card ringan">
            <div class="stat-number"><?= $ringan ?></div>
            <div class="stat-label">Ringan (<25)</div>
        </div>
    </div>

    <!-- Tabel Riwayat Pelanggaran -->
    <div class="card">
        <div class="card-header">
            <h3>
                <i class="fas fa-list"></i>
                Riwayat Pelanggaran Siswa
            </h3>
            <span class="badge badge-info"><?= count($riwayat_pelanggaran) ?> Data</span>
        </div>
        
        <div class="table-responsive">
            <table class="table" id="tablePelanggaran">
                <thead>
                    <tr>
                        <th>No</th>
                        <th>Tanggal</th>
                        <th>NIS</th>
                        <th>Nama Siswa</th>
                        <th>Jenis Pelanggaran</th>
                        <th>Keterangan</th>
                        <th>Poin</th>
                        <th>Klasifikasi</th>
                        <th>Status</th>
                        <th>Dialihkan</th>
                        <th>Pelapor</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (!empty($riwayat_pelanggaran)): ?>
                        <?php $no = 1; ?>
                        <?php foreach ($riwayat_pelanggaran as $p): 
                            // Klasifikasi
                            if ($p['poin'] >= 50) {
                                $klasifikasi = 'Berat';
                                $klasifikasiClass = 'badge-berat';
                            } elseif ($p['poin'] >= 25) {
                                $klasifikasi = 'Sedang';
                                $klasifikasiClass = 'badge-sedang';
                            } else {
                                $klasifikasi = 'Ringan';
                                $klasifikasiClass = 'badge-ringan';
                            }
                            
                            // Status
                            $statusClass = $p['status'] == 'Aktif' ? 'badge-aktif' : 'badge-selesai';
                            
                            // Dialihkan
                            $dialihkan = $p['status_alihkan'] == 'ya' ? '<span class="badge badge-dialihkan"><i class="fas fa-share-alt"></i> Ya</span>' : '-';
                            
                            // Pelapor
                            if ($p['guru_id']) {
                                $pelapor = '<span class="badge badge-info">Guru</span> ' . htmlspecialchars($p['guru_nama'] ?? '-');
                            } elseif ($p['wali_kelas_id']) {
                                $pelapor = '<span class="badge badge-warning">Wali</span> ' . htmlspecialchars($p['wali_nama'] ?? '-');
                            } else {
                                $pelapor = '<span class="badge badge-secondary">System</span>';
                            }
                        ?>
                        <tr>
                            <td class="text-center"><?= $no++ ?></td>
                            <td class="text-center"><?= date('d/m/Y', strtotime($p['tanggal'])) ?></td>
                            <td class="text-center"><?= htmlspecialchars($p['nis']) ?></td>
                            <td class="text-start"><?= htmlspecialchars($p['siswa_nama']) ?></td>
                            <td class="text-start"><?= htmlspecialchars($p['jenis_pelanggaran']) ?></td>
                            <td class="text-start" style="max-width: 200px;"><?= htmlspecialchars($p['keterangan']) ?></td>
                            <td class="text-center"><strong><?= $p['poin'] ?></strong></td>
                            <td class="text-center"><span class="badge <?= $klasifikasiClass ?>"><?= $klasifikasi ?></span></td>
                            <td class="text-center"><span class="badge <?= $statusClass ?>"><?= $p['status'] ?></span></td>
                            <td class="text-center"><?= $dialihkan ?></td>
                            <td class="text-center"><?= $pelapor ?></td>
                        </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="11" class="text-center py-5">
                                <i class="fas fa-folder-open fa-3x mb-3" style="color: #dee2e6;"></i>
                                <h4>Tidak Ada Data Pelanggaran</h4>
                                <p class="text-muted">Belum ada pelanggaran yang tercatat untuk kelas ini</p>
                            </td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <!-- Footer Navigation -->
    <div class="footer">
        <a href="dashboard_wali_kelas.php">
            <i class="fas fa-chart-pie"></i> Dashboard
        </a>
        <a href="pelanggaran_dialihkan.php" class="warning">
            <i class="fas fa-share-alt"></i> Pelanggaran Dialihkan
        </a>
        <a href="logout.php">
            <i class="fas fa-sign-out-alt"></i> Logout
        </a>
    </div>

    <!-- Scripts -->
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
    
    <script>
        $(document).ready(function() {
            // Inisialisasi DataTables hanya jika ada data
            <?php if (!empty($riwayat_pelanggaran)): ?>
                $('#tablePelanggaran').DataTable({
                    language: {
                        url: '//cdn.datatables.net/plug-ins/1.13.6/i18n/id.json'
                    },
                    order: [[1, 'desc']], // Urutkan berdasarkan Tanggal
                    pageLength: 25,
                    lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "Semua"]],
                    columnDefs: [
                        { targets: 0, width: '5%' },   // No
                        { targets: 1, width: '8%' },   // Tanggal
                        { targets: 2, width: '8%' },   // NIS
                        { targets: 3, width: '12%' },  // Nama
                        { targets: 4, width: '12%' },  // Jenis
                        { targets: 5, width: '15%' },  // Keterangan
                        { targets: 6, width: '5%' },   // Poin
                        { targets: 7, width: '8%' },   // Klasifikasi
                        { targets: 8, width: '8%' },   // Status
                        { targets: 9, width: '7%' },   // Dialihkan
                        { targets: 10, width: '12%' }  // Pelapor
                    ]
                });
            <?php endif; ?>
        });
    </script>
</body>
</html>