<?php
include('session_validator.php');
include("includes/db.php");

// Fetch assigned subjects and classes from the database
$assignedSubjectsQuery = "SELECT class_subject_mapping.id, classes.class_name, subjects.subject_name, classes.section
                         FROM class_subject_mapping
                         INNER JOIN classes ON class_subject_mapping.class_id = classes.Class_id
                         INNER JOIN subjects ON class_subject_mapping.subject_id = subjects.id";

$assignedSubjectsResult = $conn->query($assignedSubjectsQuery);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>SRMS Admin Manage Subjects</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/prism/prism.css" media="screen">
    <link rel="stylesheet" href="css/select2/select2.min.css">
    <link rel="stylesheet" href="css/main.css" media="screen">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@10"></script>
    <script src="js/modernizr/modernizr.min.js"></script>
</head>
<body class="top-navbar-fixed">
<div class="main-wrapper">

    <!-- ========== TOP NAVBAR ========== -->
    <?php include('includes/topbar.php'); ?>
    <!-- ========== WRAPPER FOR BOTH SIDEBARS & MAIN CONTENT ========== -->
    <div class="content-wrapper">
        <div class="content-container">

            <!-- ========== LEFT SIDEBAR ========== -->
            <?php include('includes/leftbar.php'); ?>
            <!-- /.left-sidebar -->

            <div class="main-page">

                <div class="container-fluid">
                    <div class="row page-title-div">
                        <div class="col-md-6">
                            <h2 class="title">Enter Marks</h2>
                        </div>
                        <!-- /.col-md-6 text-right -->
                    </div>
                    <!-- /.row -->
                    <div class="row breadcrumb-div">
                        <div class="col-md-6">
                            <ul class="breadcrumb">
                                <li><a href="dashboard.php"><i class="fa fa-home"></i> Home</a></li>
                                <li> Subjects</li>
                                <li class="active">Enter Marks</li>
                            </ul>
                        </div>
                    </div>
                    <!-- /.row -->
                </div>
                <div class="container-fluid">
                    <div class="row">
                        <div class="col-md-12">
                            <div class="panel">
                                <div class="panel-heading">
                                    <div class="panel-title">
                                        <h5>Enter Marks</h5>
                                    </div>
                                </div>
                                <div class="panel-body">
                                    <form method="POST" action="update_editmarks.php">
                                        <div class="form-row">
                                            <div class="form-group col-md-4">
                                                <label for="exam_id1">Select Exam:</label>
                                                <select id="exam_id1" name="exam_id1" class="form-control" required>
                                                    <option value="">Select Exam</option>
                                                    <?php
                                                    $queryexam = "SELECT id, exm_year, exam_type FROM examination_type";
                                                    $resultexam = $conn->query($queryexam);

                                                    while ($row = $resultexam->fetch_assoc()) {
                                                        echo "<option value='" . $row['id'] . "'>" . $row['exam_type'] . " - " . $row['exm_year'] . "</option>";
                                                    }
                                                    ?>
                                                </select>
                                            </div>

                                            <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
                                                    $query = "SELECT Class_id, class_name, section FROM classes";
                                                    $result = $conn->query($query);

                                                    while ($row = $result->fetch_assoc()) {
                                                        echo "<option value='" . $row['Class_id'] . "'>" . $row['class_name'] . " - " . $row['section'] . "</option>";
                                                    }
                                                    ?>
                                                </select>
                                            </div>

                                            <div class="form-group col-md-4">
                                                <label for="student_id">Select Student:</label>
                                                <select id="student_id" name="student_id" class="form-control">
                                                    <option value="">Select Student</option>
                                                    <!-- Students will be populated here via AJAX -->
                                                </select>
                                            </div>
                                       

                                        <div id="student-subjects">
                                            <!-- Subject marks fields will be populated here via AJAX -->
                                        </div>

                                        <button type="submit" name="submit" class="btn btn-primary">Submit Marks</button>
                                     </div></form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<?php
// Close the database connection
$conn->close();
?>

<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/main.js"></script>
<script src="js/modernizr/modernizr.min.js"></script>

<?php
// Check for success or error parameter in the URL
if (isset($_GET['success']) && $_GET['success'] == 1) {
    // Display success alert using SweetAlert
    echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@10'></script>";
    echo "<script>
            $(document).ready(function () {
                Swal.fire({
                    icon: 'success',
                    title: 'Success',
                    text: 'Data inserted successfully!',
                });
            });
          </script>";
} elseif (isset($_GET['error']) && $_GET['error'] == 1) {
    // Display error alert using SweetAlert
    echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@10'></script>";
    echo "<script>
            $(document).ready(function () {
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: 'Error inserting data!',
                });
            });
          </script>";
}
?>

<script>
    $(document).ready(function () {
        // Change event for class selection
        $('#class_id').change(function () {
            var classId = $(this).val();

            // Fetch students for the selected class
            $.ajax({
                type: 'POST',
                url: 'get_students_markedit.php',
                data: {classId: classId},
                success: function (response) {
                    $('#student_id').html(response);
                    $('#student-subjects').empty(); // Clear subjects when class changes
                }
            });
        });

        // Change event for student selection
        $('#student_id').change(function () {
            var studentId = $(this).val();
            var classId = $('#class_id').val();
            var examId = $('#exam_id1').val();

            // Fetch subjects and marks for the selected student
            $.ajax({
                type: 'POST',
                url: 'get_student_subjects.php',
                data: {studentId: studentId, classId: classId},
                success: function (response) {
                    $('#student-subjects').html(response);
                    // After loading subjects, fetch the marks
                    if (studentId && classId && examId) {
                        fetchMarks(studentId, classId, examId);
                    }
                }
            });
        });

        // Change event for exam selection
        $('#exam_id1').change(function () {
            var studentId = $('#student_id').val();
            var classId = $('#class_id').val();
            var examId = $(this).val();

            // Fetch marks for the selected student, class, and exam
            if (studentId && classId && examId) {
                fetchMarks(studentId, classId, examId);
            }
        });

        // Function to fetch marks from the database
        function fetchMarks(studentId, classId, examId) {
            $.ajax({
                type: 'POST',
                url: 'fetch_marks.php',
                data: {
                    studentId: studentId,
                    classId: classId,
                    examId: examId
                },
                success: function (response) {
                    var marks = JSON.parse(response);

                    // Populate marks into input fields
                    $('.marks-input').each(function () {
                        var subjectId = $(this).data('subject-id');
                        if (marks[subjectId] !== undefined) {
                            $(this).val(marks[subjectId]);
                        } else {
                            $(this).val(''); // Clear input if no marks found
                        }
                    });
                }
            });
        }

        // Input validation for marks fields
        $('#student-subjects').on('input', '.marks-input', function () {
            var enteredMarks = parseFloat($(this).val());
            var theoryFullMarks = parseFloat($('#theory-full-marks').text());

            if (enteredMarks > theoryFullMarks) {
                // Display alert using SweetAlert
                Swal.fire({
                    icon: 'warning',
                    title: 'Warning',
                    text: 'Entered marks cannot exceed theory full marks!',
                });

                // Reset the entered marks
                $(this).val('');
            }
        });
    });
</script>

</body>
</html>
