<?php
	include 'includes/session.php';
	include 'includes/sessions.php'; 
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $material_name = $_POST['material_name'];
    $course_id = $_POST['course_name'];
    
    // Handle file upload
    $target_dir = "materials/"; // Directory where the files will be saved
    $file = $_FILES['file'];
    $file_name = basename($file["name"]);
    $target_file = $target_dir . $file_name;
    $file_type = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

    // Allowed file types (PDF, Word, Images)
    $allowed_file_types = ['pdf', 'doc', 'docx', 'jpg', 'jpeg', 'png', 'gif'];

    // Validate file type
    if (in_array($file_type, $allowed_file_types)) {
        // Check if file already exists
        if (file_exists($target_file)) {
            echo "Sorry, the file already exists.";
        } else {
            // Move the file to the server folder
            if (move_uploaded_file($file["tmp_name"], $target_file)) {
                // Insert material information into the database
                $sql = "INSERT INTO materials (material_name, file_name, course_name) VALUES (?, ?, ?)";
                $stmt = $conn->prepare($sql);
                $stmt->bind_param("sss", $material_name, $file_name, $course_id);

                if ($stmt->execute()) {
                    echo "The file ". htmlspecialchars($file_name) . " has been uploaded successfully.";
                } else {
                    echo "Error uploading material: " . $stmt->error;
                }
            } else {
                echo "Sorry, there was an error uploading your file.";
            }
        }
    } else {
        echo "Sorry, only PDF, DOC, DOCX, JPG, JPEG, PNG, and GIF files are allowed.";
    }
}
	header('location: material_list.php');

$conn->close();
?>
