<?php
session_start();
include('db_connection.php');

$teacher_id = $_SESSION['teacher_id'];

$class_id = $_POST['class_id'];
$subject_id = $_POST['subject_id'];
$title = $_POST['title'];
$description = $_POST['description'];
$due_date = $_POST['due_date'];

$file_path = NULL;

/* FILE UPLOAD */
if (!empty($_FILES['file']['name'])) {

    $target_dir = "uploads/";
    if (!is_dir($target_dir)) mkdir($target_dir);

    $file_name = time() . "_" . basename($_FILES["file"]["name"]);
    $target_file = $target_dir . $file_name;

    $file_type = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

    $allowed = ['pdf','doc','docx'];

    if (in_array($file_type, $allowed)) {
        move_uploaded_file($_FILES["file"]["tmp_name"], $target_file);
        $file_path = $target_file;
    }
}

/* INSERT */
$stmt = $conn->prepare("
INSERT INTO homework 
(subject_id, teacher_id, class_id, title, description, due_date, file_path, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, NOW())
");

$stmt->bind_param("iiissss", $subject_id, $teacher_id, $class_id, $title, $description, $due_date, $file_path);
$stmt->execute();

header("Location: add_homework.php");