<!DOCTYPE html>
<html lang="en">

<head>
    <title>Assign Subjects</title>
    <!-- Include your CSS and other necessary files here -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <!-- DataTables CSS -->
    <link rel="stylesheet" href="css/jquery.dataTables.min.css">
    <!-- DataTables JavaScript -->
    <script src="js/jquery.dataTables.min.js"></script>
    <style>
        /* Example DataTable styling */
#studentTable {
    width: 100%;
}

        /* Add your CSS styles here */
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            padding: 20px;
        }

        .container {
            max-width: 800px;
            margin: 0 auto;
            background-color: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }

        th, td {
            padding: 15px;
            text-align: left;
        }

        th {
            background-color: #4caf50;
            color: white;
        }

        tr:nth-child(even) {
            background-color: #f2f2f2;
        }

        .action-buttons a {
            text-decoration: none;
            margin-right: 10px;
            color: #4caf50;
        }
    </style>
</head>

<body>
    <?php
    // Include your database connection file
    include("includes/db.php");
    include("header.php");

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

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


?>
  

    <div class="container">
        <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>
            <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();

?>

    <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>
