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

// Handle form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $class_sec = $_POST['class_id'];
    $std_symbolnumber = !empty($_POST['std_symbolnumber']) ? $_POST['std_symbolnumber'] : NULL; // Set to NULL if empty
    $std_id = $_POST['std_id_visible'];
    $student_name = $_POST['student_name'];
    $subject_id = $_POST['subject_id'];
    $marks = $_POST['marks'];
    $entered_by = $_POST['teacher_name'];
    $date = $_POST['feedate'];

    // Insert data into the leftover_marks table
    $insertQuery = "INSERT INTO leftover_marks (class_sec, std_symbolnumber, std_id, student_name, subject_id, marks, entered_by, date) 
                    VALUES ('$class_sec', " . ($std_symbolnumber !== NULL ? "'$std_symbolnumber'" : "NULL") . ", 
                            '$std_id', '$student_name', '$subject_id', '$marks', '$entered_by', '$date')";
    
    if ($conn->query($insertQuery) === TRUE) {
        $message = "Marks successfully entered!";
    } else {
        $message = "Error: " . $conn->error;
    }
}

// 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/styles.css">
<link rel="stylesheet" href="css/main.css">

  <script src="js/jquery/jquery-2.2.4.min.js"></script>
<script src="js/modernizr/modernizr.min.js"></script>
<script src="nepali.datepicker.v4.0.1/js/nepali.datepicker.v4.0.1.min.js"></script>

<style type="text/css">
    #studentNameList {
        position: absolute;
        z-index: 1000;
        width: 100%;
        background-color: #fff;
        border: 1px solid #ccc;
        max-height: 200px;  /* Set a limit for how tall the list can be */
        overflow-y: auto;
        padding: 0;
        margin-top: 2px;  /* Adjust the space between input and the list */
    }

    .list-group-item {
        padding: 5px 10px;  /* Reduce padding inside each list item */
        font-size: 14px;    /* Smaller font size for a more compact look */
        line-height: 1.2;   /* Decrease line height for a tighter list */
        margin: 0;          /* Remove extra margins */
        border-bottom: 1px solid #ddd;  /* Subtle divider between items */
        cursor: pointer;
    }

    .list-group-item:last-child {
        border-bottom: none;  /* Remove the border from the last item */
    }

    .list-group-item:hover {
        background-color: #f1f1f1;  /* Add a hover effect for better UX */
    }
     /* 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 style="margin-left:5%; margin-right: 5%;">

        <h2>Enter Missing Marks</h2>

    <div class="panel" >
        <div class="panel-body" >
<!-- Loading GIF -->
<div id="loading" style="display:none;">
    <img src="loading.gif" alt="Loading..." />
</div>

<!-- Form -->
<form id="missingmarks" method="POST"  action="">
            <div class="row">
           
<div class="form-group col-md-3">
                <label for="feedate">Marks Entered Date:</label>
                <input type="text" class="form-control" id="feedate_visible" disabled>
                <input type="hidden" id="feedate" name="feedate">
            </div>
            <div class="form-group col-md-4">
                <label for="std_symbolnumber">Student Symbol Number:</label>
                <input type="text" class="form-control" id="std_symbolnumber" name="std_symbolnumber">
            </div>
        </div>
        <div class="row">

            <div class="form-group col-md-9">
                <label for="manual_entry_checkbox" style="color:red"><b> <input type="checkbox" id="manual_entry_checkbox">सिम्बोल नं. थाहा नभएमा यहाँ थिच्नुहोस् र विद्यार्थीको नाम अंग्रेजीमा प्रविष्ट गर्नुहोस्। </b> </label>
                
</div>
</div>
       <div class="row">
             <input type="hidden" class="form-control" id="std_id_visible" name="std_id_visible">

            <div class="form-group col-md-3">
                <label for="student_name">Student Name:</label>
                <input type="hidden" class="form-control" id="student_name1" name="student_name1" >
                <input type="text" class="form-control" id="student_name" name="student_name" autocomplete="off">
    <div id="studentNameList" class="list-group"></div> <!-- Container for autocomplete suggestions -->
</div>



                
        <div class="form-group col-md-2">
                <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-2">
                <label for="subject_id">Subject:</label>
                <select class="form-control" id="subject_id" name="subject_id" required>
                    <option value="">Select Subject</option>
                </select>
            </div>
</div>
 <div class="row">
            <div class="form-group col-md-3">
                <label for="marks">Marks:</label>
                <input type="number" class="form-control" id="marks" name="marks" step="0.01" required>
            </div>


            <div class="form-group col-md-3">
                <label for="entered_by">Entered By:</label>
                <input type="text" class="form-control" id="teacher_name" name="teacher_name"  placeholder="Search teacher name...">
                <div id="teacherNameList" class="list-group"></div> <!-- Container for autocomplete suggestions -->
            </div>
            

            <div class="form-group col-md-3">
                <label for="entered_by">.</label>
                <button type="submit" class="btn btn-primary">Submit</button>
            </div>
        </div>
        </form>



         <div class="form-group col-md-9">
        <div class="form-group">
      <a href="index.php"> <button class="btn btn-primary">Back Home</button></a>
  
        <a href="marksentrypr.php"> <button style="margin-left:20px" class="btn btn-primary">Marks Entry [IN]</button></a>
         </div>
</div>



     </div>   <!-- Form End -->



    </div>
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://kit.fontawesome.com/a076d05399.js"></script> 
<script>
    // Handle form submission
    $('#missingmarks').on('submit', function(e) {
        e.preventDefault(); // Prevent the default form submission

        // Show loading GIF
        $('#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) {
                // Hide the loading GIF
                $('#loading').fadeOut();

                // Optionally handle the response (e.g., redirect to another page)
                window.location.href = 'thank_you.php'; // Redirect after successful submission
            },
            error: function(jqXHR, textStatus, errorThrown) {
                // Hide loading GIF if there's an error
                $('#loading').fadeOut();

                // Show error message
                alert('There was an error processing your request. Please try again.');
            }
        });
    });
</script>

<script>
// Autocomplete for Teacher Name
$(document).ready(function(){
    $('#teacher_name').keyup(function(){
        var query = $(this).val();
        if (query != '') {
            $.ajax({
                url: "fetch_teacher_names.php",
                method: "POST",
                data: {query: query},
                success: function(data) {
                    $('#teacherNameList').fadeIn();
                    $('#teacherNameList').html(data);
                }
            });
        } else {
            $('#teacherNameList').fadeOut();
        }
    });

   // Handle the selection from the list
    $(document).on('click', '.teacher-name-item', function () {
        $('#teacher_name').val($(this).text());  // Set the clicked name as the input value
        $('#teacherNameList').fadeOut();  // Hide the suggestions
    });
});
</script>
    <script>
    $(document).ready(function () {
        $('#std_symbolnumber').on('blur', function () {
            var symbolNumber = $(this).val();
            if (symbolNumber) {
                $.ajax({
                    url: 'get_student_details_leftover.php',
                    type: 'POST',
                    data: { symbol_no: symbolNumber },
                    success: function (response) {
                        if (response) {
                            var studentData = JSON.parse(response);
                            $('#student_name').val(studentData.name).prop('', true);
                            $('#student_name1').val(studentData.name).prop('disabled', true);
                            $('#std_id_visible').val(studentData.student_id);
                        } else {
                            $('#student_name').val('').prop('disabled', true);
                            alert('Student not found!');
                        }
                    }
                });
            } else {
                $('#student_name').val('').prop('', true);
            }
        });

        $('#manual_entry_checkbox').on('change', function () {
            if ($(this).is(':checked')) {
                $('#student_name').prop('disabled', false);
                $('#std_symbolnumber').val('');
            } else {
                $('#student_name').prop('disabled', true).val('');
            }
        });

        $('#class_id').change(function () {
            var classId = $(this).val();
            $('#subject_id').html("<option value=''>Select Subject</option>");
            fetch(`getSubjects.php?class_id=${classId}`)
                .then(response => response.json())
                .then(data => {
                    data.forEach(subject => {
                        $('#subject_id').append(`<option value='${subject.id}'>${subject.subject_name}</option>`);
                    });
                });
        });

        $('#feedate_visible').val(NepaliFunctions.ConvertDateFormat(NepaliFunctions.GetCurrentBsDate(), "YYYY-MM-DD"));
        $('#feedate').val(NepaliFunctions.ConvertDateFormat(NepaliFunctions.GetCurrentBsDate(), "YYYY-MM-DD"));
    });
    </script>

<script>$(document).ready(function () {
    $('#student_name').on('keyup', function () {
        var query = $(this).val();  // Get the input value

        if (query.length > 0) {
            $.ajax({
                url: 'fetch_student_names.php', // PHP script to fetch data from DB
                method: 'POST',
                data: { query: query },  // Send the query to the server
                success: function (data) {
                    $('#studentNameList').fadeIn();  // Show the suggestions
                    $('#studentNameList').html(data); // Populate the list with fetched data
                }
            });
        } else {
            $('#studentNameList').fadeOut();  // Hide suggestions if no query is entered
        }
    });

    // Handle the selection from the list
    $(document).on('click', '.student-name-item', function () {
        $('#student_name').val($(this).text());  // Set the clicked name as the input value
        $('#studentNameList').fadeOut();  // Hide the suggestions
    });
});

</script>

</div>
</body>

</html>
