<?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'];
$guru_id = 0;
$guru_nama = '';

$query = "SELECT * FROM guru WHERE nip = '$username' LIMIT 1";
$result = mysqli_query($conn, $query);

if ($result && mysqli_num_rows($result) > 0) {
    $guru = mysqli_fetch_assoc($result);
    $guru_id = $guru['id'];
    $guru_nama = $guru['nama'];
} else {
    $query_user = "SELECT * FROM users WHERE username = '$username' AND role = 'guru' LIMIT 1";
    $result_user = mysqli_query($conn, $query_user);
    if ($result_user && mysqli_num_rows($result_user) > 0) {
        $user = mysqli_fetch_assoc($result_user);
        $guru_nama = $user['nama'] ?? $username;
    }
}

// Ambil parameter ID jika ada
$pelanggaran_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

// Ambil data pelanggaran untuk ditangani
$pelanggaran = null;
if ($pelanggaran_id > 0) {
    $query = "SELECT p.*, s.nama as nama_siswa, s.kelas, s.nisn, s.no_wa,
                     g.nama as nama_guru_pelapor, w.nama_wali as nama_wali_kelas
              FROM pelanggaran p 
              LEFT JOIN siswa s ON p.siswa_id = s.id 
              LEFT JOIN guru g ON p.guru_id = g.id
              LEFT JOIN wali_kelas w ON p.wali_kelas_id = w.id
              WHERE p.id = $pelanggaran_id";
    $result = mysqli_query($conn, $query);
    if ($result && mysqli_num_rows($result) > 0) {
        $pelanggaran = mysqli_fetch_assoc($result);
    }
}

// Ambil daftar pelanggaran aktif untuk ditampilkan di tabel
$daftar_pelanggaran = [];
$query_list = "SELECT p.*, s.nama as nama_siswa, s.kelas, s.nisn
               FROM pelanggaran p 
               LEFT JOIN siswa s ON p.siswa_id = s.id 
               WHERE p.status = 'Aktif'
               ORDER BY p.tanggal DESC, p.created_at DESC";
$result_list = mysqli_query($conn, $query_list);
if ($result_list) {
    while ($row = mysqli_fetch_assoc($result_list)) {
        $daftar_pelanggaran[] = $row;
    }
}

// Proses form penanganan
$message = '';
$message_type = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        $id = (int)$_POST['id'];
        $tindakan = mysqli_real_escape_string($conn, $_POST['tindakan']);
        $catatan_penanganan = mysqli_real_escape_string($conn, $_POST['catatan_penanganan']);
        $status = mysqli_real_escape_string($conn, $_POST['status']);
        
        $updated_at = date('Y-m-d H:i:s');
        
        $query = "UPDATE pelanggaran SET 
                  tindakan = '$tindakan',
                  catatan_penanganan = '$catatan_penanganan',
                  status = '$status',
                  updated_at = '$updated_at'
                  WHERE id = $id";
        
        if (mysqli_query($conn, $query)) {
            $message = "Pelanggaran berhasil ditangani!";
            $message_type = "success";
            header("refresh:2;url=penanganan_pelanggaran.php");
        } else {
            $message = "Error: " . mysqli_error($conn);
            $message_type = "error";
        }
    }
}

// Ambil nama sekolah untuk header
$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>Penanganan Pelanggaran - Guru Piket</title>
    
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css">
    
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: Arial, sans-serif;
            background: #f3f4f6;
            color: #333;
            line-height: 1.5;
            padding: 20px;
        }

        /* Header */
        .header {
            background: white;
            border-radius: 8px;
            padding: 15px 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 4px 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;
            color: #333;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .logo h2 i {
            color: #10b981;
        }

        .logo p {
            font-size: 0.875rem;
            color: #666;
            margin-top: 5px;
        }

        .user-info {
            display: flex;
            align-items: center;
            gap: 15px;
            background: #f8f9fa;
            padding: 8px 15px;
            border-radius: 50px;
        }

        .user-avatar {
            width: 40px;
            height: 40px;
            background: #10b981;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
        }

        .user-details .name {
            font-weight: 600;
            color: #333;
        }

        .user-details .role {
            font-size: 0.75rem;
            color: #666;
        }

        /* Title */
        h2 {
            text-align: center;
            margin-bottom: 5px;
            color: #333;
        }

        .subtitle {
            text-align: center;
            color: #666;
            margin-bottom: 20px;
            font-size: 0.9rem;
        }

        /* Alert */
        .alert {
            background: white;
            border-radius: 8px;
            padding: 15px 20px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 15px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        .alert.success {
            border-left: 4px solid #10b981;
        }

        .alert.error {
            border-left: 4px solid #ef4444;
        }

        .alert i {
            font-size: 1.25rem;
        }

        .alert.success i {
            color: #10b981;
        }

        .alert.error i {
            color: #ef4444;
        }

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

        .detail-header {
            background: #10b981;
            color: white;
            padding: 10px 15px;
            border-radius: 8px 8px 0 0;
            margin: -20px -20px 20px -20px;
            font-weight: bold;
        }

        .detail-header i {
            margin-right: 8px;
        }

        .info-row {
            display: flex;
            border-bottom: 1px solid #eee;
            padding: 10px 0;
        }

        .info-label {
            width: 150px;
            font-weight: bold;
            color: #666;
        }

        .info-value {
            flex: 1;
        }

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

        .form-card h3 {
            margin-bottom: 20px;
            color: #333;
            border-bottom: 2px solid #10b981;
            padding-bottom: 10px;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-group label {
            display: block;
            font-weight: bold;
            margin-bottom: 5px;
            color: #555;
        }

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

        .form-control:focus {
            outline: none;
            border-color: #10b981;
        }

        textarea.form-control {
            resize: vertical;
            min-height: 100px;
        }

        /* Buttons */
        .btn {
            padding: 8px 16px;
            border-radius: 4px;
            font-size: 14px;
            font-weight: bold;
            cursor: pointer;
            border: none;
            display: inline-flex;
            align-items: center;
            gap: 5px;
            text-decoration: none;
        }

        .btn-primary {
            background: #10b981;
            color: white;
        }

        .btn-primary:hover {
            background: #059669;
        }

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

        .btn-secondary:hover {
            background: #5a6268;
        }

        .btn-success {
            background: #28a745;
            color: white;
        }

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

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

        .btn-sm {
            padding: 4px 8px;
            font-size: 12px;
        }

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

        .table-container h3 {
            margin-bottom: 20px;
            color: #333;
            border-bottom: 2px solid #10b981;
            padding-bottom: 10px;
        }

        table {
            border-collapse: collapse;
            width: 100%;
            font-size: 14px;
        }

        th, td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: center;
        }

        th {
            background: #f8f9fa;
            font-weight: bold;
            color: #333;
        }

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

        /* Badges */
        .badge {
            padding: 3px 8px;
            border-radius: 4px;
            font-weight: bold;
            font-size: 12px;
            display: inline-block;
        }

        .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;
        }

        /* Action Buttons */
        .action-buttons {
            display: flex;
            gap: 5px;
            justify-content: center;
        }

        .action-btn {
            padding: 4px 8px;
            border-radius: 4px;
            color: white;
            text-decoration: none;
            font-size: 12px;
            display: inline-flex;
            align-items: center;
            gap: 3px;
        }

        .action-btn.view {
            background: #3b82f6;
        }

        .action-btn.handle {
            background: #10b981;
        }

        .action-btn.transfer {
            background: #f59e0b;
        }

        .action-btn:hover {
            opacity: 0.9;
        }

        /* Footer Buttons */
        .footer-buttons {
            margin-top: 20px;
            display: flex;
            gap: 10px;
            justify-content: center;
            flex-wrap: wrap;
        }

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

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

        .footer-buttons a.print {
            background: #28a745;
        }

        .footer-buttons a.print:hover {
            background: #218838;
        }

        /* No Data */
        .no-data {
            text-align: center;
            padding: 40px;
            color: #666;
        }

        .no-data i {
            font-size: 48px;
            color: #ddd;
            margin-bottom: 10px;
        }

        /* Responsive */
        @media (max-width: 768px) {
            .info-row {
                flex-direction: column;
            }

            .info-label {
                width: 100%;
                margin-bottom: 5px;
            }

            .action-buttons {
                flex-direction: column;
            }

            table {
                font-size: 12px;
            }

            th, td {
                padding: 5px;
            }
        }
    </style>
</head>
<body>
    <!-- Header -->
    <div class="header">
        <div class="logo">
            <h2>
                <i class="fas fa-hand-holding-heart"></i>
                Penanganan Pelanggaran
            </h2>
            <p><?= $nama_sekolah ?> • Guru Piket</p>
        </div>
        
        <div class="user-info">
            <div class="user-avatar">
                <?= strtoupper(substr($guru_nama, 0, 1)) ?>
            </div>
            <div class="user-details">
                <div class="name"><?= htmlspecialchars($guru_nama) ?></div>
                <div class="role">Guru Piket</div>
            </div>
        </div>
    </div>

    <!-- Title -->
    <h2>PENANGANAN PELANGGARAN SISWA</h2>
    <div class="subtitle">Tangani dan tindak lanjuti pelanggaran yang dilaporkan</div>

    <!-- Alert -->
    <?php if (!empty($message)): ?>
    <div class="alert <?= $message_type ?>">
        <i class="fas fa-<?= ($message_type == 'success') ? 'check-circle' : 'exclamation-circle' ?>"></i>
        <span><?= nl2br(htmlspecialchars($message)) ?></span>
    </div>
    <?php endif; ?>

    <?php if ($pelanggaran): ?>
    <!-- Detail Pelanggaran -->
    <div class="detail-card">
        <div class="detail-header">
            <i class="fas fa-clipboard-list"></i>
            DETAIL PELANGGARAN #<?= $pelanggaran['id'] ?>
        </div>
        
        <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 20px;">
            <div>
                <div class="info-row">
                    <div class="info-label">NISN</div>
                    <div class="info-value">: <?= htmlspecialchars($pelanggaran['nisn'] ?? '-') ?></div>
                </div>
                <div class="info-row">
                    <div class="info-label">Nama Siswa</div>
                    <div class="info-value">: <strong><?= htmlspecialchars($pelanggaran['nama_siswa'] ?? '-') ?></strong></div>
                </div>
                <div class="info-row">
                    <div class="info-label">Kelas</div>
                    <div class="info-value">: <?= htmlspecialchars($pelanggaran['kelas'] ?? '-') ?></div>
                </div>
            </div>
            <div>
                <div class="info-row">
                    <div class="info-label">Tanggal</div>
                    <div class="info-value">: <?= date('d/m/Y', strtotime($pelanggaran['tanggal'])) ?></div>
                </div>
                <div class="info-row">
                    <div class="info-label">Jenis Pelanggaran</div>
                    <div class="info-value">: <?= htmlspecialchars($pelanggaran['jenis_pelanggaran']) ?></div>
                </div>
                <div class="info-row">
                    <div class="info-label">Poin</div>
                    <div class="info-value">: 
                        <span class="badge <?= ($pelanggaran['poin'] >= 50) ? 'badge-berat' : (($pelanggaran['poin'] >= 25) ? 'badge-sedang' : 'badge-ringan') ?>">
                            <?= $pelanggaran['poin'] ?> Poin
                        </span>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="info-row" style="margin-top: 10px;">
            <div class="info-label">Keterangan</div>
            <div class="info-value">: <?= nl2br(htmlspecialchars($pelanggaran['keterangan'])) ?></div>
        </div>
        
        <?php if (!empty($pelanggaran['bukti_foto'])): ?>
        <div class="info-row">
            <div class="info-label">Bukti Foto</div>
            <div class="info-value">: 
                <a href="<?= $pelanggaran['bukti_foto'] ?>" target="_blank" class="btn btn-sm btn-secondary">
                    <i class="fas fa-image"></i> Lihat Bukti
                </a>
            </div>
        </div>
        <?php endif; ?>
    </div>

    <!-- Form Penanganan -->
    <div class="form-card">
        <h3><i class="fas fa-pen"></i> FORM PENANGANAN PELANGGARAN</h3>
        
        <form method="POST" id="formPenanganan">
            <input type="hidden" name="id" value="<?= $pelanggaran['id'] ?>">
            <input type="hidden" name="action" value="handle">
            
            <div class="form-group">
                <label>Tindakan yang Diambil</label>
                <select class="form-control" name="tindakan" required>
                    <option value="">-- Pilih Tindakan --</option>
                    <option value="Teguran Lisan">Teguran Lisan</option>
                    <option value="Teguran Tertulis">Teguran Tertulis</option>
                    <option value="Pemanggilan Orang Tua">Pemanggilan Orang Tua</option>
                    <option value="Skorsing">Skorsing</option>
                    <option value="Sanksi Lainnya">Sanksi Lainnya</option>
                </select>
            </div>
            
            <div class="form-group">
                <label>Status Penanganan</label>
                <select class="form-control" name="status" required>
                    <option value="Aktif" <?= ($pelanggaran['status'] == 'Aktif') ? 'selected' : '' ?>>Aktif (Masih Ditangani)</option>
                    <option value="Selesai" <?= ($pelanggaran['status'] == 'Selesai') ? 'selected' : '' ?>>Selesai (Telah Ditangani)</option>
                </select>
            </div>
            
            <div class="form-group">
                <label>Catatan Penanganan</label>
                <textarea class="form-control" name="catatan_penanganan" rows="4" placeholder="Isikan catatan penanganan, sanksi, atau tindak lanjut..." required><?= htmlspecialchars($pelanggaran['catatan_penanganan'] ?? '') ?></textarea>
            </div>
            
            <div style="display: flex; gap: 10px; justify-content: flex-end;">
                <a href="penanganan_pelanggaran.php" class="btn btn-secondary">
                    <i class="fas fa-times"></i> Batal
                </a>
                <button type="submit" class="btn btn-primary">
                    <i class="fas fa-save"></i> Simpan Penanganan
                </button>
            </div>
        </form>
    </div>
    <?php endif; ?>

    <!-- Tabel Daftar Pelanggaran Aktif -->
    <div class="table-container">
        <h3><i class="fas fa-list"></i> DAFTAR PELANGGARAN AKTIF</h3>
        
        <table>
            <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>Klasifikasi</th>
                    <th>Status</th>
                    <th>Aksi</th>
                </tr>
            </thead>
            <tbody>
                <?php if (!empty($daftar_pelanggaran)): ?>
                    <?php $no = 1; ?>
                    <?php foreach ($daftar_pelanggaran as $row): 
                        // Klasifikasi
                        if ($row['poin'] >= 50) {
                            $klasifikasi = 'Berat';
                            $klasifikasiClass = 'badge-berat';
                        } elseif ($row['poin'] >= 25) {
                            $klasifikasi = 'Sedang';
                            $klasifikasiClass = 'badge-sedang';
                        } else {
                            $klasifikasi = 'Ringan';
                            $klasifikasiClass = 'badge-ringan';
                        }
                    ?>
                    <tr>
                        <td><?= $no++ ?></td>
                        <td><?= date('d/m/Y', strtotime($row['tanggal'])) ?></td>
                        <td><?= htmlspecialchars($row['nisn'] ?? '-') ?></td>
                        <td class="text-left"><?= htmlspecialchars($row['nama_siswa'] ?? '-') ?></td>
                        <td><?= htmlspecialchars($row['kelas'] ?? '-') ?></td>
                        <td class="text-left"><?= htmlspecialchars($row['jenis_pelanggaran']) ?></td>
                        <td><strong><?= $row['poin'] ?></strong></td>
                        <td><span class="badge <?= $klasifikasiClass ?>"><?= $klasifikasi ?></span></td>
                        <td><span class="badge badge-aktif">Aktif</span></td>
                        <td>
                            <div class="action-buttons">
                                <a href="detail_pelanggaran.php?id=<?= $row['id'] ?>" class="action-btn view" title="Detail">
                                    <i class="fas fa-eye"></i>
                                </a>
                                <a href="penanganan_pelanggaran.php?id=<?= $row['id'] ?>" class="action-btn handle" title="Tangani">
                                    <i class="fas fa-hand-holding-heart"></i>
                                </a>
                                <?php if (!isset($row['status_alihkan']) || $row['status_alihkan'] != 'ya'): ?>
                                <a href="alihkan_pelanggaran.php?id=<?= $row['id'] ?>" class="action-btn transfer" title="Alihkan ke Wali Kelas">
                                    <i class="fas fa-share-alt"></i>
                                </a>
                                <?php endif; ?>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="10" class="no-data">
                            <i class="fas fa-check-circle"></i>
                            <p>Tidak ada pelanggaran aktif</p>
                        </td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

    <!-- Footer Buttons -->
    <div class="footer-buttons">
        <a href="dashboard_guru_piket.php">
            <i class="fas fa-arrow-left"></i> Kembali ke Dashboard
        </a>
        <a href="laporkan_pelanggaran.php" class="print">
            <i class="fas fa-plus-circle"></i> Lapor Pelanggaran
        </a>
        <a href="rekap_pelanggaran.php" class="print">
            <i class="fas fa-file-alt"></i> Rekap Bulanan
        </a>
    </div>

    <script>
        document.getElementById('formPenanganan')?.addEventListener('submit', function(e) {
            const tindakan = document.querySelector('select[name="tindakan"]').value;
            const catatan = document.querySelector('textarea[name="catatan_penanganan"]').value;
            
            if (!tindakan || !catatan) {
                e.preventDefault();
                alert('Tindakan dan catatan penanganan harus diisi!');
                return false;
            }
            
            return confirm('Apakah data penanganan sudah benar?');
        });
    </script>
</body>
</html>