<?php
// Koneksi ke database
include "config.php";

// Query untuk mendapatkan data pelanggaran
$query = "SELECT 
            ps.id_pelanggaran,
            ps.nama_siswa,
            ps.jenis_kelamin,
            ps.tanggal,
            ps.pelanggaran,
            ps.poin,
            ps.keterangan,
            k.nama_kelas,
            k.wali_kelas,
            ta.tahun_ajaran,
            ta.semester
          FROM ctkpoin_pelanggaran_siswa ps
          JOIN ctkpoin_kelas k ON ps.kode_kelas = k.kode_kelas
          JOIN ctkpoin_tahun_ajaran ta ON ps.kode_tahun_ajaran = ta.kode_tahun_ajaran
          ORDER BY ps.tanggal DESC, ps.id_pelanggaran DESC";

$result = mysqli_query($conn, $query);

// Hitung total poin
$queryTotal = "SELECT SUM(poin) as total_poin FROM ctkpoin_pelanggaran_siswa";
$resultTotal = mysqli_query($conn, $queryTotal);
$totalPoin = mysqli_fetch_assoc($resultTotal)['total_poin'];

// Hitung jumlah pelanggaran
$queryCount = "SELECT COUNT(*) as jumlah FROM ctkpoin_pelanggaran_siswa";
$resultCount = mysqli_query($conn, $queryCount);
$jumlahPelanggaran = mysqli_fetch_assoc($resultCount)['jumlah'];
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Data Pelanggaran Siswa</title>
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <!-- DataTables CSS -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap5.min.css">
    
    <style>
        body {
            background-color: #f8f9fa;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        .navbar-brand {
            font-weight: bold;
            font-size: 1.5rem;
        }
        
        .card {
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            border: none;
            margin-bottom: 20px;
        }
        
        .card-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 10px 10px 0 0 !important;
            font-weight: bold;
        }
        
        .stat-card {
            transition: transform 0.3s;
        }
        
        .stat-card:hover {
            transform: translateY(-5px);
        }
        
        .stat-icon {
            font-size: 2.5rem;
            opacity: 0.8;
        }
        
        .badge-pelanggaran {
            font-size: 0.8rem;
            padding: 5px 10px;
        }
        
        .table th {
            background-color: #f1f3fa;
            font-weight: 600;
        }
        
        .btn-action {
            margin: 2px;
            padding: 5px 10px;
        }
        
        footer {
            margin-top: 30px;
        }
        
        /* Responsive adjustments */
        @media (max-width: 768px) {
            .card-header h4 {
                font-size: 1.2rem;
            }
            
            .table-responsive {
                font-size: 0.9rem;
            }
        }
    </style>
</head>
<body>
    <!-- Navbar -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <div class="container">
            <a class="navbar-brand" href="#">
                <i class="fas fa-school me-2"></i>Sistem E-Poin Sekolah
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item">
                        <a class="nav-link active" href="data_pelanggaran.php">
                            <i class="fas fa-list me-1"></i>Data Pelanggaran
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#">
                            <i class="fas fa-chart-bar me-1"></i>Statistik
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#">
                            <i class="fas fa-cog me-1"></i>Pengaturan
                        </a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="container mt-4">
        <!-- Header -->
        <div class="row mb-4">
            <div class="col-12">
                <h2 class="text-primary">
                    <i class="fas fa-clipboard-list me-2"></i>Data Pelanggaran Siswa
                </h2>
                <p class="text-muted">Manajemen data pelanggaran dan poin pelanggaran siswa</p>
            </div>
        </div>

        <!-- Statistik Cards -->
        <div class="row mb-4">
            <div class="col-md-4 mb-3">
                <div class="card stat-card bg-primary text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h5 class="card-title">Total Pelanggaran</h5>
                                <h2 class="mb-0"><?php echo $jumlahPelanggaran; ?></h2>
                                <p class="card-text">Data pelanggaran</p>
                            </div>
                            <div class="stat-icon">
                                <i class="fas fa-exclamation-triangle"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="col-md-4 mb-3">
                <div class="card stat-card bg-warning text-dark">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h5 class="card-title">Total Poin</h5>
                                <h2 class="mb-0"><?php echo $totalPoin; ?></h2>
                                <p class="card-text">Akumulasi poin pelanggaran</p>
                            </div>
                            <div class="stat-icon">
                                <i class="fas fa-chart-line"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="col-md-4 mb-3">
                <div class="card stat-card bg-success text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h5 class="card-title">Rata-rata Poin</h5>
                                <h2 class="mb-0"><?php echo $jumlahPelanggaran > 0 ? round($totalPoin / $jumlahPelanggaran, 2) : 0; ?></h2>
                                <p class="card-text">Poin per pelanggaran</p>
                            </div>
                            <div class="stat-icon">
                                <i class="fas fa-calculator"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Tabel Data Pelanggaran -->
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h4 class="mb-0">Daftar Pelanggaran</h4>
                <div>
                   <!-- Menjadi -->
                    <div class="dropdown d-inline">
                        <button class="btn btn-light btn-sm dropdown-toggle" type="button" data-bs-toggle="dropdown">
                            <i class="fas fa-print me-1"></i> Cetak
                        </button>
                        <ul class="dropdown-menu">
                            <li><a class="dropdown-item" href="cetak_pelanggaran.php"><i class="fas fa-user me-2"></i> Cetak Per Siswa</a></li>
                            <li><a class="dropdown-item" href="cetak_perkelas.php"><i class="fas fa-users me-2"></i> Cetak Per kelas</a></li>
                        </ul>
                    </div>
                    <button class="btn btn-light btn-sm" onclick="exportToExcel()">
                        <i class="fas fa-file-excel me-1"></i>Excel
                    </button>
                    <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#addModal">
                        <i class="fas fa-plus me-1"></i>Tambah Data
                    </button>
                </div>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table id="dataTable" class="table table-hover table-striped">
                        <thead>
                            <tr>
                                <th>No</th>
                                <th>Nama Siswa</th>
                                <th>kelas</th>
                                <th>Jenis Kelamin</th>
                                <th>Tanggal</th>
                                <th>Pelanggaran</th>
                                <th>Poin</th>
                                <th>Keterangan</th>
                                <!-- <th>Tahun Ajaran</th> -->
                                <th width="10%">Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            $no = 1;
                            if (mysqli_num_rows($result) > 0) {
                                while ($row = mysqli_fetch_assoc($result)) {
                                    $poinClass = '';
                                    if ($row['poin'] >= 10) {
                                        $poinClass = 'danger';
                                    } elseif ($row['poin'] >= 5) {
                                        $poinClass = 'warning';
                                    } else {
                                        $poinClass = 'info';
                                    }
                            ?>
                            <tr>
                                <td><?php echo $no++; ?></td>
                                <td><?php echo htmlspecialchars($row['nama_siswa']); ?></td>
                                <td><?php echo htmlspecialchars($row['nama_kelas']); ?></td>
                                <td>
                                    <span class="badge bg-<?php echo $row['jenis_kelamin'] == 'Laki-Laki' ? 'primary' : 'danger'; ?>">
                                        <?php echo $row['jenis_kelamin']; ?>
                                    </span>
                                </td>
                                <td><?php echo date('d-m-Y', strtotime($row['tanggal'])); ?></td>
                                <td><?php echo htmlspecialchars($row['pelanggaran']); ?></td>
                                <td>
                                    <span class="badge bg-<?php echo $poinClass; ?>">
                                        <?php echo $row['poin']; ?>
                                    </span>
                                </td>
                                <td><?php echo htmlspecialchars($row['keterangan']); ?></td>
                               <!-- <td>
                                    <span class="badge bg-secondary">
                                        <?php echo $row['tahun_ajaran'] . ' - ' . $row['semester']; ?>
                                    </span>
                                </td> -->
                                <td>
                                    <button class="btn btn-sm btn-warning btn-action" title="Edit" 
                                            onclick="editData(<?php echo $row['id_pelanggaran']; ?>)">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    <button class="btn btn-sm btn-danger btn-action" title="Hapus"
                                            onclick="deleteData(<?php echo $row['id_pelanggaran']; ?>, '<?php echo htmlspecialchars($row['nama_siswa']); ?>')">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </td>
                            </tr>
                            <?php
                                }
                            } else {
                            ?>
                            <tr>
                                <td colspan="10" class="text-center text-muted py-4">
                                    <i class="fas fa-database fa-2x mb-3"></i><br>
                                    Tidak ada data pelanggaran
                                </td>
                            </tr>
                            <?php
                            }
                            ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Footer -->
        <footer class="text-center text-muted py-3">
            <p>&copy; <?php echo date('Y'); ?> Sistem E-Poin Sekolah. All rights reserved.</p>
        </footer>
    </div>

    <!-- Modal Tambah Data -->
    <div class="modal fade" id="addModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <form id="formTambah" action="proses_tambah.php" method="POST">
                    <div class="modal-header bg-primary text-white">
                        <h5 class="modal-title">
                            <i class="fas fa-plus-circle me-2"></i>Tambah Data Pelanggaran
                        </h5>
                        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Nama Siswa</label>
                                <input type="text" class="form-control" name="nama_siswa" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Jenis Kelamin</label>
                                <select class="form-select" name="jenis_kelamin" required>
                                    <option value="">Pilih Jenis Kelamin</option>
                                    <option value="Laki-Laki">Laki-Laki</option>
                                    <option value="Perempuan">Perempuan</option>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Kelas</label>
                                <select class="form-select" name="kode_kelas" required>
                                    <option value="">Pilih kelas</option>
                                    <?php
                                    $queryKelas = "SELECT * FROM ctkpoin_kelas";
                                    $resultKelas = mysqli_query($conn, $queryKelas);
                                    while ($ctkpoin_kelas = mysqli_fetch_assoc($resultKelas)) {
                                        echo "<option value='" . $ctkpoin_kelas['kode_kelas'] . "'>" . 
                                             $ctkpoin_kelas['nama_kelas'] . " - " . $ctkpoin_kelas['wali_kelas'] . "</option>";
                                    }
                                    ?>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Tahun Ajaran</label>
                                <select class="form-select" name="kode_tahun_ajaran" required>
                                    <option value="">Pilih Tahun Ajaran</option>
                                    <?php
                                    $queryTahun = "SELECT * FROM ctkpoin_tahun_ajaran";
                                    $resultTahun = mysqli_query($conn, $queryTahun);
                                    while ($tahun = mysqli_fetch_assoc($resultTahun)) {
                                        echo "<option value='" . $tahun['kode_tahun_ajaran'] . "'>" . 
                                             $tahun['ctkpoin_tahun_ajaran'] . " - " . $tahun['semester'] . "</option>";
                                    }
                                    ?>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Tanggal</label>
                                <input type="date" class="form-control" name="tanggal" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Poin</label>
                                <input type="number" class="form-control" name="poin" min="1" max="100" required>
                            </div>
                            <div class="col-md-12 mb-3">
                                <label class="form-label">Jenis Pelanggaran</label>
                                <input type="text" class="form-control" name="pelanggaran" required>
                            </div>
                            <div class="col-md-12 mb-3">
                                <label class="form-label">Keterangan</label>
                                <textarea class="form-control" name="keterangan" rows="3"></textarea>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                        <button type="submit" class="btn btn-primary">Simpan Data</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Modal Edit Data -->
    <div class="modal fade" id="editModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <form id="formEdit" action="proses_edit.php" method="POST">
                    <div class="modal-header bg-warning text-white">
                        <h5 class="modal-title">
                            <i class="fas fa-edit me-2"></i>Edit Data Pelanggaran
                        </h5>
                        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <input type="hidden" name="id_pelanggaran" id="edit_id">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Nama Siswa</label>
                                <input type="text" class="form-control" name="nama_siswa" id="edit_nama" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Jenis Kelamin</label>
                                <select class="form-select" name="jenis_kelamin" id="edit_jk" required>
                                    <option value="Laki-Laki">Laki-Laki</option>
                                    <option value="Perempuan">Perempuan</option>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Kelas</label>
                                <select class="form-select" name="kode_kelas" id="edit_kelas" required>
                                    <?php
                                    mysqli_data_seek($resultKelas, 0);
                                    while ($ctkpoin_kelas = mysqli_fetch_assoc($resultKelas)) {
                                        echo "<option value='" . $ctkpoin_kelas['kode_kelas'] . "'>" . 
                                             $ctkpoin_kelas['nama_kelas'] . " - " . $ctkpoin_kelas['wali_kelas'] . "</option>";
                                    }
                                    ?>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Tahun Ajaran</label>
                                <select class="form-select" name="kode_tahun_ajaran" id="edit_tahun" required>
                                    <?php
                                    mysqli_data_seek($resultTahun, 0);
                                    while ($tahun = mysqli_fetch_assoc($resultTahun)) {
                                        echo "<option value='" . $tahun['kode_tahun_ajaran'] . "'>" . 
                                             $tahun['ctkpoin_tahun_ajaran'] . " - " . $tahun['semester'] . "</option>";
                                    }
                                    ?>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Tanggal</label>
                                <input type="date" class="form-control" name="tanggal" id="edit_tanggal" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Poin</label>
                                <input type="number" class="form-control" name="poin" id="edit_poin" min="1" max="100" required>
                            </div>
                            <div class="col-md-12 mb-3">
                                <label class="form-label">Jenis Pelanggaran</label>
                                <input type="text" class="form-control" name="pelanggaran" id="edit_pelanggaran" required>
                            </div>
                            <div class="col-md-12 mb-3">
                                <label class="form-label">Keterangan</label>
                                <textarea class="form-control" name="keterangan" id="edit_keterangan" rows="3"></textarea>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                        <button type="submit" class="btn btn-warning">Update Data</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- JavaScript -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap5.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
    <script>
    // Inisialisasi DataTable
    $(document).ready(function() {
        $('#dataTable').DataTable({
            "language": {
                "url": "//cdn.datatables.net/plug-ins/1.13.4/i18n/id.json"
            },
            "order": [[0, 'asc']],
            "lengthMenu": [[10, 30, 50, 100, -1], [10, 30, 50, 100, "All"]],
            "pageLength": 10
        });
    });

    // Fungsi untuk edit data
    function editData(id) {
        // AJAX untuk mengambil data
        $.ajax({
            url: 'get_data.php',
            type: 'GET',
            data: {id: id},
            dataType: 'json',
            success: function(response) {
                if (response.status == 'success') {
                    $('#edit_id').val(response.data.id_pelanggaran);
                    $('#edit_nama').val(response.data.nama_siswa);
                    $('#edit_jk').val(response.data.jenis_kelamin);
                    $('#edit_kelas').val(response.data.kode_kelas);
                    $('#edit_tahun').val(response.data.kode_tahun_ajaran);
                    $('#edit_tanggal').val(response.data.tanggal);
                    $('#edit_pelanggaran').val(response.data.pelanggaran);
                    $('#edit_poin').val(response.data.poin);
                    $('#edit_keterangan').val(response.data.keterangan);
                    
                    var editModal = new bootstrap.Modal(document.getElementById('editModal'));
                    editModal.show();
                } else {
                    Swal.fire('Error', 'Data tidak ditemukan', 'error');
                }
            },
            error: function() {
                Swal.fire('Error', 'Terjadi kesalahan saat mengambil data', 'error');
            }
        });
    }

    // Fungsi untuk hapus data
    function deleteData(id, nama) {
        Swal.fire({
            title: 'Apakah Anda yakin?',
            text: `Anda akan menghapus data pelanggaran untuk ${nama}`,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#3085d6',
            confirmButtonText: 'Ya, Hapus!',
            cancelButtonText: 'Batal'
        }).then((result) => {
            if (result.isConfirmed) {
                window.location.href = 'proses_hapus.php?id=' + id;
            }
        });
    }

    // Fungsi untuk cetak tabel
    function printTable() {
        window.print();
    }

    // Fungsi untuk export ke Excel
    function exportToExcel() {
        // Implementasi export ke Excel
        Swal.fire({
            title: 'Export ke Excel',
            text: 'Fitur ini akan segera tersedia',
            icon: 'info',
            confirmButtonText: 'OK'
        });
    }

    // Validasi form tambah
    $('#formTambah').on('submit', function(e) {
        var poin = $('input[name="poin"]').val();
        if (poin < 1 || poin > 100) {
            e.preventDefault();
            Swal.fire('Error', 'Poin harus antara 1-100', 'error');
        }
    });

    // Validasi form edit
    $('#formEdit').on('submit', function(e) {
        var poin = $('#edit_poin').val();
        if (poin < 1 || poin > 100) {
            e.preventDefault();
            Swal.fire('Error', 'Poin harus antara 1-100', 'error');
        }
    });
</script>
</body>
</html>

<?php
// Tutup koneksi
mysqli_close($conn);
?>