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

// Koneksi database
require_once 'config.php';

// Ambil data guru piket yang login
$username = $_SESSION['username'];
$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);
} else {
    // Coba dari tabel users
    $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 = [
            'id' => $_SESSION['guru_id'] ?? 0,
            'nama' => $user['nama'] ?? $username,
            'nip' => $username,
            'mapel' => 'Guru Piket',
            'status' => 'aktif'
        ];
    } else {
        $guru = [
            'id' => $_SESSION['guru_id'] ?? 0,
            'nama' => $_SESSION['nama_guru'] ?? $_SESSION['nama'] ?? $username,
            'nip' => $username,
            'mapel' => 'Guru Piket',
            'status' => 'aktif'
        ];
    }
}

// Fungsi untuk mendapatkan statistik pelanggaran
function getStatistikPelanggaran($conn) {
    $statistik = [
        'total_pelanggaran' => 0,
        'pelanggaran_aktif' => 0,
        'pelanggaran_selesai' => 0,
        'pelanggaran_hari_ini' => 0,
        'total_poin' => 0,
        'alihkan_ke_walas' => 0,
        'dengan_bukti_foto' => 0,
        'tanpa_bukti' => 0,
        'siswa_terlibat' => 0,
        'pelanggaran_berat' => 0,
        'pelanggaran_sedang' => 0,
        'pelanggaran_ringan' => 0
    ];

    $hari_ini = date('Y-m-d');

    // Cek apakah tabel pelanggaran ada
    $check_table = mysqli_query($conn, "SHOW TABLES LIKE 'pelanggaran'");
    if (!$check_table || mysqli_num_rows($check_table) == 0) {
        return $statistik;
    }

    // Total pelanggaran
    $query = "SELECT COUNT(*) as total FROM pelanggaran";
    $result = mysqli_query($conn, $query);
    if ($result && $row = mysqli_fetch_assoc($result)) {
        $statistik['total_pelanggaran'] = (int)$row['total'];
    }

    // Pelanggaran aktif
    $query = "SELECT COUNT(*) as total FROM pelanggaran WHERE status = 'Aktif'";
    $result = mysqli_query($conn, $query);
    if ($result && $row = mysqli_fetch_assoc($result)) {
        $statistik['pelanggaran_aktif'] = (int)$row['total'];
    }

    // Pelanggaran selesai
    $query = "SELECT COUNT(*) as total FROM pelanggaran WHERE status = 'Selesai'";
    $result = mysqli_query($conn, $query);
    if ($result && $row = mysqli_fetch_assoc($result)) {
        $statistik['pelanggaran_selesai'] = (int)$row['total'];
    }

    // Pelanggaran hari ini
    $query = "SELECT COUNT(*) as total FROM pelanggaran WHERE tanggal = '$hari_ini'";
    $result = mysqli_query($conn, $query);
    if ($result && $row = mysqli_fetch_assoc($result)) {
        $statistik['pelanggaran_hari_ini'] = (int)$row['total'];
    }

    // Total poin pelanggaran
    $query = "SELECT SUM(poin) as total FROM pelanggaran";
    $result = mysqli_query($conn, $query);
    if ($result && $row = mysqli_fetch_assoc($result)) {
        $statistik['total_poin'] = (int)($row['total'] ?? 0);
    }

    // Pelanggaran yang dialihkan ke wali kelas
    $query = "SELECT COUNT(*) as total FROM pelanggaran WHERE status_alihkan = 'ya'";
    $result = mysqli_query($conn, $query);
    if ($result && $row = mysqli_fetch_assoc($result)) {
        $statistik['alihkan_ke_walas'] = (int)$row['total'];
    }

    // Pelanggaran dengan bukti foto
    $query = "SELECT COUNT(*) as total FROM pelanggaran WHERE bukti_foto IS NOT NULL AND bukti_foto != ''";
    $result = mysqli_query($conn, $query);
    if ($result && $row = mysqli_fetch_assoc($result)) {
        $statistik['dengan_bukti_foto'] = (int)$row['total'];
    }

    // Pelanggaran tanpa bukti foto
    $statistik['tanpa_bukti'] = $statistik['total_pelanggaran'] - $statistik['dengan_bukti_foto'];

    // Jumlah siswa yang terlibat pelanggaran
    $query = "SELECT COUNT(DISTINCT siswa_id) as total FROM pelanggaran";
    $result = mysqli_query($conn, $query);
    if ($result && $row = mysqli_fetch_assoc($result)) {
        $statistik['siswa_terlibat'] = (int)$row['total'];
    }

    // Klasifikasi berdasarkan poin
    $query = "SELECT 
                SUM(CASE WHEN poin >= 50 THEN 1 ELSE 0 END) as berat,
                SUM(CASE WHEN poin >= 25 AND poin < 50 THEN 1 ELSE 0 END) as sedang,
                SUM(CASE WHEN poin < 25 THEN 1 ELSE 0 END) as ringan
              FROM pelanggaran";
    $result = mysqli_query($conn, $query);
    if ($result && $row = mysqli_fetch_assoc($result)) {
        $statistik['pelanggaran_berat'] = (int)($row['berat'] ?? 0);
        $statistik['pelanggaran_sedang'] = (int)($row['sedang'] ?? 0);
        $statistik['pelanggaran_ringan'] = (int)($row['ringan'] ?? 0);
    }

    return $statistik;
}

// Fungsi untuk mendapatkan aktivitas terbaru
function getAktivitasTerbaru($conn, $limit = 5) {
    $aktivitas = [];
    
    // Cek tabel pelanggaran
    $check_table = mysqli_query($conn, "SHOW TABLES LIKE 'pelanggaran'");
    if (!$check_table || mysqli_num_rows($check_table) == 0) {
        return $aktivitas;
    }
    
    // Cek tabel siswa
    $check_siswa = mysqli_query($conn, "SHOW TABLES LIKE 'siswa'");
    if (!$check_siswa || mysqli_num_rows($check_siswa) == 0) {
        return $aktivitas;
    }
    
    $query = "SELECT 
                p.id, 
                p.tanggal, 
                p.created_at,
                p.jenis_pelanggaran,
                p.status,
                p.tindakan,
                s.nama as nama_siswa,
                s.kelas
              FROM pelanggaran p 
              LEFT JOIN siswa s ON p.siswa_id = s.id 
              WHERE p.created_at IS NOT NULL
              ORDER BY p.created_at DESC
              LIMIT $limit";
    
    $result = mysqli_query($conn, $query);
    if ($result) {
        while ($row = mysqli_fetch_assoc($result)) {
            $aktivitas[] = $row;
        }
    }
    
    return $aktivitas;
}

// Fungsi untuk mendapatkan statistik per kelas
function getStatistikKelas($conn) {
    $kelas_data = [];
    
    // Cek tabel yang diperlukan
    $check_siswa = mysqli_query($conn, "SHOW TABLES LIKE 'siswa'");
    $check_pelanggaran = mysqli_query($conn, "SHOW TABLES LIKE 'pelanggaran'");
    
    if (!$check_siswa || mysqli_num_rows($check_siswa) == 0 || 
        !$check_pelanggaran || mysqli_num_rows($check_pelanggaran) == 0) {
        return $kelas_data;
    }
    
    $query = "SELECT s.kelas, COUNT(p.id) as jumlah, COALESCE(SUM(p.poin), 0) as total_poin
              FROM siswa s
              LEFT JOIN pelanggaran p ON s.id = p.siswa_id
              WHERE s.status = 'aktif' AND s.kelas IS NOT NULL AND s.kelas != ''
              GROUP BY s.kelas
              ORDER BY jumlah DESC
              LIMIT 5";
    
    $result = mysqli_query($conn, $query);
    if ($result) {
        while ($row = mysqli_fetch_assoc($result)) {
            $kelas_data[] = $row;
        }
    }
    
    return $kelas_data;
}

// Ambil statistik
$statistik = getStatistikPelanggaran($conn);

// Ambil daftar pelanggaran terbaru
$pelanggaran_terbaru = [];
$query_pelanggaran = "SELECT p.*, s.nama as nama_siswa, s.kelas, s.nisn
                      FROM pelanggaran p 
                      LEFT JOIN siswa s ON p.siswa_id = s.id 
                      ORDER BY p.tanggal DESC, p.created_at DESC 
                      LIMIT 10";
$result_pelanggaran = mysqli_query($conn, $query_pelanggaran);
if ($result_pelanggaran) {
    while ($row = mysqli_fetch_assoc($result_pelanggaran)) {
        $pelanggaran_terbaru[] = $row;
    }
}

// Ambil aktivitas terbaru
$aktivitas = getAktivitasTerbaru($conn, 7);

// Ambil statistik per kelas
$statistik_kelas = getStatistikKelas($conn);
?>
<!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Dashboard Guru Piket - Sistem Pelanggaran Siswa</title>
  <!-- Bootstrap 5 -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
  <!-- Font Awesome -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css">
  <!-- Google Fonts -->
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
  <!-- DataTables -->
  <link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">
  <style>
    :root {
      --primary: #10b981;
      --primary-dark: #059669;
      --secondary: #f59e0b;
      --danger: #ef4444;
      --info: #3b82f6;
      --dark: #1f2937;
      --light: #f8fafc;
    }
    
    body {
      font-family: 'Inter', sans-serif;
      background: #f3f4f6;
      color: #333;
    }
    
    /* Header */
    .header {
      background: linear-gradient(135deg, #10b981 0%, #34d399 100%);
      color: white;
      padding: 1rem 2rem;
      box-shadow: 0 4px 12px rgba(0,0,0,0.1);
    }
    
    .header-content {
      max-width: 1400px;
      margin: 0 auto;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .user-info {
      background: rgba(255,255,255,0.2);
      padding: 0.5rem 1.5rem;
      border-radius: 50px;
      display: flex;
      align-items: center;
      gap: 1rem;
    }
    
    .user-avatar {
      width: 40px;
      height: 40px;
      background: rgba(255,255,255,0.3);
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    
    /* Dashboard Container */
    .dashboard-container {
      max-width: 1400px;
      margin: 0 auto;
      padding: 2rem;
    }
    
    /* Welcome Banner */
    .welcome-banner {
      background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
      color: white;
      padding: 2rem;
      border-radius: 16px;
      margin-bottom: 2rem;
      position: relative;
    }
    
    .date-badge {
      position: absolute;
      top: 1rem;
      right: 1rem;
      background: rgba(255,255,255,0.2);
      padding: 0.5rem 1rem;
      border-radius: 20px;
      font-size: 0.85rem;
    }
    
    /* Stats Grid */
    .stats-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
      gap: 1.5rem;
      margin-bottom: 2rem;
    }
    
    .stat-card {
      background: white;
      border-radius: 16px;
      padding: 1.5rem;
      box-shadow: 0 4px 12px rgba(0,0,0,0.05);
      display: flex;
      align-items: center;
      gap: 1rem;
      border-left: 4px solid var(--primary);
    }
    
    .stat-icon {
      width: 60px;
      height: 60px;
      border-radius: 12px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 1.75rem;
      color: white;
      background: var(--primary);
    }
    
    .stat-number {
      font-size: 2rem;
      font-weight: 700;
      line-height: 1;
    }
    
    .stat-label {
      font-size: 0.9rem;
      color: #6b7280;
    }
    
    /* Menu Grid (Quick Actions yang diubah) */
    .menu-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
      gap: 1rem;
      margin-bottom: 2rem;
    }
    
    .menu-card {
      background: white;
      border-radius: 16px;
      padding: 1.5rem 1rem;
      box-shadow: 0 4px 12px rgba(0,0,0,0.05);
      transition: all 0.3s;
      text-align: center;
      text-decoration: none;
      color: #333;
      display: block;
      border: 1px solid transparent;
    }
    
    .menu-card:hover {
      transform: translateY(-5px);
      box-shadow: 0 12px 24px rgba(0,0,0,0.15);
      border-color: var(--primary);
    }
    
    .menu-icon {
      width: 60px;
      height: 60px;
      border-radius: 30px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 1.5rem;
      color: white;
      margin: 0 auto 1rem;
    }
    
    .menu-title {
      font-size: 1rem;
      font-weight: 600;
      margin-bottom: 0.25rem;
    }
    
    .menu-desc {
      font-size: 0.8rem;
      color: #6b7280;
    }
    
    /* Cards */
    .chart-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
      gap: 1.5rem;
      margin-bottom: 2rem;
    }
    
    .chart-card, .table-card {
      background: white;
      border-radius: 16px;
      box-shadow: 0 4px 12px rgba(0,0,0,0.05);
      overflow: hidden;
    }
    
    .chart-header, .table-header {
      padding: 1rem 1.5rem;
      border-bottom: 1px solid #e5e7eb;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .chart-body {
      padding: 1.5rem;
      height: 300px;
    }
    
    .table-container {
      padding: 1.5rem;
    }
    
    /* Badges */
    .badge {
      padding: 0.25rem 0.75rem;
      border-radius: 20px;
      font-size: 0.75rem;
      font-weight: 600;
    }
    
    .badge-aktif {
      background: #fee2e2;
      color: #ef4444;
    }
    
    .badge-selesai {
      background: #d1fae5;
      color: #10b981;
    }
    
    /* Footer */
    .footer {
      background: #1f2937;
      color: white;
      padding: 1.5rem;
      margin-top: 3rem;
    }
    
    .footer-content {
      max-width: 1400px;
      margin: 0 auto;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .footer-links a {
      color: white;
      text-decoration: none;
      margin: 0 0.75rem;
      opacity: 0.8;
    }
    
    .footer-links a:hover {
      opacity: 1;
    }
    
    /* Responsive */
    @media (max-width: 768px) {
      .header-content {
        flex-direction: column;
        gap: 1rem;
      }
      
      .dashboard-container {
        padding: 1rem;
      }
      
      .stats-grid {
        grid-template-columns: 1fr;
      }
      
      .menu-grid {
        grid-template-columns: 1fr;
      }
      
      .chart-grid {
        grid-template-columns: 1fr;
      }
      
      .footer-content {
        flex-direction: column;
        gap: 1rem;
      }
    }
  </style>
</head>
<body>
  <!-- Header -->
  <header class="header">
    <div class="header-content">
      <div class="logo-section">
        <h1><i class="fas fa-shield-alt me-2"></i>Dashboard Guru Piket</h1>
        <div class="small">Sistem Pelanggaran Siswa</div>
      </div>
      <div class="user-info">
        <div class="user-avatar">
          <i class="fas fa-user-clock"></i>
        </div>
        <div>
          <div class="fw-bold"><?php echo htmlspecialchars($guru['nama']); ?></div>
          <small>NIP: <?php echo htmlspecialchars($guru['nip']); ?></small>
        </div>
      </div>
    </div>
  </header>

  <!-- Main Content -->
  <div class="dashboard-container">
    <!-- Welcome Banner -->
    <div class="welcome-banner">
      <h2>Assalamu'alaikum, <?php echo htmlspecialchars(explode(' ', $guru['nama'])[0]); ?>!</h2>
      <p>Selamat bertugas sebagai Guru Piket. Pantau dan tangani pelanggaran siswa.</p>
      <div class="date-badge">
        <i class="fas fa-calendar-alt me-2"></i><?php echo date('l, d F Y'); ?>
      </div>
    </div>

    <!-- Statistik Utama -->
    <h3 class="mb-3"><i class="fas fa-chart-pie me-2" style="color: #10b981;"></i>Statistik Pelanggaran</h3>
    <div class="stats-grid">
      <div class="stat-card" style="border-left-color: #10b981;">
        <div class="stat-icon" style="background: #10b981;">
          <i class="fas fa-exclamation-triangle"></i>
        </div>
        <div>
          <div class="stat-number"><?php echo number_format($statistik['total_pelanggaran']); ?></div>
          <div class="stat-label">Total Pelanggaran</div>
        </div>
      </div>
      
      <div class="stat-card" style="border-left-color: #f59e0b;">
        <div class="stat-icon" style="background: #f59e0b;">
          <i class="fas fa-clock"></i>
        </div>
        <div>
          <div class="stat-number"><?php echo number_format($statistik['pelanggaran_aktif']); ?></div>
          <div class="stat-label">Pelanggaran Aktif</div>
        </div>
      </div>
      
      <div class="stat-card" style="border-left-color: #8b5cf6;">
        <div class="stat-icon" style="background: #8b5cf6;">
          <i class="fas fa-check-circle"></i>
        </div>
        <div>
          <div class="stat-number"><?php echo number_format($statistik['pelanggaran_selesai']); ?></div>
          <div class="stat-label">Selesai Ditangani</div>
        </div>
      </div>
      
      <div class="stat-card" style="border-left-color: #3b82f6;">
        <div class="stat-icon" style="background: #3b82f6;">
          <i class="fas fa-calendar-day"></i>
        </div>
        <div>
          <div class="stat-number"><?php echo number_format($statistik['pelanggaran_hari_ini']); ?></div>
          <div class="stat-label">Hari Ini</div>
        </div>
      </div>
      
      <div class="stat-card" style="border-left-color: #ef4444;">
        <div class="stat-icon" style="background: #ef4444;">
          <i class="fas fa-weight-hanging"></i>
        </div>
        <div>
          <div class="stat-number"><?php echo number_format($statistik['total_poin']); ?></div>
          <div class="stat-label">Total Poin</div>
        </div>
      </div>
      
      <div class="stat-card" style="border-left-color: #ec4899;">
        <div class="stat-icon" style="background: #ec4899;">
          <i class="fas fa-user-shield"></i>
        </div>
        <div>
          <div class="stat-number"><?php echo number_format($statistik['alihkan_ke_walas']); ?></div>
          <div class="stat-label">Dialihkan ke Walas</div>
        </div>
      </div>
    </div>

    <!-- Statistik Detail -->
    <div class="stats-grid" style="grid-template-columns: repeat(4, 1fr);">
      <div class="stat-card" style="border-left-color: #10b981;">
        <div class="stat-icon" style="background: #10b981; width: 45px; height: 45px; font-size: 1.25rem;">
          <i class="fas fa-camera"></i>
        </div>
        <div>
          <div class="stat-number" style="font-size: 1.5rem;"><?php echo $statistik['dengan_bukti_foto']; ?></div>
          <div class="stat-label">Dengan Bukti</div>
        </div>
      </div>
      
      <div class="stat-card" style="border-left-color: #6b7280;">
        <div class="stat-icon" style="background: #6b7280; width: 45px; height: 45px; font-size: 1.25rem;">
          <i class="fas fa-times-circle"></i>
        </div>
        <div>
          <div class="stat-number" style="font-size: 1.5rem;"><?php echo $statistik['tanpa_bukti']; ?></div>
          <div class="stat-label">Tanpa Bukti</div>
        </div>
      </div>
      
      <div class="stat-card" style="border-left-color: #8b5cf6;">
        <div class="stat-icon" style="background: #8b5cf6; width: 45px; height: 45px; font-size: 1.25rem;">
          <i class="fas fa-users"></i>
        </div>
        <div>
          <div class="stat-number" style="font-size: 1.5rem;"><?php echo $statistik['siswa_terlibat']; ?></div>
          <div class="stat-label">Siswa Terlibat</div>
        </div>
      </div>
      
      <div class="stat-card" style="border-left-color: #f59e0b;">
        <div class="stat-icon" style="background: #f59e0b; width: 45px; height: 45px; font-size: 1.25rem;">
          <i class="fas fa-balance-scale"></i>
        </div>
        <div>
          <div class="stat-number" style="font-size: 1.5rem;"><?php echo $statistik['pelanggaran_berat']; ?></div>
          <div class="stat-label">Pelanggaran Berat</div>
        </div>
      </div>
    </div>

    <!-- MENU MENU (sebelumnya Aksi Cepat) -->
    <h3 class="mb-3 mt-4"><i class="fas fa-bolt me-2" style="color: #f59e0b;"></i>Menu Menu</h3>
    <div class="menu-grid">
      <a href="laporkan_pelanggaran.php" class="menu-card">
        <div class="menu-icon" style="background: #ef4444;">
          <i class="fas fa-camera"></i>
        </div>
        <div class="menu-title">Laporkan Pelanggaran</div>
        <div class="menu-desc">Dengan bukti foto</div>
      </a>
      
      <a href="penanganan_pelanggaran.php" class="menu-card">
        <div class="menu-icon" style="background: #10b981;">
          <i class="fas fa-hand-holding-heart"></i>
        </div>
        <div class="menu-title">Penanganan Pelanggaran</div>
        <div class="menu-desc">Tindak lanjuti</div>
      </a>
      
      <a href="rekap_pelanggaran.php" class="menu-card">
        <div class="menu-icon" style="background: #3b82f6;">
          <i class="fas fa-print"></i>
        </div>
        <div class="menu-title">Rekap & Cetak</div>
        <div class="menu-desc">Cetak laporan</div>
      </a>
      
      <a href="semua_pelanggaran.php" class="menu-card">
        <div class="menu-icon" style="background: #8b5cf6;">
          <i class="fas fa-list"></i>
        </div>
        <div class="menu-title">Semua Pelanggaran</div>
        <div class="menu-desc">Lihat daftar</div>
      </a>
      
      <a href="statistik_pelanggaran.php" class="menu-card">
        <div class="menu-icon" style="background: #6b7280;">
          <i class="fas fa-chart-bar"></i>
        </div>
        <div class="menu-title">Statistik Lengkap</div>
        <div class="menu-desc">Analisis data</div>
      </a>
      
      <!-- Menu Logout -->
      <a href="logout.php" class="menu-card">
        <div class="menu-icon" style="background: #ef4444;">
          <i class="fas fa-sign-out-alt"></i>
        </div>
        <div class="menu-title">Logout</div>
        <div class="menu-desc">Keluar dari sistem</div>
      </a>
    </div>

    <!-- Grafik -->
    <div class="chart-grid">
      <div class="chart-card">
        <div class="chart-header">
          <h5 class="mb-0"><i class="fas fa-chart-pie me-2" style="color: #10b981;"></i>Klasifikasi Pelanggaran</h5>
          <span class="badge bg-secondary">Berdasarkan Poin</span>
        </div>
        <div class="chart-body">
          <canvas id="chartKlasifikasi"></canvas>
        </div>
      </div>
      
      <div class="chart-card">
        <div class="chart-header">
          <h5 class="mb-0"><i class="fas fa-chart-bar me-2" style="color: #3b82f6;"></i>Status Penanganan</h5>
          <span class="badge bg-secondary">Aktif vs Selesai</span>
        </div>
        <div class="chart-body">
          <canvas id="chartStatus"></canvas>
        </div>
      </div>
    </div>

    <!-- Tabel Pelanggaran Terbaru -->
    <div class="table-card">
      <div class="table-header">
        <h5 class="mb-0"><i class="fas fa-history me-2" style="color: #f59e0b;"></i>Pelanggaran Terbaru</h5>
        <div>
          <a href="semua_pelanggaran.php" class="btn btn-outline-secondary btn-sm">Lihat Semua</a>
          <a href="laporkan_pelanggaran.php" class="btn btn-primary btn-sm ms-2">Tambah</a>
        </div>
      </div>
      <div class="table-container">
        <div class="table-responsive">
          <table class="table table-hover" id="tablePelanggaran">
            <thead>
              <tr>
                <th>No</th>
                <th>Tanggal</th>
                <th>NISN</th>
                <th>Nama Siswa</th>
                <th>Kelas</th>
                <th>Jenis Pelanggaran</th>
                <th>Poin</th>
                <th>Status</th>
                <th>Bukti</th>
                <th>Aksi</th>
              </tr>
            </thead>
            <tbody>
              <?php if (!empty($pelanggaran_terbaru)): ?>
                <?php $no = 1; ?>
                <?php foreach ($pelanggaran_terbaru as $row): ?>
                <tr>
                  <td><?php echo $no++; ?></td>
                  <td><?php echo date('d/m/Y', strtotime($row['tanggal'])); ?></td>
                  <td><?php echo htmlspecialchars($row['nisn'] ?? '-'); ?></td>
                  <td><strong><?php echo htmlspecialchars($row['nama_siswa'] ?? '-'); ?></strong></td>
                  <td><?php echo htmlspecialchars($row['kelas'] ?? '-'); ?></td>
                  <td><?php echo htmlspecialchars($row['jenis_pelanggaran']); ?></td>
                  <td>
                    <span class="badge" style="background: <?php echo ($row['poin'] >= 50) ? '#ef4444' : (($row['poin'] >= 25) ? '#f59e0b' : '#10b981'); ?>; color: white;">
                      <?php echo $row['poin']; ?>
                    </span>
                  </td>
                  <td>
                    <?php if ($row['status'] == 'Aktif'): ?>
                      <span class="badge badge-aktif"><i class="fas fa-clock"></i> Aktif</span>
                    <?php else: ?>
                      <span class="badge badge-selesai"><i class="fas fa-check"></i> Selesai</span>
                    <?php endif; ?>
                  </td>
                  <td class="text-center">
                    <?php if (!empty($row['bukti_foto'])): ?>
                      <a href="<?php echo $row['bukti_foto']; ?>" target="_blank" class="btn btn-sm btn-outline-info" title="Lihat Bukti">
                        <i class="fas fa-image"></i>
                      </a>
                    <?php else: ?>
                      <span class="badge bg-secondary">-</span>
                    <?php endif; ?>
                  </td>
                  <td>
                    <div class="d-flex gap-1">
                      <a href="detail_pelanggaran.php?id=<?php echo $row['id']; ?>" class="btn btn-sm btn-outline-secondary" title="Detail">
                        <i class="fas fa-eye"></i>
                      </a>
                      <?php if ($row['status'] == 'Aktif'): ?>
                        <a href="penanganan_pelanggaran.php?id=<?php echo $row['id']; ?>" class="btn btn-sm btn-outline-success" title="Tangani">
                          <i class="fas fa-hand-holding-heart"></i>
                        </a>
                      <?php endif; ?>
                    </div>
                  </td>
                </tr>
                <?php endforeach; ?>
              <?php else: ?>
                <tr>
                  <td colspan="10" class="text-center py-4">
                    <i class="fas fa-check-circle" style="color: #10b981; font-size: 2rem; margin-bottom: 0.5rem; display: block;"></i>
                    Belum ada data pelanggaran
                  </td>
                </tr>
              <?php endif; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>

    <!-- Aktivitas Terbaru & Statistik Kelas -->
    <div class="row mt-4">
      <div class="col-md-6">
        <div class="table-card">
          <div class="table-header">
            <h5 class="mb-0"><i class="fas fa-bell me-2" style="color: #8b5cf6;"></i>Aktivitas Terbaru</h5>
          </div>
          <div class="table-container">
            <?php if (!empty($aktivitas)): ?>
              <ul class="list-unstyled">
                <?php foreach ($aktivitas as $akt): ?>
                <li class="mb-3 pb-2 border-bottom">
                  <div class="d-flex gap-3">
                    <div class="rounded-circle p-2" style="background: <?php echo (!empty($akt['tindakan'])) ? '#10b981' : '#ef4444'; ?>; color: white; width: 32px; height: 32px; display: flex; align-items: center; justify-content: center;">
                      <i class="fas fa-<?php echo (!empty($akt['tindakan'])) ? 'check' : 'exclamation'; ?>"></i>
                    </div>
                    <div>
                      <strong><?php echo htmlspecialchars($akt['nama_siswa'] ?? 'Siswa'); ?></strong> (<?php echo htmlspecialchars($akt['kelas'] ?? '-'); ?>)
                      <div class="small text-muted">
                        <?php if (!empty($akt['tindakan'])): ?>
                          Menangani: <?php echo htmlspecialchars($akt['jenis_pelanggaran']); ?>
                        <?php else: ?>
                          Melaporkan: <?php echo htmlspecialchars($akt['jenis_pelanggaran']); ?>
                        <?php endif; ?>
                      </div>
                      <div class="small text-muted">
                        <i class="fas fa-clock me-1"></i>
                        <?php 
                        if (!empty($akt['created_at'])) {
                            $waktu = strtotime($akt['created_at']);
                            $selisih = time() - $waktu;
                            if ($selisih < 60) echo "Baru saja";
                            elseif ($selisih < 3600) echo floor($selisih/60) . " menit lalu";
                            elseif ($selisih < 86400) echo floor($selisih/3600) . " jam lalu";
                            else echo date('d/m/Y H:i', $waktu);
                        }
                        ?>
                      </div>
                    </div>
                  </div>
                </li>
                <?php endforeach; ?>
              </ul>
            <?php else: ?>
              <p class="text-center py-3">Belum ada aktivitas</p>
            <?php endif; ?>
          </div>
        </div>
      </div>
      
      <div class="col-md-6">
        <div class="table-card">
          <div class="table-header">
            <h5 class="mb-0"><i class="fas fa-chart-bar me-2" style="color: #f59e0b;"></i>Top 5 Kelas</h5>
          </div>
          <div class="table-container">
            <?php if (!empty($statistik_kelas)): ?>
              <table class="table">
                <thead>
                  <tr>
                    <th>Kelas</th>
                    <th>Jumlah</th>
                    <th>Total Poin</th>
                    <th>Grafik</th>
                  </tr>
                </thead>
                <tbody>
                  <?php 
                  $max_jumlah = 0;
                  foreach ($statistik_kelas as $row) {
                      if ($row['jumlah'] > $max_jumlah) $max_jumlah = $row['jumlah'];
                  }
                  foreach ($statistik_kelas as $row): 
                  $persen = ($max_jumlah > 0) ? ($row['jumlah'] / $max_jumlah * 100) : 0;
                  ?>
                  <tr>
                    <td><strong>Kelas <?php echo htmlspecialchars($row['kelas']); ?></strong></td>
                    <td><?php echo $row['jumlah']; ?> kasus</td>
                    <td><?php echo $row['total_poin'] ?? 0; ?> poin</td>
                    <td style="width: 150px;">
                      <div class="progress" style="height: 8px;">
                        <div class="progress-bar bg-success" style="width: <?php echo $persen; ?>%;"></div>
                      </div>
                    </td>
                  </tr>
                  <?php endforeach; ?>
                </tbody>
              </table>
            <?php else: ?>
              <p class="text-center py-3">Belum ada data kelas</p>
            <?php endif; ?>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- Footer -->
  <footer class="footer">
    <div class="footer-content">
      <div>Versi 4.00 | Sistem Pelanggaran Siswa</div>
      <div class="footer-links">
        <a href="tentang.php"><i class="fas fa-info-circle"></i> Tentang</a>
        <a href="bantuan.php"><i class="fas fa-question-circle"></i> Bantuan</a>
        <a href="kontak.php"><i class="fas fa-phone"></i> Kontak</a>
      </div>
    </div>
  </footer>

  <!-- 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 src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
  
  <script>
    $(document).ready(function() {
      // Inisialisasi DataTable dengan pengecekan data
      if ($('#tablePelanggaran tbody tr').length > 1 || ($('#tablePelanggaran tbody tr').length === 1 && $('#tablePelanggaran tbody tr td').length === 10)) {
        $('#tablePelanggaran').DataTable({
          pageLength: 10,
          lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "Semua"]],
          language: {
            url: '//cdn.datatables.net/plug-ins/1.13.6/i18n/id.json'
          },
          order: [[1, 'desc']],
          columnDefs: [
            { targets: 0, width: '5%' },
            { targets: 1, width: '10%' },
            { targets: 2, width: '10%' },
            { targets: 3, width: '15%' },
            { targets: 4, width: '5%' },
            { targets: 5, width: '15%' },
            { targets: 6, width: '5%' },
            { targets: 7, width: '8%' },
            { targets: 8, width: '5%' },
            { targets: 9, width: '15%' }
          ],
          responsive: true
        });
      }
    });

    // Chart Klasifikasi
    const ctx1 = document.getElementById('chartKlasifikasi')?.getContext('2d');
    if (ctx1) {
      new Chart(ctx1, {
        type: 'doughnut',
        data: {
          labels: ['Berat (≥50)', 'Sedang (25-49)', 'Ringan (<25)'],
          datasets: [{
            data: [
              <?php echo $statistik['pelanggaran_berat']; ?>,
              <?php echo $statistik['pelanggaran_sedang']; ?>,
              <?php echo $statistik['pelanggaran_ringan']; ?>
            ],
            backgroundColor: ['#ef4444', '#f59e0b', '#10b981'],
            borderWidth: 0
          }]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          plugins: {
            legend: { position: 'bottom' }
          }
        }
      });
    }

    // Chart Status
    const ctx2 = document.getElementById('chartStatus')?.getContext('2d');
    if (ctx2) {
      new Chart(ctx2, {
        type: 'bar',
        data: {
          labels: ['Aktif', 'Selesai'],
          datasets: [{
            data: [
              <?php echo $statistik['pelanggaran_aktif']; ?>,
              <?php echo $statistik['pelanggaran_selesai']; ?>
            ],
            backgroundColor: ['#f59e0b', '#10b981'],
            borderRadius: 8
          }]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          plugins: { legend: { display: false } },
          scales: {
            y: { beginAtZero: true }
          }
        }
      });
    }
  </script>
</body>
</html>