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

// Fetch classes and exams for dropdowns
$classQuery = "SELECT Class_id, class_name, section FROM classes";
$classResult = $conn->query($classQuery);

$examQuery = "SELECT id, exm_year, exam_type FROM examination_type";
$examResult = $conn->query($examQuery);
?>

<!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 Enter Marks</title>
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="css/font-awesome.min.css">
    <link rel="stylesheet" href="css/animate-css/animate.min.css">
    <link rel="stylesheet" href="css/lobipanel/lobipanel.min.css">
    <link rel="stylesheet" href="css/select2/select2.min.css">
    <link rel="stylesheet" href="css/main.css">

    <script src="js/modernizr/modernizr.min.js"></script>
        <script src="js/jquery/jquery-2.2.4.min.js"></script>
        <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="js/sweetalert2.all.min.js"></script>
</head>
<body class="top-navbar-fixed">
<div class="main-wrapper">
    <?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="row page-title-div">
                        <div class="col-md-6">
                            <h2 class="title">Enter Theory Marks</h2>
                        </div>
                    </div>
                    <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 Theory Marks</li>
                            </ul>
                        </div>
                    </div>
                </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 Theory Marks</h5>
                                    </div>
                                </div>
                                <div class="panel-body">
                                    <form method="POST" action="save_marks.php">
                                        <div class="form-row">
                                            <div class="form-group col-md-4">
                                                <label for="exam_id">Select Exam:</label>
                                                <select id="exam_id1" name="exam_id1" class="form-control" required>
                                                    <option value="">Select Exam</option>
                                                    <?php while ($row = $examResult->fetch_assoc()) { ?>
                                                        <option value="<?= $row['id'] ?>"><?= $row['exam_type'] . " - " . $row['exm_year'] ?></option>
                                                    <?php } ?>
                                                </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 while ($row = $classResult->fetch_assoc()) { ?>
                                                        <option value="<?= $row['Class_id'] ?>"><?= $row['class_name'] . " - " . $row['section'] ?></option>
                                                    <?php } ?>
                                                </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>
                                                </select>
                                            </div>
                                        </div>

                                        <div id="subject-marks">
                                            <!-- Subject marks fields will be populated here via AJAX -->
                                        </div>
 <div class="form-group col-md-4"><label>&nbsp;</label>

                                        <button style="width:300px" type="submit" name="submit" class="btn btn-primary">Save Marks</button>
                                    </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

            </div>
        </div>
    </div>
</div>

<?php
$conn->close();
?>

             <script src="js/jquery/jquery-2.2.4.min.js"></script>
<script>
    $(document).ready(function () {
        // Fetch students based on selected class
        $('#class_id').change(function () {
            var classId = $(this).val();
            $.ajax({
                type: 'POST',
                url: 'get_students_markedit.php',
                data: {classId: classId},
                success: function (response) {
                    $('#student_id').html(response);
                    $('#subject-marks').empty(); // Clear subjects when class changes
                },
                error: function () {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: 'An error occurred while fetching students.'
                    });
                }
            });
        });

        // Fetch subjects when student is selected
        $('#student_id').change(function () {
            var studentId = $(this).val();
            var classId = $('#class_id').val();
            var examId = $('#exam_id1').val();

            if (studentId && classId && examId) {
                $.ajax({
                    type: 'POST',
                    url: 'get_subjects_marksenter.php',
                    data: {studentId: studentId, classId: classId, examId: examId},
                    success: function (response) {
                        $('#subject-marks').html(response);
                    },
                    error: function () {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: 'An error occurred while fetching subjects.'
                        });
                    }
                });
            } else {
                $('#subject-marks').empty(); // Clear subjects if any field is missing
            }
        });

        // Input validation for theory marks fields
        $('#subject-marks').on('input', '.theory-marks-input', function () {
            var enteredMarks = parseFloat($(this).val());
            var maxMarks = parseFloat($(this).data('theory-max-marks'));

            if (enteredMarks > maxMarks) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Warning',
                    text: 'Entered marks cannot exceed maximum theory marks (' + maxMarks + ')!'
                });
                $(this).val(''); // Reset the input value
            }
        });

        // Handle form submission with validation
        $("form").submit(function (e) {
            e.preventDefault(); // Prevent traditional form submission

            var studentId = $('#student_id').val();
            var classId = $('#class_id').val();
            var examId = $('#exam_id1').val();

            // Check for required fields
            if (!studentId || !classId || !examId) {
                Swal.fire({
                    icon: 'error',
                    title: 'Missing Fields',
                    text: 'Please select a student, class, and exam.'
                });
                return;
            }

            // Ensure all marks are entered
            var allMarksEntered = true;
            $('#subject-marks .marks-input').each(function () {
                if ($(this).val() === '') {
                    allMarksEntered = false;
                    return false; // Stop the loop if any mark field is empty
                }
            });

            if (!allMarksEntered) {
                Swal.fire({
                    icon: 'error',
                    title: 'Missing Marks',
                    text: 'Please enter marks for all subjects.'
                });
                return;
            }

            // Show the data that will be submitted in the request (debugging purpose)
            console.log($(this).serialize());  // Log serialized form data to console for debugging

            $.ajax({
    type: 'POST',
    url: 'save_marks.php',  // Path to your PHP save script
    data: $(this).serialize(),  // Serialize form data
    dataType: 'json',
    success: function (response) {
        if (response.status === 'success') {
            Swal.fire({
                icon: 'success',
                title: 'Success',
                text: response.message
            });
        } else {
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: response.message
            });
        }
    },
    error: function () {
        Swal.fire({
            icon: 'error',
            title: 'Error',
            text: 'An error occurred while submitting the marks.'
        });
    }
});
});
    });
</script>



<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>
</body>
</html>
