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


// Function to sanitize user inputs
function sanitizeInput($input) {
    return htmlspecialchars(stripslashes(trim($input)));
}

// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) {
    $classId = sanitizeInput($_POST['class_id']);
    $examType = sanitizeInput($_POST['exam_type']);
    $subjectDates = $_POST['subject_date'];
    $examyear = $_POST['exm_year'];

    // Process each subject and its date
    foreach ($subjectDates as $subjectId => $examDate) {
        // Check for duplicate entry
        $checkDuplicate = $conn->prepare("SELECT id FROM examination_routine WHERE class_id = ? AND subject_id = ?");
        $checkDuplicate->bind_param("ii", $classId, $subjectId);
        $checkDuplicate->execute();
        $duplicateResult = $checkDuplicate->get_result();

        if ($duplicateResult->num_rows > 0) {
            echo "Examination routine for the selected class and subject already exists. Please update it.";
        } else {
            // Insert into database
        $insertQuery = $conn->prepare("INSERT INTO examination_routine (class_id, exam_type, exam_year, subject_id, exam_date) VALUES (?, ?, ?, ?, ?)");
            $insertQuery->bind_param("isiis", $classId, $examType, $examyear, $subjectId, $examDate);

            if ($insertQuery->execute()) {
                echo "Examination routine added successfully!";
            } else {
                echo "Error adding examination routine. Please try again.";
            }
        }
    }
}

// Fetch classes for dropdown
$fetchClassesQuery = "SELECT class_id, class_name ,section FROM classes";
$classesResult = $conn->query($fetchClassesQuery);
$classes = [];

if ($classesResult->num_rows > 0) {
    while ($row = $classesResult->fetch_assoc()) {
        $classes[] = $row;
    }
}

// Fetch subjects based on selected class
$selectedClassId = isset($_POST['class_id']) ? $_POST['class_id'] : null;

if ($selectedClassId) {
    $fetchSubjectsQuery = "SELECT subjects.id, subjects.subject_name FROM subjects 
                            INNER JOIN class_subject_mapping ON subjects.id = class_subject_mapping.subject_id 
                            WHERE class_subject_mapping.class_id = $selectedClassId";
    $subjectsResult = $conn->query($fetchSubjectsQuery);
    $subjects = [];

    if ($subjectsResult->num_rows > 0) {
        while ($row = $subjectsResult->fetch_assoc()) {
            $subjects[] = $row;
        }
    }
}

$conn->close();
?>
<!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="nepali.datepicker.v4.0.1/css/main.css" media="screen">
        <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">Add Exam Routine</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> Exam</li>
                                        <li class="">Add Exam Routine</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>Add Exam Routine</h5>
                                                </div>
                                            </div>


                                            <div class="panel-body">

                                    <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
                   <div class="form-row">


            <div class="form-group col-md-3">
                <label for="class_id">Select Year:</label>
                <select id="exm_year" name="exm_year" class="form-control" required>
                    <option value="">Select Year</option>
                     <?php
    // Include database connection
    include("includes/db.php");

    // Fetch exam types from the database
    $fetchExamTypesQuery = "SELECT DISTINCT exm_year FROM examination_type";
    $examTypesResult = $conn->query($fetchExamTypesQuery);

    // Check if there are rows returned
    if ($examTypesResult->num_rows > 0) {
        while ($row = $examTypesResult->fetch_assoc()) {
            // Output options for select field
            echo '<option value="' . $row['exm_year'] . '">' . $row['exm_year'] . '</option>';
        }
    }
    ?>

</select>
            </div>
       
                <div class="form-group col-md-3">
<label for="exam_type">Select Exam Type:</label>
<select id="exam_type" name="exam_type" class="form-control" required>
    <option value="">Select Exam Type</option>

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

    // Fetch exam types from the database
    $fetchExamTypesQuery = "SELECT id, exam_type, exm_year FROM examination_type";
    $examTypesResult = $conn->query($fetchExamTypesQuery);

    // Check if there are rows returned
    if ($examTypesResult->num_rows > 0) {
        while ($row = $examTypesResult->fetch_assoc()) {
            // Output options for select field
            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 foreach ($classes as $class) : ?>
                        <option value="<?php echo $class['class_id']; ?>"><?php echo $class['class_name'].'-'. $class['section'] ; ?></option>
                    <?php endforeach; ?>
                </select>
            </div>

   <div class="form-group col-md-4">
        
                <div id="subjectDates">
                    <!-- Subject and date fields will be dynamically added here based on class selection -->
                </div>
             </div>
                <input type="submit" name="submit" value="Create Routine" style="background: green; color: white; font-weight: bold;" class="form-control">
            </div>
            </form>
       

   <!-- Include necessary scripts -->
                                            <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/waypoint/waypoints.min.js"></script>
                                            <script src="js/counterUp/jquery.counterup.min.js"></script>
                                            <script src="js/toastr/toastr.min.js"></script>
                                            <script src="js/icheck/icheck.min.js"></script>
                                            <script src="js/main.js"></script>
                                            <script src="js/production-chart.js"></script>
                                            <script src="js/traffic-chart.js"></script>
                                            <script src="js/task-list.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>
    document.getElementById('class_id').addEventListener('change', function() {
        var classId = this.value;

        // Fetch subjects based on selected class via AJAX
        fetch('getSubjects_routine.php?class_id=' + classId)
            .then(response => response.json())
            .then(data => {
                var subjectDates = document.getElementById('subjectDates');
                subjectDates.innerHTML = '';

                data.forEach(subject => {
                    var div = document.createElement('div');
                    div.classList.add('form-group');

                    var label = document.createElement('label');
                    label.textContent = `${subject.subject_name}:`;
                    div.appendChild(label);

                    var input = document.createElement('input');
                    input.type = 'text';
                    input.name = `subject_date[${subject.id}]`;
                    input.classList.add('form-control');
                    input.required = true;
                    div.appendChild(input);

                    subjectDates.appendChild(div);

                    // Initialize Nepali Datepicker for each subject input
                    $(input).nepaliDatePicker({
                        ndpYear: true,
                        ndpMonth: true,
                        ndpYearCount: 100
                    });
                });
            })
            .catch(error => console.error('Error:', error));
    });
</script>
 
        <script src="nepali.datepicker.v4.0.1/js/main.js"></script>

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

      </body>
</html>