<?php
/**
 * ===================================================================================
 * My Grades Page (for Students) - FINAL FIX
 * ===================================================================================
 *
 * File: my_grades.php
 * Location: /homework_portal/student/my_grades.php
 *
 * Purpose:
 * 1. Displays a list of all graded assignments for the logged-in student.
 * 2. Clears the "new grade" notification.
 * 3. FIX: Prevents "strtotime()" error for null dates.
 */

require_once '../config.php';

if (!isset($_SESSION['student_id'])) {
    header('Location: ../login.php');
    exit();
}
$student_id = $_SESSION['student_id'];

try {
    // 1. Fetch all graded submissions for this student
    $sql = "
        SELECT 
            a.title as assignment_title,
            s.subject_name,
            sub.grade,
            sub.teacher_feedback,
            sub.graded_file_path,
            sub.graded_at
        FROM submissions sub
        JOIN assignments a ON sub.assignment_id = a.id
        JOIN subjects s ON a.subject_id = s.id
        WHERE sub.student_id = ? AND sub.grade IS NOT NULL
        ORDER BY sub.graded_at DESC
    ";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$student_id]);
    $graded_submissions = $stmt->fetchAll();

    // 2. After fetching, mark all of this student's unread grades as 'seen'
    $update_sql = "UPDATE submissions SET grade_seen_by_student = 1 WHERE student_id = ? AND grade_seen_by_student = 0";
    $pdo->prepare($update_sql)->execute([$student_id]);

} catch (PDOException $e) {
    error_log($e->getMessage());
    $graded_submissions = [];
    $page_error = "We had a problem loading your grades. Please tell your teacher!";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Grades - School Portal</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700&family=Baloo+2:wght@700&display=swap" rel="stylesheet">
    <style>
        body { font-family: 'Poppins', sans-serif; background-color: #f0f4f8; }
        .font-brand { font-family: 'Baloo 2', cursive; }
    </style>
</head>
<body class="min-h-screen">
    <header class="bg-white shadow-sm sticky top-0 z-10">
        <div class="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-4 flex justify-between items-center">
            <a href="dashboard.php" class="flex items-center text-cyan-700 hover:text-cyan-800"><svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path></svg>Back to Dashboard</a>
            <a href="../logout.php" class="py-2 px-4 bg-orange-500 text-white text-sm font-semibold rounded-full shadow-md hover:bg-orange-600">Logout</a>
        </div>
    </header>
    <main class="max-w-4xl mx-auto py-8 px-4 sm:px-6 lg:px-8">
        <div class="mb-8 text-center">
            <h1 class="text-4xl font-bold font-brand text-gray-800">My Grades</h1>
            <p class="text-gray-500">A summary of all your graded assignments.</p>
        </div>
        <?php if (isset($page_error)): ?><div class="p-4 text-center text-red-800 bg-red-100 rounded-lg"><?php echo e($page_error); ?></div>
        <?php elseif (empty($graded_submissions)): ?><div class="p-6 text-center text-gray-600 bg-white rounded-lg shadow"><p>You have no graded assignments yet.</p></div>
        <?php else: ?>
            <div class="bg-white shadow-lg rounded-lg overflow-hidden">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Assignment</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Subject</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Grade</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Graded On</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200">
                        <?php foreach ($graded_submissions as $item): ?>
                            <tr>
                                <td class="px-6 py-4 text-sm font-medium text-gray-900"><?php echo e($item['assignment_title']); ?></td>
                                <td class="px-6 py-4 text-sm text-gray-500"><?php echo e($item['subject_name']); ?></td>
                                <td class="px-6 py-4 text-sm font-bold text-teal-600"><?php echo e($item['grade']); ?></td>
                                <td class="px-6 py-4 text-sm text-gray-500">
                                    <?php
                                        // ==================================================
                                        // ** THE FIX IS HERE **
                                        // ==================================================
                                        if (!empty($item['graded_at'])) {
                                            echo date('M d, Y', strtotime($item['graded_at']));
                                        } else {
                                            echo 'N/A';
                                        }
                                    ?>
                                </td>
                            </tr>
                            <?php if(!empty($item['teacher_feedback']) || !empty($item['graded_file_path'])): ?>
                                <tr class="bg-gray-50">
                                    <td colspan="4" class="px-6 py-3">
                                        <?php if(!empty($item['teacher_feedback'])): ?>
                                            <p class="text-sm text-gray-700"><strong>Feedback:</strong> <?php echo nl2br(e($item['teacher_feedback'])); ?></p>
                                        <?php endif; ?>
                                        <?php if(!empty($item['graded_file_path'])): ?>
                                            <a href="../<?php echo e($item['graded_file_path']); ?>" download class="inline-block mt-2 text-sm text-blue-600 hover:underline">Download Graded File</a>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endif; ?>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </main>
</body>
</html>