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

// Ensure teacher is logged in
if (!isset($_SESSION['staff'])) {
    header("Location: ../../login.php");
    exit;
}

$teacher_id = $_SESSION['staff'];
$grade_success = '';

// Handle grading submission
if (isset($_POST['grade_btn'])) {
    $submission_id = $_POST['submission_id'];
    $grade = $_POST['grade'];
    $comment = $_POST['comment'] ?? '';

    $stmt = $connection->prepare(
        "UPDATE submissions SET grade = ?, comment = ? WHERE id = ?"
    );
    $stmt->bind_param("ssi", $grade, $comment, $submission_id);

    if ($stmt->execute()) {
        $grade_success = "Grade updated successfully!";
    }
}

// Fetch assignments
$stmt = $connection->prepare(
    "SELECT * FROM assignments WHERE teacher_id = ? ORDER BY due_date DESC"
);
$stmt->bind_param("i", $teacher_id);
$stmt->execute();
$assignments = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

// Fetch ungraded submissions
$all_submissions = [];
foreach ($assignments as $assignment) {
    $stmt = $connection->prepare("
        SELECT s.id AS sub_id, s.file_path, s.submission_time,
               st.reg_number, st.firstname, st.lastname, st.othername
        FROM submissions s
        JOIN students st ON s.student_id = st.id
        WHERE s.assignment_id = ?
          AND (s.grade IS NULL OR s.grade = '')
        ORDER BY s.submission_time DESC
    ");
    $stmt->bind_param("i", $assignment['id']);
    $stmt->execute();

    $subs = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    if ($subs) {
        $all_submissions[$assignment['id']] = $subs;
    }
}
?>

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

<div class="container mt-4">
    <h4 class="mb-3">Submitted Assignments Pending Grading</h4>

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

    <?php if (empty($all_submissions)): ?>
        <div class="alert alert-info">No submissions pending grading.</div>
    <?php else: ?>

        <?php foreach ($assignments as $assignment): ?>
            <?php if (!isset($all_submissions[$assignment['id']])) continue; ?>

            <div class="card shadow-sm mb-4">
                <div class="card-header bg-primary text-white">
                    <strong><?= htmlspecialchars($assignment['title']) ?></strong>
                    <div class="small">
                        <?= htmlspecialchars($assignment['subject']) ?> |
                        <?= htmlspecialchars($assignment['class']) ?>
                    </div>
                </div>

                <div class="card-body">

                    <!-- ASSIGNMENT DETAILS (DESKTOP ONLY) -->
                    <div class="d-none d-md-block mb-3">
                        <p><?= nl2br(htmlspecialchars($assignment['description'])) ?></p>
                        <p class="text-muted">
                            Due: <?= date("d M Y, h:i A", strtotime($assignment['due_date'])) ?>
                        </p>
                    </div>

                    <!-- TABLE (DESKTOP & MOBILE) -->
                    <div class="table-responsive">
                        <table class="table table-bordered table-striped align-middle">
                            <thead class="table-light">
                                <tr>
                                    <th>Student</th>
                                    <th>Submitted</th>
                                    <th>File</th>
                                    <th width="220">Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($all_submissions[$assignment['id']] as $s): ?>
                                <tr>
                                    <td>
                                        <?= htmlspecialchars($s['firstname'].' '.$s['lastname'].' '.$s['othername']) ?><br>
                                        <small class="text-muted"><?= $s['reg_number'] ?></small>
                                    </td>
                                    <td>
                                        <?= date("d M Y, h:i A", strtotime($s['submission_time'])) ?>
                                    </td>
                                    <td>
                                        <?php if ($s['file_path']): ?>
                                            <a href="<?= $s['file_path'] ?>" target="_blank">View</a>
                                        <?php else: ?>
                                            -
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <form method="POST" class="d-flex flex-column gap-1">
                                            <input type="hidden" name="submission_id" value="<?= $s['sub_id'] ?>">
                                            <input type="text" name="grade"
                                                   class="form-control form-control-sm"
                                                   placeholder="Grade" required>
                                            <input type="text" name="comment"
                                                   class="form-control form-control-sm"
                                                   placeholder="Comment">
                                            <button class="btn btn-success btn-sm" name="grade_btn">
                                                Update
                                            </button>
                                        </form>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>

                </div>
            </div>

        <?php endforeach; ?>
    <?php endif; ?>
</div>

<script src="../../assets/js/bootstrap.bundle.min.js"></script>
