<?php
// Koneksi database
include 'koneksi.php';
session_start(); // Pastikan session dimulai

// Ambil data kelas dan mata kuliah
$query_kelas = "SELECT * FROM tbl_kelas";
$result_kelas = mysqli_query($conn, $query_kelas);

$query_matakuliah = "SELECT * FROM tbl_matakuliah";
$result_matakuliah = mysqli_query($conn, $query_matakuliah);

// Batas maksimal SKS
$max_sks = 24;  // Maksimal SKS per semester

// Proses pengisian KRS
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $id_kelas = $_POST['id_kelas'];
    $id_matakuliah = $_POST['id_matakuliah'];
    $jumlah_sks = $_POST['jumlah_sks'];
    $semester = $_POST['semester'];
    $tahun_ajaran = $_POST['tahun_ajaran'];

    // Pastikan id_mahasiswa ada dalam session
    if (isset($_SESSION['id_mahasiswa'])) {
        $id_mahasiswa = $_SESSION['id_mahasiswa'];
    } else {
        $error = "Anda harus login terlebih dahulu.";
    }

    // Validasi SKS: Cek berapa SKS yang sudah diambil mahasiswa di semester yang sama
    $query_sks_terambil = "SELECT SUM(jumlah_sks) AS total_sks FROM tbl_krs WHERE id_mahasiswa = '$id_mahasiswa' AND semester = '$semester' AND tahun_ajaran = '$tahun_ajaran'";
    $result_sks_terambil = mysqli_query($conn, $query_sks_terambil);
    $row_sks = mysqli_fetch_assoc($result_sks_terambil);
    $sks_terambil = $row_sks['total_sks'] ? $row_sks['total_sks'] : 0;

    // Validasi batas SKS
    $total_sks = $sks_terambil + $jumlah_sks;
    if ($total_sks > $max_sks) {
        $error = "Jumlah SKS Anda melebihi batas maksimal (" . $max_sks . " SKS) pada semester ini.";
    } else {
        // Cek apakah mata kuliah sudah diambil pada semester yang sama
        $query_check = "SELECT * FROM tbl_krs WHERE id_mahasiswa = '$id_mahasiswa' AND id_matakuliah = '$id_matakuliah' AND semester = '$semester' AND tahun_ajaran = '$tahun_ajaran'";
        $result_check = mysqli_query($conn, $query_check);
        if (mysqli_num_rows($result_check) > 0) {
            $error = "Mata kuliah ini sudah diambil pada semester ini.";
        } else {
            // Insert data KRS
            $query_insert = "INSERT INTO tbl_krs (id_mahasiswa, id_kelas, id_matakuliah, jumlah_sks, semester, tahun_ajaran) 
                             VALUES ('$id_mahasiswa', '$id_kelas', '$id_matakuliah', '$jumlah_sks', '$semester', '$tahun_ajaran')";
            if (mysqli_query($conn, $query_insert)) {
                header("Location: krs.php");
                exit;
            } else {
                $error = "Gagal menyimpan data KRS: " . mysqli_error($conn);
            }
        }
    }
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tambah KRS</title>
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
    <script>
        // Fungsi untuk update SKS ketika mata kuliah dipilih
        function updateSks() {
            var matakuliahSelect = document.getElementById('id_matakuliah');
            var sksInput = document.getElementById('jumlah_sks');
            var selectedOption = matakuliahSelect.options[matakuliahSelect.selectedIndex];
            var jumlahSks = selectedOption.getAttribute('data-sks');
            sksInput.value = jumlahSks;
        }

        // Fungsi untuk validasi batas SKS dan mata kuliah yang sudah diambil
        function validateForm() {
            var jumlahSks = parseInt(document.getElementById('jumlah_sks').value);
            var semester = document.getElementById('semester').value;
            var tahunAjaran = document.getElementById('tahun_ajaran').value;

            // Validasi batas SKS
            if (jumlahSks > 24) {
                alert("Jumlah SKS tidak boleh melebihi 24.");
                return false;
            }

            // Validasi jika mata kuliah sudah diambil di semester ini
            var matakuliahSelect = document.getElementById('id_matakuliah');
            var idMatakuliah = matakuliahSelect.value;
            
            // Cek mata kuliah sudah diambil di semester ini (ini perlu integrasi backend, tidak bisa di cek di client-side)
            // Anda perlu menambahkan validasi ini di PHP bagian server, seperti pada contoh sebelumnya

            return true;
        }
    </script>
</head>
<body>
    <!-- Navbar -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <a class="navbar-brand" href="#">Sistem KRS</a>
    </nav>

    <!-- Form -->
    <div class="container mt-4">
        <h3 class="text-center mb-4">Tambah KRS</h3>

        <!-- Pesan error -->
        <?php if (isset($error)): ?>
            <div class="alert alert-danger"><?php echo $error; ?></div>
        <?php endif; ?>

        <form method="POST" onsubmit="return validateForm()">
            <!-- Pilih Kelas -->
            <div class="form-group">
                <label for="id_kelas">Pilih Kelas</label>
                <select name="id_kelas" id="id_kelas" class="form-control" required>
                    <option value="">Pilih Kelas</option>
                    <?php
                    if ($result_kelas && mysqli_num_rows($result_kelas) > 0) {
                        while ($row = mysqli_fetch_assoc($result_kelas)) {
                            echo "<option value='" . $row['id_kelas'] . "'>" . $row['nama_kelas'] . "</option>";
                        }
                    } else {
                        echo "<option value=''>Tidak ada data kelas</option>";
                    }
                    ?>
                </select>
            </div>

            <!-- Pilih Mata Kuliah -->
            <div class="form-group">
                <label for="id_matakuliah">Pilih Mata Kuliah</label>
                <select name="id_matakuliah" id="id_matakuliah" class="form-control" required onchange="updateSks()">
                    <option value="">Pilih Mata Kuliah</option>
                    <?php
                    if ($result_matakuliah && mysqli_num_rows($result_matakuliah) > 0) {
                        while ($row = mysqli_fetch_assoc($result_matakuliah)) {
                            echo "<option value='" . $row['id_matakuliah'] . "' data-sks='" . $row['jumlah_sks'] . "'>" . $row['nama_matakuliah'] . "</option>";
                        }
                    } else {
                        echo "<option value=''>Tidak ada data mata kuliah</option>";
                    }
                    ?>
                </select>
            </div>

            <!-- Jumlah SKS -->
            <div class="form-group">
                <label for="jumlah_sks">Jumlah SKS</label>
                <input type="number" name="jumlah_sks" id="jumlah_sks" class="form-control" readonly required>
            </div>

            <!-- Semester -->
            <div class="form-group">
                <label for="semester">Semester</label>
                <select name="semester" id="semester" class="form-control" required>
                    <option value="ganjil">Ganjil</option>
                    <option value="genap">Genap</option>
                </select>
            </div>

            <!-- Tahun Ajaran -->
            <div class="form-group">
                <label for="tahun_ajaran">Tahun Ajaran</label>
                <input type="text" name="tahun_ajaran" id="tahun_ajaran" class="form-control" placeholder="Misal: 2023/2024" required>
            </div>

            <!-- Tombol -->
            <button type="submit" class="btn btn-success btn-block">Simpan</button>
        </form>
    </div>

    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>
</html>
