<?php
include('session_validator.php');
?>
<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/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 Subject Combination</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> Subjects</li>
                                        <li class="active">Add Subject Combination</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 Subject Combination</h5>
                                                </div>
                                            </div>
                                            <div class="panel-body">
<?php
    // Include your database connection file
    include("includes/db.php");

    // Fetch classes and subjects from the database
$classQuery = "SELECT * FROM classes";
$subjectQuery = "SELECT * FROM subjects";

$classResult = $conn->query($classQuery);
$subjectResult = $conn->query($subjectQuery);


?>

        <form id="assignSubjectForm">
            <div>
        <label for="class_id">Select Class:</label>
        <select id="class_id" name="class_id"  class="form-control col-md-3" required>
            <option value="">Select Class</option>
            <?php
            while ($classRow = $classResult->fetch_assoc()) {
                echo "<option value=\"{$classRow['Class_id']}\">{$classRow['class_name']}"." - "."{$classRow['section']}</option>";
            }
            ?>
        </select>
    </div> <br><br>            <div id="remaining-subjects-list">
                <!-- Remaining subjects list for selection will be populated here -->
            </div> <br>

            <button type="submit" name="remaining_subjects" class="btn btn-primary">Assign Subjects</button>

            <div id="assigned-subjects-table">
                <!-- Assigned subjects table will be populated here -->
            </div>
        </form>
    </div>


    <?php

      if ($_SERVER["REQUEST_METHOD"] == "POST" &&  isset($_POST["remaining_subjects"])) {
        $classId = $conn->real_escape_string($_POST["class_id"]);
        $selectedSubjects = $_POST["remaining_subjects"];

        // Iterate through selected subjects and insert into class_subject_mapping table
        foreach ($selectedSubjects as $subjectId) {
            // Check if the mapping already exists (optional)
            $checkQuery = "SELECT * FROM class_subject_mapping WHERE class_id = '$classId' AND subject_id = '$subjectId'";
            $checkResult = $conn->query($checkQuery);

            if ($checkResult->num_rows == 0) {
                // Fetch subject name from subjects table based on subjectId
                $subjectNameQuery = "SELECT subject_name FROM subjects WHERE id = '$subjectId'";
                $subjectNameResult = $conn->query($subjectNameQuery);
                $subjectRow = $subjectNameResult->fetch_assoc();
                $subjectName = $subjectRow["subject_name"];

                // Insert subject into class_subject_mapping table
                $insertQuery = "INSERT INTO class_subject_mapping (class_id, subject_id, subject_name) VALUES ('$classId', '$subjectId', '$subjectName')";

    if ($conn->query($insertQuery) === TRUE) {
        // Student added successfully
        echo "Subject Assigned successfully!";
    } else {
        // Error occurred while adding student
        echo "Error: " . $insertQuery . "<br>" . $conn->error;
    }

    }
}
}

    // Close the database connection
    $conn->close();

?>

                                                </form>

                                            </div>
                                        </div>
                                    </div>
                                    <!-- /.col-md-12 -->
                                </div>
                    </div>
                </div>
                <!-- /.content-container -->
            </div>
            <!-- /.content-wrapper -->
        </div>
        <!-- /.main-wrapper -->
        <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/select2/select2.min.js"></script>
        <script src="js/main.js"></script>

    </body>
</html>


    <script>
         // Fetch classes from the database and populate the class select option
            $(document).ready(function () {
                // Handle class selection change
                $('#studentClass').change(function () {
                    var classId = $(this).val();

                    // Update class ID span with the selected class ID
                    $('#classID').text(classId);

                    // Add additional logic here to fetch and display students based on the selected class
                });

    });

        // Fetch assigned subjects and remaining subjects based on the selected class
        $(document).ready(function () {
            $('#class_id').on('change', function () {
                var classId = $(this).val();

                // Fetch assigned subjects for the selected class via AJAX
                $.ajax({
                    type: 'POST',
                    url: 'get_assigned_subjects.php', // PHP script to fetch assigned subjects based on class
                    data: { class_id: classId },
                    success: function (assignedSubjectsData) {
                        // Populate assigned subjects table
                        $('#assigned-subjects-table').html(assignedSubjectsData);
                    }
                });

                // Fetch remaining subjects for the selected class via AJAX
                $.ajax({
                    type: 'POST',
                    url: 'get_remaining_subjects.php', // PHP script to fetch remaining subjects based on class
                    data: { class_id: classId },
                    success: function (remainingSubjectsData) {
                        // Populate remaining subjects list
                        $('#remaining-subjects-list').html(remainingSubjectsData);
                    }
                });
            });

            // Form submission via AJAX
            $('#assignSubjectForm').submit(function (e) {
                e.preventDefault();

                // Serialize form data
                var formData = $(this).serializeArray();

                // Submit form data via AJAX
                $.ajax({
                    type: 'POST',
                    url: 'assign_subject.php', // PHP script to handle form submission
                    data: formData,
                    success: function (response) {
                        // Handle success response here (e.g., display success message)
                        console.log(response);
                    },
                    error: function (error) {
                        // Handle error response here (e.g., display error message)
                        console.error(error);
                    }
                });
            });
        });
    </script>


</body>

</html>
