<?php

require_once(__DIR__ . "/../header.php");
require_once(__DIR__ . "/../../public/connection.php");

// =============================
// STUDENT AUTH CHECK
// =============================
if (!isset($_SESSION['student']) || empty($_SESSION['student'])) {
    die("<div class='alert alert-danger m-4'>Access denied. Please log in as a student.</div>");
}

$student_id = $_SESSION['student'];

// =============================
// FETCH STUDENT CLASS
// =============================
$st_q = $connection->prepare("SELECT class, firstname, lastname FROM students WHERE id=?");
$st_q->bind_param("i", $student_id);
$st_q->execute();
$student = $st_q->get_result()->fetch_assoc();
$class = $student['class'] ?? null;

if (!$class) {
    die("<div class='alert alert-danger m-4'>Student record not found or class not assigned.</div>");
}

// =============================
// HANDLE SUBMISSION
// =============================
$success = $error = "";

if (isset($_POST['submit_assignment'])) {
    $assignment_id = (int)$_POST['assignment_id'];

    // Check if already submitted
    $sub_q = $connection->prepare("SELECT id FROM submissions WHERE assignment_id=? AND student_id=?");
    $sub_q->bind_param("ii", $assignment_id, $student_id);
    $sub_q->execute();
    $submission = $sub_q->get_result()->fetch_assoc();

    if ($submission) {
        $error = "You have already submitted this assignment.";
    } elseif (!isset($_FILES['file']) || $_FILES['file']['error'] !== 0) {
        $error = "Please upload your assignment file.";
    } else {
        $filename = time() . "_" . basename($_FILES['file']['name']);
        $upload_dir = $_SERVER['DOCUMENT_ROOT'] . "/uploads/assignments/submissions/";
        if (!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);

        $target = $upload_dir . $filename;
        if (move_uploaded_file($_FILES['file']['tmp_name'], $target)) {
            $file_path = "/uploads/assignments/submissions/" . $filename;

            $ins = $connection->prepare("INSERT INTO submissions (assignment_id, student_id, file_path) VALUES (?,?,?)");
            $ins->bind_param("iis", $assignment_id, $student_id, $file_path);
            if ($ins->execute()) {
                $success = "Assignment submitted successfully!";
            } else {
                $error = "Submission failed. Try again.";
            }
        } else {
            $error = "File upload failed.";
        }
    }
}

// =============================
// FETCH ASSIGNMENTS NOT YET SUBMITTED
// =============================
$ass_q = $connection->prepare("
    SELECT a.* 
    FROM assignments a
    LEFT JOIN submissions s 
        ON a.id = s.assignment_id AND s.student_id = ?
    WHERE a.class = ? AND s.id IS NULL
    ORDER BY a.due_date DESC
");
$ass_q->bind_param("is", $student_id, $class);
$ass_q->execute();
$assignments = $ass_q->get_result();

?>

<link rel="stylesheet" href="../../assets/css/bootstrap.min.css">
<link rel="stylesheet" href="../../assets/css/style.css">
<link rel="stylesheet" href="../../assets/css/custom.css">

<div class="container mt-4">
    <h3>Assignments Yet to be Submitted - Class <?= htmlspecialchars($class) ?></h3>

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

    <?php if ($assignments->num_rows === 0): ?>
        <div class="alert alert-info">You have no pending assignments to submit.</div>
    <?php else: ?>
        <?php while ($assignment = $assignments->fetch_assoc()): ?>
            <div class="card shadow-sm mb-3">
                <div class="card-header bg-primary text-white">
                    <h5 class="mb-0"><?= htmlspecialchars($assignment['title']) ?></h5>
                </div>
                <div class="card-body">
                    <p><strong>Subject:</strong> <?= htmlspecialchars($assignment['subject']) ?></p>
                    <p><strong>Description:</strong> <?= nl2br(htmlspecialchars($assignment['description'])) ?></p>
                    <p><strong>Deadline:</strong> <?= date("d M Y, h:i A", strtotime($assignment['due_date'])) ?></p>
                    <span class="badge bg-<?= strtotime(date("Y-m-d H:i:s")) > strtotime($assignment['due_date']) ? 'danger' : 'success' ?>">
                        <?= strtotime(date("Y-m-d H:i:s")) > strtotime($assignment['due_date']) ? 'Deadline Passed' : 'Submission Open' ?>
                    </span>

                    <?php if (!empty($assignment['file_path'])): ?>
                        <p class="mt-2">
                            <a href="<?= $assignment['file_path'] ?>" target="_blank" class="btn btn-outline-primary btn-sm">
                                Download Assignment File
                            </a>
                        </p>
                    <?php endif; ?>

                    <form method="POST" enctype="multipart/form-data" class="mt-3">
                        <input type="hidden" name="assignment_id" value="<?= $assignment['id'] ?>">
                        <div class="mb-3">
                            <label class="form-label">Upload Your Assignment</label>
                            <input type="file" name="file" class="form-control" required>
                        </div>
                        <button type="submit" name="submit_assignment" class="btn btn-success">Submit Assignment</button>
                    </form>
                </div>
            </div>
        <?php endwhile; ?>
    <?php endif; ?>
</div>
