<?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();

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

// Get instructor's subjects for filter
$subjects_query = "SELECT * FROM subjects WHERE instructor_id = ?";
$stmt = $conn->prepare($subjects_query);
$stmt->bind_param("i", $instructor_id);
$stmt->execute();
$subjects_result = $stmt->get_result();
$subjects = [];
while ($row = $subjects_result->fetch_assoc()) {
    $subjects[] = $row;
}
$stmt->close();

// Get activities
$activities_query = "SELECT a.*, s.subject_name, s.subject_code,
                     (SELECT COUNT(*) FROM submissions sub WHERE sub.activity_id = a.id) as submission_count,
                     (SELECT COUNT(*) FROM submissions sub WHERE sub.activity_id = a.id AND sub.status = 'pending') as pending_count
                     FROM activities a
                     JOIN subjects s ON a.subject_id = s.id
                     WHERE a.created_by = ?";

if ($subject_filter) {
    $activities_query .= " AND s.id = ?";
}

$activities_query .= " ORDER BY a.due_date DESC";

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

if ($subject_filter) {
    $stmt->bind_param("ii", $instructor_id, $subject_filter);
} else {
    $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 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>Activities - 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 active">Activities</a>
                <a href="submissions.php" class="nav-link">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>📝 My Activities</h1>
            <a href="create_activity.php" class="btn btn-success">+ Create New Activity</a>
        </div>

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

        <!-- Filter Section -->
        <div class="filter-section">
            <div class="filter-group">
                <label>Filter by Subject:</label>
                <select onchange="window.location.href='activities.php?subject=' + this.value">
                    <option value="">All Subjects</option>
                    <?php foreach ($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="activities.php" class="btn btn-secondary">Clear Filter</a>
            <?php endif; ?>
        </div>

        <div class="dashboard-section full-width">
            <?php if (!empty($activities)): ?>
                <?php foreach ($activities as $activity): ?>
                    <div class="activity-item" style="margin-bottom: 20px;">
                        <div class="activity-info" style="flex: 1;">
                            <h4><?php echo htmlspecialchars($activity['title']); ?></h4>
                            <p class="subject-tag"><?php echo htmlspecialchars($activity['subject_name']); ?></p>
                            <p style="color: #666; margin-top: 10px;">
                                <?php echo nl2br(htmlspecialchars(substr($activity['description'], 0, 150))); ?>
                                <?php if (strlen($activity['description']) > 150): ?>...<?php endif; ?>
                            </p>
                            <div style="display: flex; gap: 20px; margin-top: 10px;">
                                <span class="due-date">📅 Due: <?php echo date('M d, Y H:i', strtotime($activity['due_date'])); ?></span>
                                <span style="color: #667eea; font-weight: 600;">📝 <?php echo $activity['submission_count']; ?> Submissions</span>
                                <?php if ($activity['pending_count'] > 0): ?>
                                    <span style="color: #ffc107; font-weight: 600;">⏳ <?php echo $activity['pending_count']; ?> Pending</span>
                                <?php endif; ?>
                            </div>
                        </div>
                        <div style="display: flex; flex-direction: column; gap: 10px;">
                            <a href="edit_activity.php?id=<?php echo $activity['id']; ?>" class="btn btn-small btn-secondary">Edit</a>
                            <a href="submissions.php?activity=<?php echo $activity['id']; ?>" class="btn btn-small btn-primary">View Submissions</a>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php else: ?>
                <p class="empty-message">📝 No activities yet. <a href="create_activity.php">Create your first activity</a></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>
