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

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['class_id']) && !empty($_POST['class_id'])) {
    $classId = $_POST['class_id'];
    $minSubjects = 2; // Minimum number of subjects allowed
    $maxSubjects = 7; // Maximum number of subjects allowed

    if (isset($_POST['subjects']) && is_array($_POST['subjects'])) {
        foreach ($_POST['subjects'] as $studentId => $selectedSubjects) {
            // Validate selected subjects count
            $subjectCount = count($selectedSubjects);
            if ($subjectCount < $minSubjects || $subjectCount > $maxSubjects) {
                echo "Invalid number of subjects selected for Student ID $studentId.";
                continue;
            }

            // Check for duplicate entry
            $checkDuplicateQuery = "SELECT * FROM studentsub WHERE student_id = $studentId";
            $checkDuplicateResult = $conn->query($checkDuplicateQuery);

            if ($checkDuplicateResult->num_rows > 0) {
                echo "Subjects for Student ID $studentId already exist. Skipping duplicate entry.";
                continue;
            }

            // Prepare the SQL statement
            $insertQuery = "INSERT INTO studentsub (student_id, class_id";
            $insertValues = "VALUES (?, ?";

            // Dynamically add subject columns to the SQL statement
            for ($i = 1; $i <= $maxSubjects; $i++) {
                $subjectColumn = "sub$i";
                $insertQuery .= ", $subjectColumn";
                $insertValues .= ", ?";
            }

            $insertQuery .= ")";
            $insertValues .= ")";

            // Combine the complete SQL statement
            $insertStatement = $insertQuery . " " . $insertValues;

            // Prepare the SQL statement
            $stmt = $conn->prepare($insertStatement);

            // Check for errors in preparation
            if (!$stmt) {
                echo "Error in preparing statement: " . $conn->error;
                continue;
            }

            // Create an array with required number of subjects (fill empty slots if necessary)
            $selectedSubjects = array_pad($selectedSubjects, $maxSubjects, '');

            // Build the types string for bind_param dynamically based on the number of subjects
            $types = "is" . str_repeat("s", $maxSubjects);

            // Create an array of values to bind
            $bindValues = array_merge([$types, &$studentId, &$classId], $selectedSubjects);

            // Convert $bindValues to references
            $refs = [];
            foreach ($bindValues as $key => $value) {
                $refs[$key] = &$bindValues[$key];
            }

            // Bind the parameters to the prepared statement
            call_user_func_array([$stmt, 'bind_param'], $refs);

            // Execute the statement
            $stmt->execute();

            // Check for errors in execution
            if ($stmt->error) {
                echo "Error in execution: " . $stmt->error;
            }

            // Close the statement
            $stmt->close();
        }
    } else {
        echo "Invalid subjects data.";
    }
} else {
    echo "Invalid request.";
}
header("Location: assignsubtostd.php?success=1");
// Close the database connection
$conn->close();
?>
