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

/* ================= AUTH ================= */
if (!isset($_SESSION['student_id']) || $_SESSION['role'] !== 'student') {
    header("Location: student_login.php?error=Unauthorized");
    exit();
}

$student_id = $_SESSION['student_id'];
$message = "";
$error = "";

/* ================= VALIDATE HOMEWORK ================= */
if (!isset($_GET['homework_id'])) {
    die("Invalid request.");
}

$homework_id = intval($_GET['homework_id']);

/* ================= HANDLE FORM ================= */
if ($_SERVER["REQUEST_METHOD"] == "POST") {

    $submission = trim($_POST['submission'] ?? '');
    $status = "submitted";
    $file_path = "";

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

        $allowed_types = ['pdf', 'doc', 'docx'];
        $max_size = 5 * 1024 * 1024; // 5MB

        $file_name = $_FILES['file']['name'];
        $file_tmp = $_FILES['file']['tmp_name'];
        $file_size = $_FILES['file']['size'];

        $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

        if (!in_array($file_ext, $allowed_types)) {
            $error = "Only PDF, DOC, DOCX files allowed.";
        } elseif ($file_size > $max_size) {
            $error = "File size must be less than 5MB.";
        } else {
            $new_name = "hw_" . $student_id . "_" . time() . "." . $file_ext;
            $target_dir = "uploads/";
            $target_file = $target_dir . $new_name;

            if (move_uploaded_file($file_tmp, $target_file)) {
                $file_path = $target_file;
            } else {
                $error = "File upload failed.";
            }
        }
    }

    /* ===== INSERT ===== */
    if (empty($error)) {
        $sql = "INSERT INTO student_homework 
                (homework_id, student_id, file_path, submitted_at, status, created_at)
                VALUES (?, ?, ?, NOW(), ?, NOW())";

        $stmt = $conn->prepare($sql);

        if (!$stmt) {
            $error = "Database error: " . $conn->error;
        } else {
            $stmt->bind_param("iiss", $homework_id, $student_id, $file_path, $status);

            if ($stmt->execute()) {
                $message = "✅ Homework submitted successfully!";
            } else {
                $error = "Submission failed.";
            }
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Submit Homework</title>

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">

<style>
body {
    background: linear-gradient(135deg, #667eea, #764ba2);
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
}

.card {
    border-radius: 15px;
    box-shadow: 0 10px 30px rgba(0,0,0,0.2);
}

.btn-submit {
    background: #667eea;
    color: white;
}

.btn-submit:hover {
    background: #5a67d8;
}

textarea {
    resize: none;
}
</style>
</head>

<body>

<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-6">

            <div class="card p-4">
                <h4 class="text-center mb-3">📘 Submit Homework</h4>

                <!-- SUCCESS -->
                <?php if ($message): ?>
                    <div class="alert alert-success"><?php echo $message; ?></div>
                <?php endif; ?>

                <!-- ERROR -->
                <?php if ($error): ?>
                    <div class="alert alert-danger"><?php echo $error; ?></div>
                <?php endif; ?>

                <form method="POST" enctype="multipart/form-data">

                    <div class="mb-3">
                        <label class="form-label">Your Answer</label>
                        <textarea name="submission" class="form-control" rows="4" placeholder="Write your answer here..." required></textarea>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Upload File</label>
                        <input type="file" name="file" class="form-control">
                        <small class="text-muted">Allowed: PDF, DOC, DOCX (Max 5MB)</small>
                    </div>

                    <button type="submit" class="btn btn-submit w-100">Submit Homework</button>
                </form>

                <div class="text-center mt-3">
                    <a href="view_homework.php">← Back to Homework</a>
                </div>
            </div>

        </div>
    </div>
</div>

</body>
</html>