<?php
	include 'includes/session.php';
	include 'includes/sessions.php'; 
	
	if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    
    // Get form data
    $student_email = $_POST['student_email']; // The selected student's email
    $material_id = $_POST['material_name']; // The selected material's ID
    
    // Check if the fields are not empty
    if (!empty($student_email) && !empty($material_id)) {
        
        // Prepare an SQL statement to insert the data into the assign_materials table
        $sql = "INSERT INTO assign_materials (user_email, material_id) VALUES (?, ?)";
        
        // Initialize the prepared statement
        if ($stmt = $conn->prepare($sql)) {
            
            // Bind the parameters to the SQL query
            $stmt->bind_param("si", $student_email, $material_id); // 's' is for string, 'i' is for integer
            
            // Execute the prepared statement
            if ($stmt->execute()) {
                // Success message
                echo "Material successfully assigned to the student.";
            } else {
                // Error message in case the query fails
                echo "Error: Could not execute query: " . $conn->error;
            }
            
            // Close the prepared statement
            $stmt->close();
        } else {
            // Error in preparing the statement
            echo "Error: Could not prepare the SQL statement: " . $conn->error;
        }
    } else {
        // Handle the case where required fields are missing
        echo "Please select both a student and a material.";
    }
    	header('location: assign_materials.php');

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