<?php
include('session_validator.php');
include('includes/db.php'); // Include database connection code

// Retrieve exam types from the database
$query_exam_types = "SELECT id, exm_year, exam_type FROM examination_type";
$result_exam_types = $conn->query($query_exam_types);

// Retrieve classes from the database
$query_classes = "SELECT class_id, class_name, section FROM classes";
$result_classes = $conn->query($query_classes);

// Initialize arrays to hold subjects and students
$subjects = [];
$students = [];

// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Retrieve form data
    $examId = $_POST['exam_id'];
    $classId = $_POST['class_id'];
    $subjectId = $_POST['subject_id'];

    // Fetch all subjects assigned to the selected class
    $query_subjects = "SELECT id, subject_name FROM class_subject_mapping WHERE class_id = $classId";
    $result_subjects = $conn->query($query_subjects);
    
    // Populate subjects array
    while ($row = $result_subjects->fetch_assoc()) {
        $subjects[] = $row;
    }

    // Fetch all students of the selected class with their marks for the selected subject
    $query_students_marks = "SELECT s.student_id, s.name, COALESCE(m.marks, 'N/A') AS marks
                             FROM students s
                             LEFT JOIN marks m ON s.student_id = m.student_id
                             WHERE s.class_id = $classId AND m.subject_id = $subjectId";
    $result_students_marks = $conn->query($query_students_marks);

    // Populate students array
    while ($row = $result_students_marks->fetch_assoc()) {
        $students[] = $row;
    }
}

?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Marks</title>
    <link rel="stylesheet" href="css/bootstrap.min.css" media="screen">
    <link rel="stylesheet" href="css/font-awesome.min.css" media="screen">
    <link rel="stylesheet" href="css/animate-css/animate.min.css" media="screen">
    <link rel="stylesheet" href="css/lobipanel/lobipanel.min.css" media="screen">
    <link rel="stylesheet" href="css/toastr/toastr.min.css" media="screen">
    <link rel="stylesheet" href="css/icheck/skins/line/blue.css">
    <link rel="stylesheet" href="css/icheck/skins/line/red.css">
    <link rel="stylesheet" href="css/icheck/skins/line/green.css">
    <link rel="stylesheet" href="css/main.css" media="screen">
    <script src="js/modernizr/modernizr.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script> <!-- SweetAlert Library -->

    <style type="text/css">
        .fixed-bottom-right {
            position: fixed;
            bottom: 20px;
            right: 20px;
            z-index: 9999; /* Ensure it's on top of other elements */
        }
    </style>
</head>

<body>
    <?php include('includes/topbar.php');?>
    <div class="content-wrapper">
        <div class="content-container">
            <?php include('includes/leftbar.php');?>
            <div class="main-page">
                <div class="container-fluid">
                    <div class="panel">
                        <div class="panel-heading">
                            <div class="panel-title">
                                <h5>Edit Marks</h5>
                            </div>
                        </div>
                        <div class="panel-body">
                            <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
                                <div class="form-row">
                                    <!-- Select Exam Type -->
                                    <div class="form-group col-md-4">
                                        <label for="exam_id">Select Exam Type:</label>
                                        <select id="exam_id" name="exam_id" class="form-control" required>
                                            <option value="">Select Exam Type</option>
                                            <?php
                                            while ($row = $result_exam_types->fetch_assoc()) {
                                                echo "<option value='" . $row['id'] . "'>" . $row['exm_year'] . " - " . $row['exam_type'] . "</option>";
                                            }
                                            ?>
                                        </select>
                                    </div>
                                    <!-- Select Class -->
                                    <div class="form-group col-md-4">
                                        <label for="class_id">Select Class:</label>
                                        <select id="class_id" name="class_id" class="form-control" required>
                                            <option value="">Select Class</option>
                                            <?php
                                            while ($row = $result_classes->fetch_assoc()) {
                                                echo "<option value='" . $row['class_id'] . "'>" . $row['class_name'] . " - " . $row['section'] . "</option>";
                                            }
                                            ?>
                                        </select>
                                    </div>
                                    <!-- Select Subject Assigned to Class -->
                                    <div class="form-group col-md-4">
                                        <label for="subject_id">Select Subject:</label>
                                        <select id="subject_id" name="subject_id" class="form-control" required>
                                            <option value="">Select Subject</option>
                                            <?php
                                            foreach ($subjects as $subject) {
                                                echo "<option value='" . $subject['id'] . "'>" . $subject['subject_name'] . "</option>";
                                            }
                                            ?>
                                        </select>
                                    </div>
                                    <br>
                                     <div class="form-group" id="student-marks-list">
                                        <!-- Student marks entry fields will be populated here using AJAX -->
                                    </div>
    
                                    <!-- Submit Button -->
                                    <div class="fixed-bottom-right">
                                        <button type="button" id="submitBtn" class="btn btn-primary">Submit</button>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div> 
                </div>
            </div>
        </div>
    </div>
    <script src="js/jquery/jquery-2.2.4.min.js"></script>
    <script src="js/bootstrap/bootstrap.min.js"></script>
    <script src="js/pace/pace.min.js"></script>
    <script src="js/lobipanel/lobipanel.min.js"></script>
    <script src="js/iscroll/iscroll.js"></script>
    <script src="js/prism/prism.js"></script>
    <script src="js/select2/select2.min.js"></script>
    <script src="js/main.js"></script>
<script>
$(document).ready(function () {
    // Function to fetch and populate students based on exam, class, and subject
    function fetchStudents(examId, classId, subjectId) {
        $.ajax({
            type: 'POST',
            url: 'get_student_list_th.php',
            data: { examId: examId, classId: classId, subjectId: subjectId },
            success: function (response) {
                $('#student-marks-list').html(response);
            },
            error: function (xhr, status, error) {
                console.error('Error fetching students:', error);
            }
        });
    }

    // Event handler for dropdowns
    $('#exam_id, #class_id, #subject_id').change(function () {
        const examId = $('#exam_id').val();
        const classId = $('#class_id').val();
        const subjectId = $('#subject_id').val();
        fetchStudents(examId, classId, subjectId);
    });

    // Event handler for submit button
    $('#submitBtn').click(function () {
        const marksData = {};
        $('#student-marks-list input[type="number"]').each(function () {
            const studentId = $(this).attr('id').split('_')[1];
            const marks = $(this).val();
            marksData[studentId] = marks;
        });

        const examId = $('#exam_id').val();
        const classId = $('#class_id').val();
        const subjectId = $('#subject_id').val();

        $.ajax({
            type: 'POST',
            url: 'update_thmarks.php',
            data: {
                marksData: marksData,
                examId: examId,
                classId: classId,
                subjectId: subjectId
            },
            success: function (response) {
                Swal.fire({
                    icon: 'success',
                    title: 'Marks updated successfully!',
                    showConfirmButton: false,
                    timer: 1500
                });
            },
            error: function (xhr, status, error) {
                Swal.fire({
                    icon: 'error',
                    title: 'Error updating marks!',
                    text: 'Please try again later.'
                });
            }
        });
    });
});
</script>

    <script>
        document.getElementById("class_id").addEventListener("change", function () {
            var classId = this.value;
            var subjectDropdown = document.getElementById("subject_id");

            subjectDropdown.innerHTML = "<option value=''>Select Subject</option>";

            fetch(`getSubjects.php?class_id=${classId}`)
                .then(response => response.json())
                .then(data => {
                    data.forEach(subject => {
                        var option = document.createElement("option");
                        option.value = subject.id;
                        option.textContent = subject.subject_name;
                        subjectDropdown.appendChild(option);
                    });
                })
                .catch(error => {
                    console.error('Error:', error);
                });
        });
    </script>
</body>

</html>
