<?php
	require_once("../../public/connection.php");
	require_once("../../public/functions.php");
?>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (isset($_POST['selected_students'])) {
        $selected_students = $_POST['selected_students'];
        $class = mysqli_real_escape_string($connection, $_POST['class']);
        $subject = mysqli_real_escape_string($connection, $_POST['subject']);
        $term = mysqli_real_escape_string($connection, $_POST['term']);
        $session = mysqli_real_escape_string($connection, $_POST['session']);

        $success_count = 0;
        $duplicate_count = 0;

        foreach ($selected_students as $reg_number) {
            $reg_number = mysqli_real_escape_string($connection, $reg_number);
            $name_query = "SELECT firstname, othername, lastname FROM students WHERE reg_number = '$reg_number'";
            $name_result = mysqli_query($connection, $name_query);

            if ($name_row = mysqli_fetch_assoc($name_result)) {
                $full_name = $name_row['firstname'] . " " . $name_row['othername'] . " " . $name_row['lastname'];
                $registration_date = date("Y-m-d");
                $registration_time = date("H:i:s");

                // Check for duplicates
                $check_query = "SELECT * FROM `subjects` WHERE `reg_number` = '$reg_number' AND `class` = '$class' AND `subjects` = '$subject' AND `term` = '$term' AND `session` = '$session'";
                $check_result = mysqli_query($connection, $check_query);

                if (mysqli_num_rows($check_result) == 0) {
                    // Insert into the `subjects` table
                    $insert_query = "INSERT INTO `subjects` (`name`, `reg_number`, `class`, `subjects`, `term`, `session`, `registration_date`, `registration_time`)
                                     VALUES ('$full_name', '$reg_number', '$class', '$subject', '$term', '$session', '$registration_date', '$registration_time')";
                    if (mysqli_query($connection, $insert_query)) {
                        $success_count++;
                    }
                } else {
                    $duplicate_count++;
                }
            }
        }

        // Set session message and redirect
        $_SESSION['message'] = "✅ Successfully registered $success_count students. ❌ $duplicate_count duplicates skipped.";
        header("Location: register_student_subjects.php");
        exit();
    } else {
        $_SESSION['message'] = "⚠️ No students selected!";
        header("Location: register_student_subjects.php");
        exit();
    }
} else {
    header("Location: register_student_subjects.php"); // Redirect if accessed directly
    exit();
}
?>
