<?php
session_start();
require_once '../config/database.php';

if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] != 'student') {
    header('Location: ../index.php');
    exit();
}

$student_id = $_SESSION['user_id'];
$conn = getDBConnection();

// Get user data including profile picture
$user_query = "SELECT profile_picture FROM users WHERE id = ?";
$stmt = $conn->prepare($user_query);
$stmt->bind_param("i", $student_id);
$stmt->execute();
$user_result = $stmt->get_result();
$user = $user_result->fetch_assoc();
$stmt->close();

// Get filter parameter
$subject_filter = isset($_GET['subject']) ? intval($_GET['subject']) : null;

// Get enrolled subjects for filter
$subjects_query = "SELECT s.*
                   FROM subjects s
                   JOIN enrollments e ON s.id = e.subject_id
                   WHERE e.student_id = ?";
$stmt = $conn->prepare($subjects_query);
$stmt->bind_param("i", $student_id);
$stmt->execute();
$subjects_result = $stmt->get_result();
$enrolled_subjects = [];
while ($row = $subjects_result->fetch_assoc()) {
    $enrolled_subjects[] = $row;
}
$stmt->close();

// Add passing_grade column if it doesn't exist
$conn->query("ALTER TABLE activities ADD COLUMN IF NOT EXISTS passing_grade DECIMAL(5,2) DEFAULT 75.00");

// Get all submissions with grades and passing grade
$grades_query = "SELECT s.*, a.title, a.due_date, a.passing_grade, sub.subject_name, sub.subject_code
                 FROM submissions s
                 JOIN activities a ON s.activity_id = a.id
                 JOIN subjects sub ON a.subject_id = sub.id
                 WHERE s.student_id = ?";

if ($subject_filter) {
    $grades_query .= " AND sub.id = ?";
}

$grades_query .= " ORDER BY s.submitted_at DESC";

$stmt = $conn->prepare($grades_query);

if ($subject_filter) {
    $stmt->bind_param("ii", $student_id, $subject_filter);
} else {
    $stmt->bind_param("i", $student_id);
}

$stmt->execute();
$grades_result = $stmt->get_result();
$grades = [];
while ($row = $grades_result->fetch_assoc()) {
    $grades[] = $row;
}
$stmt->close();

// Calculate statistics
$total_submissions = count($grades);
$graded_submissions = array_filter($grades, function($g) { return $g['status'] == 'graded'; });
$graded_count = count($graded_submissions);

$avg_score = 0;
$passing_count = 0;
$failing_count = 0;
if ($graded_count > 0) {
    $total_score = 0;
    foreach ($graded_submissions as $grade) {
        $total_score += $grade['score'];
        $passing_grade = isset($grade['passing_grade']) ? $grade['passing_grade'] : 75;
        if ($grade['score'] >= $passing_grade) {
            $passing_count++;
        } else {
            $failing_count++;
        }
    }
    $avg_score = $total_score / $graded_count;
}

// Get unread notifications count
$notif_count_query = "SELECT COUNT(*) as count FROM notifications WHERE user_id = ? AND is_read = FALSE";
$stmt = $conn->prepare($notif_count_query);
$stmt->bind_param("i", $student_id);
$stmt->execute();
$notif_result = $stmt->get_result();
$notif_count = $notif_result->fetch_assoc()['count'];
$stmt->close();

$conn->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Grades - CODELAB</title>
    <link rel="stylesheet" href="../assets/css/style.css">
    <script src="../assets/js/dark-mode.js" defer>
        // HTML escape function to prevent XSS
        function escapeHtml(text) {
            if (!text) return '';
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
</script>
    <script src="../assets/js/interactive-pet.js" defer></script>
    <script src="../assets/js/push-notifications.js" defer></script>
</head>
<body>
    <nav class="navbar">
        <div class="nav-container">
            <div class="nav-brand">
                <?php if (isset($user['profile_picture']) && $user['profile_picture']): ?>
                    <img src="../<?php echo htmlspecialchars($user['profile_picture']); ?>" alt="Profile" class="nav-profile-pic">
                <?php else: ?>
                    <div class="nav-avatar"><?php echo strtoupper(substr($_SESSION['full_name'], 0, 1)); ?></div>
                <?php endif; ?>
                <h2>CODELAB</h2>
            </div>
            <button class="burger-menu" onclick="toggleMenu()">
                <span></span>
                <span></span>
                <span></span>
            </button>
            <div class="nav-menu" id="nav-menu">
                <a href="dashboard.php" class="nav-link">Dashboard</a>
                <a href="subjects.php" class="nav-link">My Subjects</a>
                <a href="activities.php" class="nav-link">Activities</a>
                <a href="grades.php" class="nav-link active">Grades</a>
                <a href="profile.php" class="nav-link">Profile</a>
                <a href="#" class="nav-link notification-bell" onclick="toggleNotifications()">
                    🔔 Notifications
                    <?php if ($notif_count > 0): ?>
                        <span class="badge"><?php echo $notif_count; ?></span>
                    <?php endif; ?>
                </a>
                <a href="../auth/logout.php" class="nav-link logout">Logout</a>
            </div>
        </div>
    </nav>

    <!-- Notifications Panel -->
    <div id="notifications-panel" class="notifications-panel">
        <div class="notifications-header">
            <h3>📬 Notifications</h3>
            <button onclick="toggleNotifications()" class="close-btn">×</button>
        </div>
        <div class="notifications-content" id="notifications-content">
            <p class="loading">Loading notifications...</p>
        </div>
    </div>

    <div class="main-content">
        <div class="dashboard-header">
            <h1>🏆 My Grades</h1>
            <p>Track your performance across all activities</p>
        </div>

        <!-- Stats Cards -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-icon">📝</div>
                <div class="stat-info">
                    <h3>Total Submissions</h3>
                    <p class="stat-value"><?php echo $total_submissions; ?></p>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon">✅</div>
                <div class="stat-info">
                    <h3>Graded</h3>
                    <p class="stat-value"><?php echo $graded_count; ?></p>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon">🎯</div>
                <div class="stat-info">
                    <h3>Passed</h3>
                    <p class="stat-value"><?php echo $passing_count; ?></p>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon">❌</div>
                <div class="stat-info">
                    <h3>Failed</h3>
                    <p class="stat-value"><?php echo $failing_count; ?></p>
                </div>
            </div>
        </div>

        <!-- Filter Section -->
        <div class="filter-section">
            <div class="filter-group">
                <label>Filter by Subject:</label>
                <select onchange="window.location.href='grades.php?subject=' + this.value" class="form-control">
                    <option value="">All Subjects</option>
                    <?php foreach ($enrolled_subjects as $subject): ?>
                        <option value="<?php echo $subject['id']; ?>" <?php echo $subject_filter == $subject['id'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($subject['subject_name']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <?php if ($subject_filter): ?>
                <a href="grades.php" class="btn btn-secondary">Clear Filter</a>
            <?php endif; ?>
        </div>

        <!-- Grades Table -->
        <div class="dashboard-section full-width">
            <?php if (!empty($grades)): ?>
                <div class="data-table">
                    <table>
                        <thead>
                            <tr>
                                <th>Activity</th>
                                <th>Subject</th>
                                <th>Submitted</th>
                                <th>Status</th>
                                <th>Score</th>
                                <th>Feedback</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($grades as $grade): ?>
                                <tr>
                                    <td>
                                        <strong><?php echo htmlspecialchars($grade['title']); ?></strong>
                                        <br>
                                        <small style="color: #666;">Due: <?php echo date('M d, Y', strtotime($grade['due_date'])); ?></small>
                                    </td>
                                    <td>
                                        <span class="subject-tag"><?php echo htmlspecialchars($grade['subject_name']); ?></span>
                                    </td>
                                    <td><?php echo date('M d, Y H:i', strtotime($grade['submitted_at'])); ?></td>
                                    <td>
                                        <?php if ($grade['status'] == 'graded'): ?>
                                            <span style="color: #28a745; font-weight: 600;">✓ Graded</span>
                                        <?php else: ?>
                                            <span style="color: #ffc107; font-weight: 600;">⏳ Pending</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php if ($grade['status'] == 'graded'): ?>
                                            <?php
                                            $passing_grade = isset($grade['passing_grade']) ? $grade['passing_grade'] : 75;
                                            $is_passing = $grade['score'] >= $passing_grade;
                                            ?>
                                            <span class="score-value <?php echo $is_passing ? 'passing' : 'failing'; ?>" style="font-size: 1.2em;">
                                                <?php echo number_format($grade['score'], 2); ?>%
                                            </span>
                                            <br>
                                            <small style="color: #666;">Passing: <?php echo number_format($passing_grade, 0); ?>%</small>
                                        <?php else: ?>
                                            <span style="color: #999;">-</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php if ($grade['feedback']): ?>
                                            <button onclick="showFeedback('<?php echo htmlspecialchars($grade['title'], ENT_QUOTES); ?>', '<?php echo htmlspecialchars(str_replace(array("\r", "\n"), ' ', $grade['feedback']), ENT_QUOTES); ?>')" class="btn btn-small btn-secondary">
                                                View
                                            </button>
                                        <?php else: ?>
                                            <span style="color: #999;">-</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <a href="take_activity.php?id=<?php echo $grade['activity_id']; ?>" class="btn btn-small btn-primary">
                                            View
                                        </a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php else: ?>
                <p class="empty-message">
                    <?php if ($subject_filter): ?>
                        No submissions found for this subject.
                    <?php else: ?>
                        📚 No submissions yet. Start working on activities to see your grades here!
                    <?php endif; ?>
                </p>
            <?php endif; ?>
        </div>
    </div>

    <!-- Feedback Modal -->
    <div id="feedback-modal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 3000; align-items: center; justify-content: center;">
        <div style="background: white; padding: 30px; border-radius: 15px; max-width: 600px; width: 90%; max-height: 80vh; overflow-y: auto;">
            <h2 id="feedback-title" style="color: #333; margin-bottom: 20px;"></h2>
            <div id="feedback-content" style="background: #f8f9ff; padding: 20px; border-radius: 8px; border-left: 4px solid #667eea; line-height: 1.8;">
            </div>
            <button onclick="closeFeedback()" class="btn btn-primary" style="margin-top: 20px;">Close</button>
        </div>
    </div>

    <script>
        function toggleMenu() {
            const navMenu = document.getElementById('nav-menu');
            navMenu.classList.toggle('active');
        }

        function toggleNotifications() {
            const panel = document.getElementById('notifications-panel');
            const isOpen = panel.classList.contains('open');

            if (isOpen) {
                panel.classList.remove('open');
            } else {
                panel.classList.add('open');
                loadNotifications();
            }
        }

        function loadNotifications() {
            const content = document.getElementById('notifications-content');

            fetch('get_notifications.php')
                .then(response => response.json())
                .then(data => {
                    if (data.length === 0) {
                        content.innerHTML = '<p class="empty-message">No notifications yet.</p>';
                    } else {
                        let html = '';
                        data.forEach(notif => {
                            html += `
                                <div class="notification-item ${notif.is_read ? '' : 'unread'}">
                                    <p>${escapeHtml(notif.message)}</p>
                                    <span class="notif-time">${escapeHtml(notif.created_at)}</span>
                                    ${notif.activity_id ? `<a href="take_activity.php?id=${notif.activity_id}" class="notif-link">View Activity →</a>` : ''}
                                </div>
                            `;
                        });
                        content.innerHTML = html;

                        fetch('mark_notifications_read.php');
                    }
                })
                .catch(error => {
                    content.innerHTML = '<p class="error-message">Failed to load notifications.</p>';
                });
        }

        document.addEventListener('click', function(event) {
            const panel = document.getElementById('notifications-panel');
            const target = event.target;

            if (!panel.contains(target) && !target.closest('.nav-link')) {
                panel.classList.remove('open');
            }
        });

        function showFeedback(title, feedback) {
            document.getElementById('feedback-title').textContent = 'Feedback: ' + title;
            document.getElementById('feedback-content').innerHTML = feedback.replace(/\n/g, '<br>');
            const modal = document.getElementById('feedback-modal');
            modal.style.display = 'flex';
        }

        function closeFeedback() {
            document.getElementById('feedback-modal').style.display = 'none';
        }

        // Close modal on outside click
        document.getElementById('feedback-modal').addEventListener('click', function(e) {
            if (e.target === this) {
                closeFeedback();
            }
        });
    </script>
</body>
</html>
