<?php 
include 'koneksi.php';
cek_akses(['Super Admin', 'Kepala', 'Guru']);

// Tambah kolom NIS ke tabel students jika belum ada
$cek_nis = mysqli_query($conn, "SHOW COLUMNS FROM students LIKE 'nis'");
if($cek_nis && mysqli_num_rows($cek_nis) == 0) {
    mysqli_query($conn, "ALTER TABLE students ADD COLUMN nis VARCHAR(50) AFTER id");
}

// Tambah kolom status jika belum ada
$cek_status = mysqli_query($conn, "SHOW COLUMNS FROM students LIKE 'status'");
if($cek_status && mysqli_num_rows($cek_status) == 0) {
    mysqli_query($conn, "ALTER TABLE students ADD COLUMN status ENUM('Aktif', 'Pindah', 'Keluar', 'Lulus') DEFAULT 'Aktif'");
}

// Filter berdasarkan role
$filter_unit = "";
$filter_where = "WHERE 1=1";
$filter_unit_text = "";

if($_SESSION['role'] == 'Kepala') {
    $filter_unit = $_SESSION['unit'];
    $filter_where = "WHERE c.unit = '{$_SESSION['unit']}'";
    $filter_unit_text = "AND unit = '{$_SESSION['unit']}'";
} elseif($_SESSION['role'] == 'Guru') {
    $filter_unit = $_SESSION['unit'];
    $filter_where = "WHERE c.unit = '{$_SESSION['unit']}'";
    $filter_unit_text = "AND unit = '{$_SESSION['unit']}'";
}

// Proses Tambah Siswa
if(isset($_POST['simpan'])) {
    $nis = mysqli_real_escape_string($conn, $_POST['nis']);
    $name = mysqli_real_escape_string($conn, $_POST['name']);
    $class_id = $_POST['class_id'];
    $status = mysqli_real_escape_string($conn, $_POST['status']);
    
    $kelas_data = mysqli_fetch_assoc(mysqli_query($conn, "SELECT unit FROM classes WHERE id=$class_id"));
    $unit = $kelas_data['unit'];
    
    $cek_nis_exist = mysqli_query($conn, "SELECT id FROM students WHERE nis = '$nis'");
    if(mysqli_num_rows($cek_nis_exist) > 0) {
        echo "<script>alert('NIS sudah terdaftar! Gunakan NIS yang berbeda.');</script>";
    } else {
        $query = "INSERT INTO students (nis, name, class_id, unit, status) VALUES ('$nis', '$name', '$class_id', '$unit', '$status')";
        if(mysqli_query($conn, $query)) {
            echo "<script>alert('Siswa berhasil ditambahkan!'); window.location='kelola_siswa.php';</script>";
        } else {
            echo "<script>alert('Gagal menambahkan siswa: " . mysqli_error($conn) . "');</script>";
        }
    }
}

// Proses Edit Siswa
if(isset($_POST['update'])) {
    $id = $_POST['id'];
    $nis = mysqli_real_escape_string($conn, $_POST['nis']);
    $name = mysqli_real_escape_string($conn, $_POST['name']);
    $class_id = $_POST['class_id'];
    $status = mysqli_real_escape_string($conn, $_POST['status']);
    
    $kelas_data = mysqli_fetch_assoc(mysqli_query($conn, "SELECT unit FROM classes WHERE id=$class_id"));
    $unit = $kelas_data['unit'];
    
    $cek_nis_exist = mysqli_query($conn, "SELECT id FROM students WHERE nis = '$nis' AND id != $id");
    if(mysqli_num_rows($cek_nis_exist) > 0) {
        echo "<script>alert('NIS sudah terdaftar! Gunakan NIS yang berbeda.');</script>";
    } else {
        mysqli_query($conn, "UPDATE students SET nis='$nis', name='$name', class_id='$class_id', unit='$unit', status='$status' WHERE id=$id");
        echo "<script>alert('Siswa berhasil diupdate!'); window.location='kelola_siswa.php';</script>";
    }
}

// Proses Hapus Siswa
if(isset($_GET['hapus'])) {
    $id = $_GET['hapus'];
    mysqli_query($conn, "DELETE FROM students WHERE id=$id");
    echo "<script>alert('Siswa berhasil dihapus!'); window.location='kelola_siswa.php';</script>";
}

// Query ambil daftar kelas
$kelas_query = "SELECT * FROM classes WHERE 1=1 $filter_unit_text ORDER BY unit, name";
$kelas_result = mysqli_query($conn, $kelas_query);
$kelas_list = [];
if($kelas_result && mysqli_num_rows($kelas_result) > 0) {
    while($row = mysqli_fetch_assoc($kelas_result)) {
        $kelas_list[] = $row;
    }
}

// Query ambil data siswa
$siswa_query = "SELECT s.*, c.name as class_name, c.unit 
    FROM students s 
    JOIN classes c ON s.class_id = c.id 
    $filter_where 
    ORDER BY c.unit, c.name, s.name";

$siswa_result = mysqli_query($conn, $siswa_query);
$siswa_list = [];
if($siswa_result && mysqli_num_rows($siswa_result) > 0) {
    while($row = mysqli_fetch_assoc($siswa_result)) {
        $siswa_list[] = $row;
    }
}

$total_siswa = count($siswa_list);
?>

<!DOCTYPE html>
<html>
<head>
    <title>Kelola Siswa - SIM ISTIQLAL</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/admin-lte@3.2/dist/css/adminlte.min.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="assets/css/theme-istiqlal-green.css">
</head>
<body class="hold-transition sidebar-mini layout-fixed">
<div class="wrapper">
    <?php include 'sidebar.php'; ?>
    
    <div class="content-wrapper">
        <div class="content-header">
            <div class="container-fluid">
                <div class="row mb-2">
                    <div class="col-sm-6">
                        <h1 class="m-0 font-weight-bold">
                            <i class="fas fa-user-graduate text-primary"></i> Kelola Data Siswa
                        </h1>
                    </div>
                    <div class="col-sm-6">
                        <ol class="breadcrumb float-sm-right">
                            <li class="breadcrumb-item"><a href="dashboard.php">Home</a></li>
                            <li class="breadcrumb-item active">Kelola Siswa</li>
                        </ol>
                    </div>
                </div>
                <?php if($_SESSION['role'] == 'Kepala' || $_SESSION['role'] == 'Guru'): ?>
                <div class="alert alert-info">
                    <i class="fas fa-building"></i> Menampilkan data untuk unit: <strong><?= $_SESSION['unit'] ?></strong>
                </div>
                <?php endif; ?>
            </div>
        </div>

        <div class="content">
            <div class="container-fluid">
                <!-- Statistik -->
                <div class="row">
                    <div class="col-md-3 col-6">
                        <div class="stats-card">
                            <div class="stats-number text-primary"><?= $total_siswa ?></div>
                            <div class="stats-label">Total Siswa</div>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <!-- Form Tambah -->
                    <div class="col-md-4">
                        <div class="card">
                            <div class="card-header bg-primary text-white">
                                <h4><i class="fas fa-plus"></i> Tambah Siswa</h4>
                            </div>
                            <div class="card-body">
                                <form method="POST">
                                    <div class="mb-3">
                                        <label class="form-label">NIS <span class="text-danger">*</span></label>
                                        <input type="text" name="nis" class="form-control" placeholder="Nomor Induk Siswa" required>
                                    </div>
                                    <div class="mb-3">
                                        <label class="form-label">Nama Siswa <span class="text-danger">*</span></label>
                                        <input type="text" name="name" class="form-control" placeholder="Nama lengkap" required>
                                    </div>
                                    <div class="mb-3">
                                        <label class="form-label">Kelas <span class="text-danger">*</span></label>
                                        <select name="class_id" class="form-select" required>
                                            <option value="">-- Pilih Kelas --</option>
                                            <?php foreach($kelas_list as $kelas): ?>
                                            <option value="<?= $kelas['id'] ?>"><?= $kelas['name'] ?> (<?= $kelas['unit'] ?>)</option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <div class="mb-3">
                                        <label class="form-label">Status</label>
                                        <select name="status" class="form-select">
                                            <option value="Aktif">Aktif</option>
                                            <option value="Lulus">Lulus</option>
                                            <option value="Pindah">Pindah</option>
                                            <option value="Keluar">Keluar</option>
                                        </select>
                                    </div>
                                    <button type="submit" name="simpan" class="btn btn-primary w-100">
                                        <i class="fas fa-save"></i> Simpan
                                    </button>
                                </form>
                                <hr>
                                <a href="import_excel.php?tab=siswa" class="btn btn-success w-100">
                                    <i class="fas fa-file-excel"></i> Import Excel
                                </a>
                            </div>
                        </div>
                    </div>

                    <!-- Daftar Siswa -->
                    <div class="col-md-8">
                        <div class="card">
                            <div class="card-header bg-primary text-white">
                                <h4><i class="fas fa-list"></i> Daftar Siswa</h4>
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-bordered table-striped">
                                        <thead>
                                            <tr>
                                                <th>No</th>
                                                <th>NIS</th>
                                                <th>Nama Siswa</th>
                                                <th>Kelas</th>
                                                <th>Unit</th>
                                                <th>Status</th>
                                                <th>Aksi</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php if(count($siswa_list) > 0): ?>
                                                <?php $no=1; foreach($siswa_list as $row): 
                                                    $status_class = ($row['status'] == 'Aktif') ? 'success' : (($row['status'] == 'Lulus') ? 'warning' : 'danger');
                                                ?>
                                                <tr>
                                                    <td class="text-center"><?= $no++ ?></td>
                                                    <td><code><?= htmlspecialchars($row['nis']) ?></code></td>
                                                    <td><strong><?= htmlspecialchars($row['name']) ?></strong></td>
                                                    <td><?= htmlspecialchars($row['class_name']) ?></td>
                                                    <td><span class="badge bg-secondary"><?= htmlspecialchars($row['unit']) ?></span></td>
                                                    <td><span class="badge bg-<?= $status_class ?>"><?= $row['status'] ?></span></td>
                                                    <td class="text-center">
                                                        <button class="btn btn-sm btn-info" onclick="detailSiswa(<?= $row['id'] ?>)">
                                                            <i class="fas fa-eye"></i>
                                                        </button>
                                                        <button class="btn btn-sm btn-warning" onclick='editSiswa(<?= $row['id'] ?>, "<?= addslashes($row['nis']) ?>", "<?= addslashes($row['name']) ?>", <?= $row['class_id'] ?>, "<?= $row['status'] ?>")'>
                                                            <i class="fas fa-edit"></i>
                                                        </button>
                                                        <a href="kelola_siswa.php?hapus=<?= $row['id'] ?>" class="btn btn-sm btn-danger" onclick="return confirm('Yakin hapus siswa ini?')">
                                                            <i class="fas fa-trash"></i>
                                                        </a>
                                                    </td>
                                                </tr>
                                                <?php endforeach; ?>
                                            <?php else: ?>
                                                <tr>
                                                    <td colspan="7" class="text-center">Belum ada data siswa</td>
                                                </tr>
                                            <?php endif; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <footer class="main-footer">
        <strong>&copy; <?= date('Y') ?> SIM ISTIQLAL - Sistem Administrasi Guru</strong>
    </footer>
</div>

<!-- MODAL DETAIL SISWA -->
<div class="modal fade" id="modalDetailSiswa" data-bs-backdrop="static" data-bs-keyboard="true" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title"><i class="fas fa-user-graduate"></i> Detail Siswa</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="detailContent">
                <div class="text-center p-4">
                    <div class="spinner-border text-primary" role="status"></div>
                    <p class="mt-2">Memuat data...</p>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Tutup</button>
            </div>
        </div>
    </div>
</div>

<!-- MODAL EDIT SISWA -->
<div class="modal fade" id="modalEditSiswa" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <form method="POST">
                <div class="modal-header bg-warning text-white">
                    <h5 class="modal-title"><i class="fas fa-edit"></i> Edit Siswa</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="id" id="edit_id">
                    <div class="mb-3">
                        <label class="form-label">NIS</label>
                        <input type="text" name="nis" id="edit_nis" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Nama Siswa</label>
                        <input type="text" name="name" id="edit_name" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Kelas</label>
                        <select name="class_id" id="edit_class_id" class="form-select" required>
                            <?php foreach($kelas_list as $kelas): ?>
                            <option value="<?= $kelas['id'] ?>"><?= $kelas['name'] ?> (<?= $kelas['unit'] ?>)</option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Status</label>
                        <select name="status" id="edit_status" class="form-select">
                            <option value="Aktif">Aktif</option>
                            <option value="Lulus">Lulus</option>
                            <option value="Pindah">Pindah</option>
                            <option value="Keluar">Keluar</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                    <button type="submit" name="update" class="btn btn-warning">Update</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/admin-lte@3.2/dist/js/adminlte.min.js"></script>

<script>
let detailModal = null;

function detailSiswa(id) {
    document.getElementById('detailContent').innerHTML = `
        <div class="text-center p-4">
            <div class="spinner-border text-primary" role="status"></div>
            <p class="mt-2">Memuat data...</p>
        </div>
    `;
    
    const modalElement = document.getElementById('modalDetailSiswa');
    if (!detailModal) {
        detailModal = new bootstrap.Modal(modalElement, { backdrop: true, keyboard: true });
    }
    detailModal.show();
    
    $.ajax({
        url: 'get_siswa_detail.php',
        type: 'POST',
        data: { siswa_id: id },
        dataType: 'json',
        success: function(response) {
            if (response.error) {
                document.getElementById('detailContent').innerHTML = `<div class="alert alert-danger">${response.error}</div>`;
                return;
            }
            let statusClass = response.status == 'Aktif' ? 'success' : (response.status == 'Lulus' ? 'warning' : 'danger');
            document.getElementById('detailContent').innerHTML = `
                <table class="table table-borderless">
                    <tr><th width="30%">NIS</th><td>: <code>${response.nis}</code></td></tr>
                    <tr><th>Nama Lengkap</th><td>: <strong>${response.name}</strong></td></tr>
                    <tr><th>Kelas</th><td>: ${response.class_name}</td></tr>
                    <tr><th>Unit</th><td>: ${response.unit}</td></tr>
                    <tr><th>Status</th><td>: <span class="badge bg-${statusClass}">${response.status}</span></td></tr>
                </table>
            `;
        },
        error: function() {
            document.getElementById('detailContent').innerHTML = `<div class="alert alert-danger">Gagal memuat data!</div>`;
        }
    });
}

function editSiswa(id, nis, name, class_id, status) {
    document.getElementById('edit_id').value = id;
    document.getElementById('edit_nis').value = nis;
    document.getElementById('edit_name').value = name;
    document.getElementById('edit_class_id').value = class_id;
    document.getElementById('edit_status').value = status;
    new bootstrap.Modal(document.getElementById('modalEditSiswa')).show();
}
</script>

</body>
</html>