<?php
include('session_validator.php');
include("includes/db.php");
$sessions = $conn->query("SELECT year_id, ay_bs, status FROM academic_years ORDER BY ay_bs DESC")->fetch_all(MYSQLI_ASSOC);
$active_session = null;
foreach ($sessions as $sess) {
    if ($sess['status'] === 'active') {
        $active_session = $sess['year_id'];
        break;
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <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/prism/prism.css">
    <link rel="stylesheet" href="nepali.datepicker.v4.0.1/css/main.css">
    <title>Grade Sheet Generator</title>

    <style>
        .form-control { font-size: 12px; padding: 2px; }
        select.form-control { font-size: 12px; height: 25px; }
        input.form-control { font-size: 12px; height: 25px; }
        button { color: white; background: green; font-size: 12px; padding: 2px; }
    </style>
</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="panel-body">
                    <div class="container-fluid">
                        
                        <form id="gradesheetForm" action="student_results.php" method="post">
            <div class="row">
               <div class="form-group col-md-3">       
<select name="session_id" id="session_id" class="form-control" required>
                                            <option value="">Select Session</option>
                                            <?php foreach ($sessions as $s): ?>
                                                <option value="<?= $s['year_id'] ?>" <?= $s['year_id'] == $active_session ? 'selected' : '' ?>>
                                                    <?= $s['year_id'].' - '. $s['ay_bs'] ?><?= $s['status'] == 'active' ? ' (Active)' : '' ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
</div>

  </div>          
  <div class="row">

                <div class="form-group col-md-2">
            <label for="exam_id">Select Exam:</label>
            <select id="exam_id" name="exam_id" class="form-control" required>
                <option value="">Select Exam</option>
                    <?php
                    // Include the database configuration file
                    include("includes/db.php");

                    // Fetch class names from the 'classes' table
                    $queryexam = "SELECT id, exm_year , exam_type FROM examination_type";
                    $resultexam = $conn->query($queryexam);

                    // Populate the dropdown with class names and sections
                    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-2">
               <label for="class_id">Select Class:</label>
                    <select name="class_id" id="class_id" class="form-control" required onchange="updateCheckedBy()">
    <option value="">Select Class</option>
    <?php
    $classQuery = "SELECT class_id, class FROM classes WHERE status = 1";
    $classResult = $conn->query($classQuery);

    if ($classResult) {
        while ($row = $classResult->fetch_assoc()) {
            echo "<option value='{$row['class_id']}'>{$row['class']}</option>";
        }
    }
    ?>
</select>

       </div>
             <div class="form-group col-md-2">
               <label for="section_id">Select Section:</label>
                    <select name="section_id" id="section_id" class="form-control" required onchange="updateCheckedBy()">
    <option value="">Select Section</option>
    <?php
    $sectionQuery = "SELECT section_id, section_name FROM sections WHERE status = 1";
    $sectionResult = $conn->query($sectionQuery);

    if ($sectionResult) {
        while ($row = $sectionResult->fetch_assoc()) {
            echo "<option value='{$row['section_id']}'>{$row['section_name']}</option>";
        }
    }
    ?>
</select>

       </div>
          <div class="form-group col-md-2">
            <label for="chkby"> Checked By:</label>
                <input type="text" id="checked_by" name="checked_by" class="form-control" placeholder="select class first" />
        </div>


      
        
        <div class="form-group col-md-2">
            <label for="prepby"> Prepared By:</label>
                <select name="prepared_by" id="prepared_by" class="form-control" required>
                                                    <!-- Populate this dropdown as needed -->
                    <option value="Saurav Neupane">Saurav Neupane</option>
                    <option value="Dambaru Ballav Ojha">Dambaru Ballav Ojha</option>
                    <!-- Add more options as needed -->
                    </select>
                </div>

                <div class="form-group col-md-2">
    <label for="result_date">Result Publishing Date:</label>
    <input type="text" id="result_date" name="result_date" class="form-control"  placeholder="Select Exam and Class" />
</div>



                <div class="form-group col-md-2">
            <label for="duplicateissuedate"> Duplicate issue date: </label>
                <input type="" id="duplicateissuedate" name="duplicateissuedate" class="form-control"  />
       </div>
            </div>
<div class="form-group col-md-2">
<button type="submit" class="form-control" style=" color:white; background:green">Show Gradesheets
                                                </button>
                                            </div>
                                            </form>
                    </div>
                </div>

                     <!-- AJAX Student List -->
                    <div class="panel-body" id="studentList"></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/main.js"></script>
    <script src="js/modernizr/modernizr.min.js"></script>
    <link href="nepali.datepicker.v4.0.1/css/nepali.datepicker.v4.0.1.min.css" rel="stylesheet" type="text/css" />
    <script src="nepali.datepicker.v4.0.1/js/nepali.datepicker.v4.0.1.min.js"></script>
<script>
        window.onload = function () {
            $('#feedate_visible').val(NepaliFunctions.ConvertDateFormat(NepaliFunctions.GetCurrentBsDate(), "YYYY-MM-DD"));
        // $('#issuedate').val(NepaliFunctions.ConvertDateFormat(NepaliFunctions.GetCurrentBsDate(), "YYYY-MM-DD"));
            var mainInput1 = document.getElementById("duplicateissuedate");
            mainInput1.nepaliDatePicker({
                ndpYear: true,
                ndpMonth: true,
                ndpYearCount: 100,
            })
        };

 function updateCheckedBy() {
    var classId   = $('#class_id').val();
    var sectionId = $('#section_id').val();

    if (!classId || !sectionId) return;

    $.ajax({
        type: "POST",
        url: "get_class_teacher.php",
        data: {
            class_id: classId,
            section_id: sectionId
        },
        success: function (response) {
            $('#checked_by').val(response);
        }
    });
}


    function fetchResultDate() {
    var examId = document.getElementById("exam_id").value;
    var classId = document.getElementById("class_id").value;

    if (examId && classId) {
        // Use AJAX to fetch the result publishing date
        $.ajax({
            type: "POST",
            url: "get_result_date.php", // Create a PHP file to handle this request
            data: {
                exam_id: examId,
                class_id: classId
            },
            success: function (response) {
                document.getElementById("result_date").value = response || "No Date Found";
            },
            error: function () {
                document.getElementById("result_date").value = "Error Fetching Date";
            }
        });
    }
}

// Attach the function to the onchange event of the dropdowns
document.getElementById("exam_id").addEventListener("change", fetchResultDate);
document.getElementById("class_id").addEventListener("change", fetchResultDate);

    </script>
    <script>
        $(document).ready(function() {
            // Submit form using AJAX
            $('#gradesheetForm').submit(function(event) {
                event.preventDefault(); // Prevent form submission
                // var session_id = $('#session_id').val();
                var examId = $('#exam_id').val();
                var classId = $('#class_id').val();
                var duplicateissuedate = $('#duplicateissuedate').val();
                var checked_by = $('#checked_by').val();
                var prepared_by = $('#prepared_by').val();
                var result_date = $('#result_date').val();
                 var section_id = $('#section_id').val();
                // var session_id = $('#session_id').val();

                if (examId && classId) {
                    $.ajax({
                        type: "POST",
                        url: "student_results.php",  // PHP file to fetch student list
                        data: {
    // session_id: session_id,
    exam_id: examId, 
    class_id: classId,
    duplicateissuedate: duplicateissuedate,
    checked_by: checked_by,
    prepared_by: prepared_by,
    result_date: result_date,
    section_id: section_id

},

                        success: function(response) {
                            $('#studentList').html(response);  // Display student list
                        },
                        error: function() {
                            $('#studentList').html('<p>Error fetching student list.</p>');
                        }
                    });
                } else {
                    $('#studentList').html('<p>Please select both exam and class.</p>');
                }
            });
        });
    </script>
</body>
</html>
