<?php
/**
 * ===================================================================================
 * View Subject Page (FINAL - DUAL NOTIFICATION CLEARING)
 * ===================================================================================
 * This final version clears both the "new material" and "new grade" notifications.
 */

require_once '../config.php';

// --- Security Check & Initial Setup ---
if (!isset($_SESSION['student_id'], $_SESSION['student_class_id'])) {
    header('Location: ../login.php');
    exit();
}

$student_id = $_SESSION['student_id'];
$class_id = $_SESSION['student_class_id'];
$subject_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($subject_id <= 0) {
    header('Location: dashboard.php');
    exit();
}

// --- Fetch Data for the Page ---
try {
    $subject_stmt = $pdo->prepare("SELECT subject_name FROM subjects WHERE id = ?");
    $subject_stmt->execute([$subject_id]);
    $subject = $subject_stmt->fetch();
    $subject_name = $subject ? e($subject['subject_name']) : 'Subject';

    // This query correctly fetches all materials and submission/grade status
    $assignments_sql = "
        SELECT 
            a.id, a.title, a.instructions, a.file_path, a.post_type, a.due_date, t.full_name AS teacher_name,
            sub.id as submission_id, 
            sub.parent_guardian_remark,
            sub.grade,
            sub.teacher_feedback,
            sub.graded_file_path
        FROM assignments a
        JOIN teachers t ON a.teacher_id = t.id
        LEFT JOIN submissions sub ON a.id = sub.assignment_id AND sub.student_id = ?
        WHERE a.class_id = ? AND a.subject_id = ? AND a.status = 'published'
        ORDER BY a.created_at DESC
    ";
    $assignments_stmt = $pdo->prepare($assignments_sql);
    $assignments_stmt->execute([$student_id, $class_id, $subject_id]);
    $assignments = $assignments_stmt->fetchAll();

    // --- Notification Clearing Logic ---
    if (!empty($assignments)) {
        // 1. Mark these assignments as "seen" to clear the "new material" notification (Existing Logic)
        $assignment_ids = array_column($assignments, 'id');
        $placeholders_asgn = rtrim(str_repeat('(?, ?),', count($assignment_ids)), ',');
        $sql_mark_seen_asgn = "INSERT IGNORE INTO student_seen_assignments (student_id, assignment_id) VALUES $placeholders_asgn";
        $params_asgn = [];
        foreach ($assignment_ids as $aid) {
            $params_asgn[] = $student_id;
            $params_asgn[] = $aid;
        }
        $seen_asgn_stmt = $pdo->prepare($sql_mark_seen_asgn);
        $seen_asgn_stmt->execute($params_asgn);

        // =======================================================================
        // ** NEW: Mark any viewed GRADES as "seen" to clear the grade notification **
        // =======================================================================
        $submission_ids_with_grades = [];
        foreach ($assignments as $assignment) {
            // Check if the assignment has a submission AND a grade
            if (!empty($assignment['submission_id']) && !empty($assignment['grade'])) {
                $submission_ids_with_grades[] = $assignment['submission_id'];
            }
        }

        if (!empty($submission_ids_with_grades)) {
            // Creates a string of question marks for the IN clause: (?, ?, ?)
            $placeholders_grade = rtrim(str_repeat('?,', count($submission_ids_with_grades)), ',');
            $sql_mark_grades_seen = "UPDATE submissions SET grade_seen_by_student = 1 WHERE student_id = ? AND id IN ($placeholders_grade)";
            
            // The parameters array will contain the student_id first, followed by all submission_ids
            $params_grade = array_merge([$student_id], $submission_ids_with_grades);
            
            $seen_grades_stmt = $pdo->prepare($sql_mark_grades_seen);
            $seen_grades_stmt->execute($params_grade);
        }
    }

} catch (PDOException $e) {
    error_log($e->getMessage());
    $assignments = [];
    $page_error = "We had a problem loading the materials for this subject. Please tell your teacher!";
}

$post_styles = [
    'homework' => ['icon' => '&#128221;', 'color' => 'bg-blue-500'], 'notes' => ['icon' => '&#128214;', 'color' => 'bg-green-500'],
    'exam' => ['icon' => '&#9999;&#65039;', 'color' => 'bg-red-500'], 'announcement' => ['icon' => '&#128226;', 'color' => 'bg-yellow-500'],
    'report' => ['icon' => '&#128202;', 'color' => 'bg-purple-500'],
];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title><?php echo $subject_name; ?> - 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; }
        .material-card { background-color: white; border-radius: 16px; padding: 1.5rem; transition: transform 0.2s ease, box-shadow 0.2s ease; box-shadow: 0 4px 15px rgba(0,0,0,0.05); }
        .material-icon { font-size: 1.5rem; width: 50px; height: 50px; border-radius: 12px; display: flex; align-items: center; justify-content: center; color: white; }
    </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 Subjects</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-5xl mx-auto py-8 px-4 sm:px-6 lg:px-8">
        <div class="mb-8"><h1 class="text-4xl font-bold font-brand text-gray-800"><?php echo $subject_name; ?></h1><p class="text-gray-500">All your materials for this subject are listed below.</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($assignments)): ?><div class="p-6 text-center text-gray-600 bg-white rounded-lg shadow"><p>There are no materials posted for this subject yet. Great job staying ahead!</p></div>
        <?php else: ?>
            <div class="space-y-6">
                <?php foreach ($assignments as $assignment): ?>
                    <?php $style = $post_styles[$assignment['post_type']] ?? ['icon' => '&#128196;', 'color' => 'bg-gray-400']; ?>
                    <div class="material-card">
                        <div class="flex items-start space-x-4">
                            <div class="material-icon <?php echo $style['color']; ?>"><?php echo $style['icon']; ?></div>
                            <div class="flex-1">
                                <div class="flex justify-between items-start">
                                    <div><h3 class="font-bold text-lg text-gray-800"><?php echo e($assignment['title']); ?></h3><p class="text-sm text-gray-500">Posted by: <?php echo e($assignment['teacher_name']); ?></p></div>
                                    <span class="text-xs font-semibold text-white <?php echo $style['color']; ?> px-2 py-1 rounded-full"><?php echo e(ucfirst($assignment['post_type'])); ?></span>
                                </div>
                                <p class="mt-2 text-gray-600"><?php echo nl2br(e($assignment['instructions'])); ?></p>
                                <?php if($assignment['due_date']): ?><p class="mt-2 text-sm font-semibold text-red-600">Due: <?php echo date('D, M j, Y, g:i a', strtotime($assignment['due_date'])); ?></p><?php endif; ?>
                                <div class="mt-4 flex flex-wrap items-center gap-4">
                                    <?php if($assignment['file_path']): ?><a href="../<?php echo e($assignment['file_path']); ?>" download class="px-4 py-2 bg-blue-500 text-white text-sm font-semibold rounded-lg hover:bg-blue-600">Download File</a><?php endif; ?>
                                    <?php if($assignment['post_type'] === 'homework' || $assignment['post_type'] === 'exam'): ?>
                                        <a href="submit_work.php?id=<?php echo e($assignment['id']); ?>" class="<?php echo $assignment['submission_id'] ? 'bg-orange-500' : 'bg-green-500'; ?> px-4 py-2 text-white text-sm font-semibold rounded-lg hover:opacity-80"><?php echo $assignment['submission_id'] ? 'Re-Submit' : 'Submit Work'; ?></a>
                                        <?php if($assignment['submission_id']): ?><a href="add_remark.php?id=<?php echo e($assignment['submission_id']); ?>" class="text-sm text-indigo-600 hover:underline"><?php echo empty($assignment['parent_guardian_remark']) ? 'Add Parent Remark' : 'Edit Parent Remark'; ?></a><?php endif; ?>
                                    <?php endif; ?>
                                </div>
                                <?php if($assignment['submission_id'] && $assignment['grade']): ?>
                                    <div class="mt-6 border-t-2 border-dashed pt-4">
                                        <h4 class="font-bold text-teal-700">Grading & Feedback</h4>
                                        <div class="mt-2 grid grid-cols-1 md:grid-cols-3 gap-4">
                                            <div class="bg-teal-50 p-3 rounded-lg"><p class="text-sm font-semibold text-teal-800">Your Grade:</p><p class="text-2xl font-bold text-teal-600"><?php echo e($assignment['grade']); ?></p></div>
                                            <div class="md:col-span-2 bg-gray-50 p-3 rounded-lg"><p class="text-sm font-semibold text-gray-800">Teacher's Feedback:</p><p class="text-gray-700 mt-1"><?php echo nl2br(e($assignment['teacher_feedback'])); ?></p></div>
                                        </div>
                                         <?php if($assignment['graded_file_path']): ?>
                                             <div class="mt-3"><a href="../<?php echo e($assignment['graded_file_path']); ?>" download class="inline-flex items-center px-4 py-2 bg-purple-500 text-white text-sm font-semibold rounded-lg hover:bg-purple-600"><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="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"></path></svg>Download Marked File</a></div>
                                         <?php endif; ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </main>
    <footer class="text-center py-8 mt-12 border-t">
        <p class="text-sm text-gray-500">Built By Ele InfoComm Technologies- Kenya | <a href="http://web.e-ict.co.ke" target="_blank" class="hover:underline">web.e-ict.co.ke</a> | <a href="mailto:info@e-ict.co.ke" class="hover:underline">info@e-ict.co.ke</a> | +254202000121 | +254 722 215810 | 2025 All right reserved.</p>
    </footer>
</body>
</html>