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

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Validate and sanitize inputs
    $student_id = $_SESSION['student_id']; // Get from session
    $homework_id = $_POST['homework_id'];
    $status = 'submitted'; // Default status

    // File upload handling
    $target_dir = "uploads/";
    $file_name = basename($_FILES["submission"]["name"]);
    $target_file = $target_dir . $file_name;
    $uploadOk = 1;
    $fileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

    // Check file size
    if ($_FILES["submission"]["size"] > 500000) {
        echo "Sorry, your file is too large.";
        $uploadOk = 0;
    }

    // Allow certain file formats
    if ($fileType != "pdf" && $fileType != "doc" && $fileType != "docx") {
        echo "Sorry, only PDF, DOC, DOCX files are allowed.";
        $uploadOk = 0;
    }

    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
        echo "Sorry, your file was not uploaded.";
    } else {
        // File upload successful, move file to server
        if (move_uploaded_file($_FILES["submission"]["tmp_name"], $target_file)) {
            // Insert submission into database
            $sql = "INSERT INTO student_homework (student_id, homework_id, submission, file_path, submitted_at, status) 
                    VALUES (?, ?, ?, ?, NOW(), ?)";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("iisss", $student_id, $homework_id, $file_name, $target_file, $status);

            if ($stmt->execute()) {
                echo "Homework submitted successfully.";
            } else {
                echo "Error submitting homework: " . $stmt->error;
            }

            $stmt->close();
        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    }

    $conn->close();
}
?>
