<?php
session_start();
include 'config.php';

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

$username = $_SESSION['username'];

// Ambil data wali kelas
$qWaliKelas = mysqli_query($conn, "SELECT kelas, nama_wali FROM wali_kelas WHERE nip_wali='$username'");
if (!$qWaliKelas || mysqli_num_rows($qWaliKelas) === 0) {
    die("Data wali kelas tidak ditemukan.");
}
$wali_kelas = mysqli_fetch_assoc($qWaliKelas);
$kelas_diampu = $wali_kelas['kelas'];

// Ambil guru_id dari wali kelas
$qGuru = mysqli_query($conn, "SELECT id FROM guru WHERE nip='$username'");
$guru = mysqli_fetch_assoc($qGuru);
$guru_id = $guru['id'] ?? null;

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_pelanggaran'])) {
    $siswa_id = intval($_POST['siswa_id']);
    $tanggal = mysqli_real_escape_string($conn, $_POST['tanggal']);
    $jenis_pelanggaran = mysqli_real_escape_string($conn, $_POST['jenis_pelanggaran']);
    $keterangan = mysqli_real_escape_string($conn, $_POST['keterangan']);
    $poin = intval($_POST['poin']);
    $created_at = date('Y-m-d H:i:s');

    $query = "INSERT INTO pelanggaran (siswa_id, guru_id, tanggal, jenis_pelanggaran, keterangan, poin, status, created_at) 
              VALUES ($siswa_id, " . ($guru_id ?: 'NULL') . ", '$tanggal', '$jenis_pelanggaran', '$keterangan', $poin, 'Aktif', '$created_at')";
    
    if (mysqli_query($conn, $query)) {
        $success = "Pelanggaran berhasil dicatat!";
        // Refresh data setelah input berhasil
        header("Location: input_pelanggaran.php");
        exit;
    } else {
        $error = "Gagal mencatat pelanggaran: " . mysqli_error($conn);
    }
}

// Ambil daftar siswa di kelas
$qSiswa = mysqli_query($conn, "
    SELECT id, nama, nis 
    FROM siswa 
    WHERE kelas = '$kelas_diampu' 
    AND status = 'aktif'
    ORDER BY nama
");

$daftar_siswa = [];
if ($qSiswa) {
    while ($row = mysqli_fetch_assoc($qSiswa)) {
        $daftar_siswa[] = $row;
    }
}

// Ambil riwayat pelanggaran terbaru
$qRiwayat = mysqli_query($conn, "
    SELECT p.*, s.nama as siswa_nama, s.nis, g.nama as guru_nama 
    FROM pelanggaran p 
    JOIN siswa s ON p.siswa_id = s.id 
    LEFT JOIN guru g ON p.guru_id = g.id 
    WHERE s.kelas = '$kelas_diampu' 
    ORDER BY p.created_at DESC 
    LIMIT 50
");

$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';
}));
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pelanggaran Siswa - Sistem Absensi QR</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f8f9fa;
            color: #333333;
            line-height: 1.6;
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 20px;
        }

        .header {
            background: #ffffff;
            color: #333;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            border-left: 4px solid #dc3545;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }

        .header h1 {
            font-size: 1.5rem;
            margin-bottom: 5px;
            font-weight: 600;
        }

        .header p {
            font-size: 0.9rem;
            color: #6c757d;
            margin-bottom: 0;
        }

        .btn-back {
            padding: 6px 12px;
            background: #6c757d;
            color: #fff;
            text-decoration: none;
            border-radius: 4px;
            margin-bottom: 15px;
            display: inline-flex;
            align-items: center;
            gap: 5px;
            font-size: 0.875rem;
            transition: background 0.3s;
        }

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

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

        .stat-card {
            background: #ffffff;
            padding: 15px;
            border-radius: 8px;
            text-align: center;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            border-top: 3px solid #dc3545;
        }

        .stat-number {
            font-size: 1.5rem;
            font-weight: 600;
            color: #dc3545;
            margin-bottom: 5px;
        }

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

        .card {
            background: #ffffff;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            border: 1px solid #dee2e6;
            margin-bottom: 20px;
        }

        .card h3 {
            color: #333;
            margin-bottom: 15px;
            font-weight: 600;
            font-size: 1.1rem;
        }

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

        .form-group {
            margin-bottom: 0;
        }

        .form-group label {
            font-weight: 500;
            margin-bottom: 5px;
            color: #333;
            font-size: 0.875rem;
        }

        .form-control {
            border: 1px solid #ced4da;
            border-radius: 4px;
            padding: 8px 10px;
            font-size: 0.875rem;
            transition: border-color 0.3s;
        }

        .form-control:focus {
            border-color: #dc3545;
            box-shadow: 0 0 0 0.1rem rgba(220, 53, 69, 0.1);
            outline: none;
        }

        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            font-weight: 500;
            transition: all 0.3s;
            display: inline-flex;
            align-items: center;
            gap: 5px;
            font-size: 0.875rem;
        }

        .btn-danger {
            background: #dc3545;
            color: white;
        }

        .btn-danger:hover {
            background: #c82333;
        }

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

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

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

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

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

        .badge-warning {
            background: #fff3cd;
            color: #856404;
        }

        .badge-danger {
            background: #f8d7da;
            color: #721c24;
        }

        .badge-success {
            background: #d1edff;
            color: #0c5460;
        }

        .alert {
            padding: 10px 15px;
            border-radius: 6px;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            gap: 8px;
            border: 1px solid transparent;
            font-size: 0.875rem;
        }

        .alert-success {
            background: #d1edff;
            color: #0c5460;
            border-color: #b8daff;
        }

        .alert-error {
            background: #f8d7da;
            color: #721c24;
            border-color: #f5c6cb;
        }

        .empty-state {
            text-align: center;
            color: #6c757d;
            padding: 30px 20px;
        }

        .empty-state i {
            font-size: 2rem;
            margin-bottom: 10px;
            opacity: 0.5;
            color: #28a745;
        }

        .empty-state h4 {
            margin-bottom: 5px;
            font-weight: 600;
            color: #333;
            font-size: 1rem;
        }

        .text-muted {
            font-size: 0.8rem;
        }

        .student-info {
            font-weight: 500;
        }

        .student-nis {
            font-size: 0.75rem;
            color: #6c757d;
        }

        @media (max-width: 768px) {
            .container {
                padding: 15px;
            }
            
            .form-compact {
                grid-template-columns: 1fr;
            }
            
            .stats-grid {
                grid-template-columns: repeat(2, 1fr);
            }
            
            .table {
                font-size: 0.8rem;
            }
        }

        @media (max-width: 576px) {
            .stats-grid {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <a href="dashboard_wali_kelas.php" class="btn-back">
            <i class="fas fa-arrow-left"></i> Kembali
        </a>

        <div class="header">
            <h1><i class="fas fa-exclamation-triangle me-2"></i>Pelanggaran Siswa</h1>
            <p>Kelas <?php echo htmlspecialchars($kelas_diampu); ?></p>
        </div>

        <!-- Statistik -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-number"><?php echo $total_pelanggaran; ?></div>
                <div class="stat-label">Total Pelanggaran</div>
            </div>
            <div class="stat-card">
                <div class="stat-number"><?php echo $total_poin; ?></div>
                <div class="stat-label">Total Poin</div>
            </div>
            <div class="stat-card">
                <div class="stat-number"><?php echo $pelanggaran_aktif; ?></div>
                <div class="stat-label">Pelanggaran Aktif</div>
            </div>
        </div>

        <?php if (isset($success)): ?>
            <div class="alert alert-success">
                <i class="fas fa-check-circle"></i> <?php echo $success; ?>
            </div>
        <?php endif; ?>

        <?php if (isset($error)): ?>
            <div class="alert alert-error">
                <i class="fas fa-exclamation-circle"></i> <?php echo $error; ?>
            </div>
        <?php endif; ?>

        <!-- Form Input Minimalis -->
        <div class="card">
            <h3><i class="fas fa-plus me-2"></i>Tambah Pelanggaran</h3>
            <form method="POST">
                <div class="form-compact">
                    <div class="form-group">
                        <label for="siswa_id">Siswa</label>
                        <select class="form-control" id="siswa_id" name="siswa_id" required>
                            <option value="">Pilih Siswa</option>
                            <?php foreach ($daftar_siswa as $siswa): ?>
                                <option value="<?php echo $siswa['id']; ?>">
                                    <?php echo htmlspecialchars($siswa['nama']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="form-group">
                        <label for="tanggal">Tanggal</label>
                        <input type="date" class="form-control" id="tanggal" name="tanggal" 
                               value="<?php echo date('Y-m-d'); ?>" required>
                    </div>

                    <div class="form-group">
                        <label for="jenis_pelanggaran">Jenis</label>
                        <select class="form-control" id="jenis_pelanggaran" name="jenis_pelanggaran" required>
                            <option value="">Pilih Jenis</option>
                            <option value="Terlambat">Terlambat</option>
                            <option value="Tidak Memakai Seragam">Tidak Memakai Seragam</option>
                            <option value="Tidak Membawa Perlengkapan">Tidak Membawa Perlengkapan</option>
                            <option value="Mengganggu Kelas">Mengganggu Kelas</option>
                            <option value="Tidak Mengumpulkan Tugas">Tidak Mengumpulkan Tugas</option>
                            <option value="Melanggar Tata Tertib">Melanggar Tata Tertib</option>
                            <option value="Lainnya">Lainnya</option>
                        </select>
                    </div>

                    <div class="form-group">
                        <label for="poin">Poin</label>
                        <input type="number" class="form-control" id="poin" name="poin" 
                               min="1" max="20" value="1" required>
                    </div>
                </div>

                <div class="form-group">
                    <label for="keterangan">Keterangan</label>
                    <textarea class="form-control" id="keterangan" name="keterangan" rows="2" 
                              placeholder="Deskripsi pelanggaran..." required></textarea>
                </div>

                <button type="submit" name="submit_pelanggaran" class="btn btn-danger">
                    <i class="fas fa-save me-1"></i> Simpan
                </button>
            </form>
        </div>

        <!-- Tabel Riwayat Pelanggaran -->
        <div class="card">
            <h3><i class="fas fa-history me-2"></i>Riwayat Pelanggaran</h3>
            
            <?php if (empty($riwayat_pelanggaran)): ?>
                <div class="empty-state">
                    <i class="fas fa-check-circle"></i>
                    <h4>Belum Ada Pelanggaran</h4>
                    <p class="text-muted">Belum ada pelanggaran yang dicatat untuk kelas ini</p>
                </div>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>Tanggal</th>
                                <th>Siswa</th>
                                <th>Jenis Pelanggaran</th>
                                <th>Keterangan</th>
                                <th>Poin</th>
                                <th>Status</th>
                                <th>Oleh</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($riwayat_pelanggaran as $pelanggaran): ?>
                                <tr>
                                    <td>
                                        <div class="text-nowrap"><?php echo date('d/m/Y', strtotime($pelanggaran['tanggal'])); ?></div>
                                        <div class="text-muted" style="font-size: 0.75rem;"><?php echo date('H:i', strtotime($pelanggaran['created_at'])); ?></div>
                                    </td>
                                    <td>
                                        <div class="student-info"><?php echo htmlspecialchars($pelanggaran['siswa_nama']); ?></div>
                                        <div class="student-nis"><?php echo htmlspecialchars($pelanggaran['nis']); ?></div>
                                    </td>
                                    <td><?php echo htmlspecialchars($pelanggaran['jenis_pelanggaran']); ?></td>
                                    <td style="max-width: 250px;"><?php echo htmlspecialchars($pelanggaran['keterangan']); ?></td>
                                    <td>
                                        <span class="badge <?php echo $pelanggaran['poin'] >= 10 ? 'badge-danger' : 'badge-warning'; ?>">
                                            <?php echo $pelanggaran['poin']; ?> Poin
                                        </span>
                                    </td>
                                    <td>
                                        <span class="badge <?php echo $pelanggaran['status'] === 'Selesai' ? 'badge-success' : 'badge-warning'; ?>">
                                            <?php echo ucfirst($pelanggaran['status']); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <small class="text-muted"><?php echo htmlspecialchars($pelanggaran['guru_nama'] ?? 'System'); ?></small>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Set maximum date to today
        document.getElementById('tanggal').max = new Date().toISOString().split('T')[0];

        // Auto-hide alerts after 3 seconds
        setTimeout(() => {
            const alerts = document.querySelectorAll('.alert');
            alerts.forEach(alert => {
                alert.style.display = 'none';
            });
        }, 3000);
    </script>
</body>
</html>