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

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

$instructor_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", $instructor_id);
$stmt->execute();
$user_result = $stmt->get_result();
$user = $user_result->fetch_assoc();
$stmt->close();

$activity_filter = isset($_GET['activity']) ? intval($_GET['activity']) : null;
$status_filter = isset($_GET['status']) ? $_GET['status'] : null;

// Get instructor's activities for filter
$activities_query = "SELECT a.*, s.subject_name FROM activities a
                     JOIN subjects s ON a.subject_id = s.id
                     WHERE a.created_by = ?";
$stmt = $conn->prepare($activities_query);
$stmt->bind_param("i", $instructor_id);
$stmt->execute();
$activities_result = $stmt->get_result();
$activities = [];
while ($row = $activities_result->fetch_assoc()) {
    $activities[] = $row;
}
$stmt->close();

// Get submissions
$submissions_query = "SELECT sub.*, a.title as activity_title, s.subject_name, u.full_name as student_name
                      FROM submissions sub
                      JOIN activities a ON sub.activity_id = a.id
                      JOIN subjects s ON a.subject_id = s.id
                      JOIN users u ON sub.student_id = u.id
                      WHERE a.created_by = ?";

if ($activity_filter) {
    $submissions_query .= " AND a.id = ?";
}
if ($status_filter) {
    $submissions_query .= " AND sub.status = ?";
}

$submissions_query .= " ORDER BY sub.submitted_at DESC";

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

if ($activity_filter && $status_filter) {
    $stmt->bind_param("iis", $instructor_id, $activity_filter, $status_filter);
} elseif ($activity_filter) {
    $stmt->bind_param("ii", $instructor_id, $activity_filter);
} elseif ($status_filter) {
    $stmt->bind_param("is", $instructor_id, $status_filter);
} else {
    $stmt->bind_param("i", $instructor_id);
}

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

// 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", $instructor_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>Submissions - 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/burger-menu.js" defer></script>
    <script src="../assets/js/push-notifications.js" defer></script>
    <script src="../assets/js/interactive-pet.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="submissions.php" class="nav-link active">Submissions</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>

    <div class="main-content">
        <div class="dashboard-header">
            <h1>📬 Student Submissions</h1>
            <p>Review and grade student work</p>
        </div>

        <?php if (isset($_GET['success']) && $_GET['success'] == 'graded'): ?>
            <div class="alert alert-success">Submission graded successfully!</div>
        <?php endif; ?>

        <!-- Filter Section -->
        <div class="filter-section">
            <div class="filter-activity">
                <label>Filter by Activity:</label>
                <select onchange="window.location.href='submissions.php?activity=' + this.value + '&status=<?php echo $status_filter; ?>'">
                    <option value="">All Activities</option>
                    <?php foreach ($activities as $activity): ?>
                        <option value="<?php echo $activity['id']; ?>" <?php echo $activity_filter == $activity['id'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($activity['title']) . ' (' . $activity['subject_name'] . ')'; ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="filter-activity">
                <label>Filter by Status:</label>
                <select onchange="window.location.href='submissions.php?activity=<?php echo $activity_filter; ?>&status=' + this.value">
                    <option value="">All Statuses</option>
                    <option value="pending" <?php echo $status_filter == 'pending' ? 'selected' : ''; ?>>⏳ Pending</option>
                    <option value="graded" <?php echo $status_filter == 'graded' ? 'selected' : ''; ?>>✓ Graded</option>
                </select>
            </div>
            <?php if ($activity_filter || $status_filter): ?>
                <a href="submissions.php" class="btn btn-secondary btn-small">Clear Filters</a>
            <?php endif; ?>
        </div>

        <div class="dashboard-section full-width">
            <?php if (!empty($submissions)): ?>
                <div class="data-table">
                    <table>
                        <thead>
                            <tr>
                                <th>Student</th>
                                <th>Activity</th>
                                <th>Subject</th>
                                <th>Submitted</th>
                                <th>Status</th>
                                <th>Violations</th>
                                <th>Score</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($submissions as $submission): ?>
                                <tr>
                                    <td><strong><?php echo htmlspecialchars($submission['student_name']); ?></strong></td>
                                    <td><?php echo htmlspecialchars($submission['activity_title']); ?></td>
                                    <td><span class="subject-tag"><?php echo htmlspecialchars($submission['subject_name']); ?></span></td>
                                    <td>
                                        <?php echo date('M d, Y H:i', strtotime($submission['submitted_at'])); ?>
                                        <?php if (isset($submission['is_auto_submitted']) && $submission['is_auto_submitted']): ?>
                                            <br><small style="color: #dc3545; font-weight: 600;">🤖 Auto-submitted</small>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php if ($submission['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
                                        $violation_count = $submission['violation_count'] ?? 0;
                                        if ($violation_count > 0):
                                        ?>
                                            <span style="color: <?php echo $violation_count > 2 ? '#dc3545' : '#ffc107'; ?>; font-weight: 600;">
                                                ⚠️ <?php echo $violation_count; ?>
                                            </span>
                                        <?php else: ?>
                                            <span style="color: #28a745; font-weight: 600;">✓ 0</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php if ($submission['status'] == 'graded'): ?>
                                            <span class="score-value <?php echo $submission['score'] >= 75 ? 'passing' : 'failing'; ?>">
                                                <?php echo number_format($submission['score'], 2); ?>%
                                            </span>
                                        <?php else: ?>
                                            -
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <a href="grade_submission.php?id=<?php echo $submission['id']; ?>" class="btn btn-small btn-primary">
                                            <?php echo $submission['status'] == 'graded' ? 'Review' : 'Grade'; ?>
                                        </a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php else: ?>
                <p class="empty-message">📬 No submissions found.</p>
            <?php endif; ?>
        </div>
    </div>

    <!-- 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>

    <script>
        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>
                                </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');
            }
        });
    </script>
</body>
</html>
