<?php
/**
 * ===================================================================================
 * Student Dashboard Page (FINAL - with ALL THREE Notification Systems)
 * ===================================================================================
 * This version makes the "New Grades" icon a clickable link to my_grades.php.
 */
session_start();
require_once '../config.php';

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

$student_id = $_SESSION['student_id'];
$class_id = $_SESSION['student_class_id'];
$student_full_name = htmlspecialchars($_SESSION['student_full_name'] ?? 'Student');

try {
    // All 4 queries remain the same and are correct.
    $sql = "SELECT DISTINCT s.id, s.subject_name FROM subjects s JOIN teacher_subject_class tsc ON s.id = tsc.subject_id WHERE tsc.class_id = ? ORDER BY s.subject_name ASC";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$class_id]);
    $subjects = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $new_material_sql = "
        SELECT a.subject_id, COUNT(a.id) as new_count
        FROM assignments a
        LEFT JOIN student_seen_assignments ssa ON a.id = ssa.assignment_id AND ssa.student_id = ?
        WHERE a.class_id = ? AND a.status = 'published' AND ssa.assignment_id IS NULL
        GROUP BY a.subject_id
    ";
    $new_stmt = $pdo->prepare($new_material_sql);
    $new_stmt->execute([$student_id, $class_id]);
    $new_material_counts = $new_stmt->fetchAll(PDO::FETCH_KEY_PAIR);

    $unread_sql = "SELECT COUNT(id) FROM student_private_files WHERE student_id = ? AND is_read = 0";
    $unread_stmt = $pdo->prepare($unread_sql);
    $unread_stmt->execute([$student_id]);
    $unread_files_count = $unread_stmt->fetchColumn();

    $new_grades_sql = "SELECT COUNT(id) FROM submissions WHERE student_id = ? AND grade_seen_by_student = 0 AND grade IS NOT NULL";
    $new_grades_stmt = $pdo->prepare($new_grades_sql);
    $new_grades_stmt->execute([$student_id]);
    $new_grades_count = $new_grades_stmt->fetchColumn();

} catch (PDOException $e) {
    error_log($e->getMessage());
    $subjects = []; $unread_files_count = 0; $new_material_counts = []; $new_grades_count = 0;
    $dashboard_error = "We couldn't load your subjects. Please tell your teacher!";
}

$subject_styles = [
    ['bg' => 'bg-orange-400', 'icon' => '&#128218;'], ['bg' => 'bg-sky-500',   'icon' => '&#128200;'],
    ['bg' => 'bg-teal-500',  'icon' => '&#127757;'], ['bg' => 'bg-rose-500',  'icon' => '&#128394;'],
    ['bg' => 'bg-amber-500', 'icon' => '&#9879;'], ['bg' => 'bg-indigo-500', 'icon' => '&#127925;'],
];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>My Dashboard - TTTEDDDEL</title><link rel="manifest" href="/homework_portal/manifest.json"><meta name="theme-color" content="#dc2626"/><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; }
        .subject-card { position: relative; border-radius: 20px; padding: 1.5rem; color: white; text-shadow: 1px 1px 2px rgba(0,0,0,0.2); transition: transform 0.3s ease, box-shadow 0.3s ease; box-shadow: 0 4px 15px rgba(0,0,0,0.1); }
        .subject-card:hover { transform: translateY(-8px) scale(1.03); box-shadow: 0 10px 25px rgba(0,0,0,0.15); }
        .subject-icon { font-size: 3.5rem; line-height: 1; }
        .notification-badge { position: absolute; top: -5px; right: -5px; display: inline-flex; align-items: center; justify-content: center; width: 24px; height: 24px; border-radius: 9999px; background-color: #ef4444; color: white; font-size: 0.75rem; font-weight: bold; border: 2px solid white; }
        .hidden { display: none; }
    </style>
</head>
<body class="flex flex-col 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">
            <div class="text-center mb-4"><a href="dashboard.php"><h1 class="text-5xl font-bold text-red-600 tracking-widest font-sans">TTTEDDDEL</h1><p class="text-sm font-semibold text-blue-800 mt-1">Teacher-Student Interactive System</p><p class="text-xs text-blue-800">by Ele Infocomm Technologies</p></a></div>
            <div class="flex justify-between items-center border-t pt-3">
                <div><h2 class="text-xl md:text-2xl font-bold font-brand text-cyan-700">My Dashboard</h2><p class="text-sm text-gray-500">Hello, <?php echo explode(' ', $student_full_name)[0]; ?>!</p></div>
                <div class="flex items-center space-x-2 sm:space-x-4">
                    <button id="install-button" class="hidden py-2 px-4 bg-green-500 text-white text-sm font-semibold rounded-full shadow-md hover:bg-green-600">Install App</button>
                    
                    <!-- ============================================= -->
                    <!-- ** FIX: The href now points to my_grades.php ** -->
                    <!-- ============================================= -->
                    <a href="my_grades.php" class="relative p-2 text-gray-500 hover:text-cyan-700" title="New Grades">
                        <svg class="w-7 h-7" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M4.26 10.147a60.436 60.436 0 00-.491 6.347A48.627 48.627 0 0112 20.904a48.627 48.627 0 018.232-4.41 60.46 60.46 0 00-.491-6.347m-15.482 0a50.57 50.57 0 00-2.658-.813A59.905 59.905 0 0112 3.493a59.902 59.902 0 0110.399 5.84c-.896.248-1.783.52-2.658.814m-15.482 0l15.482 0M5.304 16.696l1.822 1.822M18.696 16.696l-1.822 1.822M12 17.25a.75.75 0 100-1.5.75.75 0 000 1.5z" />
                        </svg>
                        <?php if ($new_grades_count > 0): ?><span class="notification-badge"><?php echo $new_grades_count; ?></span><?php endif; ?>
                    </a>

                    <a href="my_private_files.php" class="relative p-2 text-gray-500 hover:text-cyan-700" title="Private Files">
                        <svg class="w-7 h-7" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"></path></svg>
                        <?php if ($unread_files_count > 0): ?><span class="notification-badge"><?php echo $unread_files_count; ?></span><?php endif; ?>
                    </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>
            </div>
        </div>
    </header>
    <main id="subjects-section" class="max-w-5xl mx-auto py-8 px-4 sm:px-6 lg:px-8 flex-grow">
        <!-- The rest of the page remains exactly the same -->
        <div class="text-center mb-8"><h2 class="text-2xl md:text-3xl font-semibold text-gray-700">My Subjects</h2><p class="text-gray-500">Click on a subject to see your homework, notes, and grades!</p></div>
        <?php if (isset($dashboard_error)): ?><div class="p-4 text-center text-red-800 bg-red-100 rounded-lg"><?php echo htmlspecialchars($dashboard_error); ?></div>
        <?php elseif (empty($subjects)): ?><div class="p-6 text-center text-gray-600 bg-white rounded-lg shadow"><p>You don't have any subjects assigned yet. Please check back later!</p></div>
        <?php else: ?>
            <div class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-4 md:gap-6">
                <?php foreach ($subjects as $index => $subject): ?>
                    <?php 
                        $style = $subject_styles[$index % count($subject_styles)]; 
                        $new_count_for_subject = $new_material_counts[$subject['id']] ?? 0;
                    ?>
                    <a href="view_subject.php?id=<?php echo htmlspecialchars($subject['id']); ?>" class="subject-card <?php echo $style['bg']; ?>">
                        <?php if ($new_count_for_subject > 0): ?>
                            <span class="notification-badge"><?php echo $new_count_for_subject; ?></span>
                        <?php endif; ?>
                        <div class="subject-icon"><?php echo $style['icon']; ?></div>
                        <h3 class="mt-4 text-lg md:text-xl font-bold"><?php echo htmlspecialchars($subject['subject_name']); ?></h3>
                    </a>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </main>
    <footer class="text-center py-6 bg-white border-t"><p class="text-sm text-gray-500">by Ele Infocomm Technologies</p><p class="text-xs text-gray-500 mt-1">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>
    <script>
        const installButton = document.getElementById('install-button'); let deferredPrompt;
        window.addEventListener('beforeinstallprompt', (e) => { e.preventDefault(); deferredPrompt = e; if (installButton) { installButton.classList.remove('hidden'); } console.log('`beforeinstallprompt` event was fired.'); });
        if (installButton) { installButton.addEventListener('click', async () => { installButton.classList.add('hidden'); deferredPrompt.prompt(); const { outcome } = await deferredPrompt.userChoice; console.log(`User response to the install prompt: ${outcome}`); deferredPrompt = null; }); }
        if ('serviceWorker' in navigator) { window.addEventListener('load', () => { navigator.serviceWorker.register('/homework_portal/sw.js', { scope: '/homework_portal/' }).then(reg => console.log('SW registered.')).catch(err => console.log('SW registration failed: ', err)); }); }
    </script>
</body>
</html>