<?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 tags, title, and stylesheets can be added here -->
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <link rel="stylesheet" href="styles.css"> <!-- Include your custom styles here -->
    <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="nepali.datepicker.v4.0.1\css\main.css" media="screen">
    <link rel="stylesheet" href="css\sweet-alert\sweetalert.css" media="screen">
    <!-- Include jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>

    <!-- Include SweetAlert -->
    <script src="js/sweetalret.js"></script>

    <script>
        $(document).ready(function () {
            $('#student-marks-list').on('input', '.marks-input', function () {
                var enteredMarks = parseFloat($(this).val());
                var theoryFullMarks = parseFloat($('#theory-full-marks').val());

                if (enteredMarks > theoryFullMarks) {
                    // Display red alert for the specific input using SweetAlert
                    Swal.fire({
                        icon: 'error',
                        title: 'Invalid Marks',
                        text: 'Entered marks cannot exceed theory full marks!',
                    });

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

            // Event handler for form submission
            $('form').submit(function (event) {
                var invalidMarksInputs = $('.marks-input.is-invalid');

                if (invalidMarksInputs.length > 0) {
                    // Prevent form submission if there are invalid marks inputs
                    event.preventDefault();
                }
            });
        });
    </script>
    <style>
        /* Loading styles */
        #loading {
            display: none; /* Hide loading by default */
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(255, 255, 255, 0.8);
            z-index: 9999;
            text-align: center;
        }
    </style>
</head>

<body>

    <div class="container">
        <h2>Enter Marks</h2>
        <form id="marksentry" method="POST" action="process_marksentry.php" enctype="multipart/form-data">
            <div class="form-row">
                <div class="form-group col-md-3">
                    <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['id'] . "-" . $row['exam_type'] . " - " . $row['exm_year'] . "</option>";
                        }
                        ?>
                    </select>
                </div>

                <div class="form-group col-md-3">
                    <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 WHERE status = 'on'";
        
                        $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="subject_id">Select Subject:</label>
                    <select id="subject_id" name="subject_id" class="form-control" required>
                        <option value="">Select Subject</option>
                    </select>
                </div>
            </div>
<!-- 
            <div>
                <p><b><span style="color: Red;" id="theory-full-marks"></span></b></p>
            </div> -->

            <div class="form-group" id="student-marks-list">
                <!-- Student marks entry fields will be populated here using AJAX -->
            </div>

            <button type="submit" name="submit" class="btn btn-primary">Submit Marks</button>
        </form>
        
<!-- Loading GIF -->
<div id="loading">
    <img src="includes/loader.gif" alt="Loading..." style="margin-top:20%; width: 100px; height: auto;">
    <h4>Processing your request, please wait...</h4>
</div>

<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://kit.fontawesome.com/a076d05399.js"></script> <!-- Font Awesome for voice icon -->
        <br>

    <div class="form-row">
        <div class="form-group">
      <a href="index.php"> <button class="btn btn-primary">Back Home</button></a>
  </div>
<div class="form-group">
        <a href="marksentrypr.php"> <button style="margin-left:20px" class="btn btn-primary">Marks Entry [IN]</button></a>
         </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/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 () {
                $('#subject_id').change(function () {
                    var subjectId = $(this).val();

                    // AJAX request to fetch internal full marks for the selected subject
                    $.ajax({
                        type: 'POST',
                        url: 'get_theory_full_marks.php', // PHP script to handle the request and fetch internal full marks
                        data: { subjectId: subjectId },
                        success: function (response) {
                            if (response === "N/A") {
                                $('#theory-full-marks').text("Not available");
                            } else {
                                $('#theory-full-marks').text(response);
                            }
                        }
                    });
                });
            });
        </script>

        <script>
            $(document).ready(function () {
                // Function to fetch and populate students based on class and subject
                function fetchStudents(classId, subjectId) {
                    $.ajax({
                        type: 'POST',
                        url: 'get_students.php',
                        data: { 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 class selection
                $('#class_id').change(function () {
                    var classId = $(this).val();
                    var subjectId = $('#subject_id').val();

                    // Fetch and populate students based on class and subject
                    fetchStudents(classId, subjectId);
                });

                // Event handler for subject selection
                $('#subject_id').change(function () {
                    var subjectId = $(this).val();
                    var classId = $('#class_id').val();

                    // Fetch and populate students based on class and subject
                    fetchStudents(classId, subjectId);
                });
            });
        </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>
             <script>

//       $(document).ready(function() {
//     $('#marksentry').on('submit', function(e) {
//         e.preventDefault(); // Prevent the default form submission

//         // Show loading indicator if necessary
//         $('#loading').fadeIn();

//         // Use AJAX to submit the form
//         $.ajax({
//             url: $(this).attr('action'), // Use form action
//             type: $(this).attr('method'), // Use form method
//             data: new FormData(this), // Send form data
//             contentType: false,
//             processData: false,
//             success: function(response) {
             
//                 window.location.href = 'thank_you.php';
//             },
//             error: function(jqXHR, textStatus, errorThrown) {
//                 // Handle errors here (e.g., show an error message)
//                 alert('There was an error processing your request. Please try again.');
//                 $('#loading').fadeOut(); // Hide loading GIF if there is an error
//             }
//         });
//     });
// });
        </script>
        
        <div class="main" style="margin-left:10px" >
        <?php
        include("includes/db.php");

        // Fetch distinct class-sections and their corresponding subjects
        $classSectionQuery = "SELECT DISTINCT classes.class_name, classes.section, subjects.subject_code, subjects.subject_name, COUNT(marks.marks) AS num_students
                              FROM classes
                              INNER JOIN marks ON classes.class_id = marks.class_id
                              INNER JOIN subjects ON marks.subject_id = subjects.id
                              WHERE marks.marks > 0
                              GROUP BY classes.class_name, classes.section, subjects.subject_code, subjects.subject_name
                              ORDER BY subject_code";
        $classSectionResult = $conn->query($classSectionQuery);

        if ($classSectionResult->num_rows > 0) {
            $currentClass = "";
            $currentSection = "";
?>
        
    <h2>Marks Submitted Report</h2>
   <table  id="subjectsTable" class="display"> 
  <?php          echo "
  <thead> <tr><th>Class</th><th>Subject Code</th><th>Subject Name</th><th>Number of Students with > 0 Marks</th></tr> </thead>";

            while ($row = $classSectionResult->fetch_assoc()) {
                $className = $row['class_name'];
                $section = $row['section'];
                $subjectCode = $row['subject_code'];
                $subjectName = $row['subject_name'];
                $numStudents = $row['num_students'];

                echo "<tr>";
                echo "<td>$className  -  $section</td>";
                               echo "<td>$subjectCode</td>";
                echo "<td>$subjectName</td>";
                echo "<td>$numStudents</td>";
                echo "</tr>";
            }
?>
    
</table>
<?php
        } else {
            echo "<p>No data found.</p>";
        }
        ?>
   
   
    </body>

</html>
