<?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 parameters
$subject_filter = isset($_GET['subject']) ? intval($_GET['subject']) : null;
$status_filter = isset($_GET['status']) ? $_GET['status'] : 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();

// Check if violation tracking columns exist
$check_columns = $conn->query("SHOW COLUMNS FROM submissions LIKE 'violation_count'");
$has_violation_tracking = $check_columns->num_rows > 0;

// Get activities
if ($has_violation_tracking) {
    $activities_query = "SELECT a.*, s.subject_name, s.subject_code,
                         (SELECT COUNT(*) FROM submissions sub WHERE sub.activity_id = a.id AND sub.student_id = ?) as submitted,
                         (SELECT score FROM submissions sub WHERE sub.activity_id = a.id AND sub.student_id = ? LIMIT 1) as student_score,
                         (SELECT status FROM submissions sub WHERE sub.activity_id = a.id AND sub.student_id = ? LIMIT 1) as submission_status,
                         (SELECT violation_count FROM submissions sub WHERE sub.activity_id = a.id AND sub.student_id = ? LIMIT 1) as violation_count,
                         (SELECT is_auto_submitted FROM submissions sub WHERE sub.activity_id = a.id AND sub.student_id = ? LIMIT 1) as is_auto_submitted
                         FROM activities a
                         JOIN subjects s ON a.subject_id = s.id
                         JOIN enrollments e ON s.id = e.subject_id
                         WHERE e.student_id = ?";
} else {
    $activities_query = "SELECT a.*, s.subject_name, s.subject_code,
                         (SELECT COUNT(*) FROM submissions sub WHERE sub.activity_id = a.id AND sub.student_id = ?) as submitted,
                         (SELECT score FROM submissions sub WHERE sub.activity_id = a.id AND sub.student_id = ? LIMIT 1) as student_score,
                         (SELECT status FROM submissions sub WHERE sub.activity_id = a.id AND sub.student_id = ? LIMIT 1) as submission_status
                         FROM activities a
                         JOIN subjects s ON a.subject_id = s.id
                         JOIN enrollments e ON s.id = e.subject_id
                         WHERE e.student_id = ?";
}

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

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

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

if ($has_violation_tracking) {
    if ($subject_filter) {
        $stmt->bind_param("iiiiiii", $student_id, $student_id, $student_id, $student_id, $student_id, $student_id, $subject_filter);
    } else {
        $stmt->bind_param("iiiiii", $student_id, $student_id, $student_id, $student_id, $student_id, $student_id);
    }
} else {
    if ($subject_filter) {
        $stmt->bind_param("iiiii", $student_id, $student_id, $student_id, $student_id, $subject_filter);
    } else {
        $stmt->bind_param("iiii", $student_id, $student_id, $student_id, $student_id);
    }
}

$stmt->execute();
$activities_result = $stmt->get_result();
$activities = [];
while ($row = $activities_result->fetch_assoc()) {
    // Add status categorization
    $is_overdue = strtotime($row['due_date']) < time() && $row['submitted'] == 0;
    $is_submitted = $row['submitted'] > 0;

    if ($is_overdue) {
        $row['activity_status'] = 'missing';
    } elseif ($is_submitted) {
        $row['activity_status'] = 'completed';
    } else {
        $row['activity_status'] = 'pending';
    }

    $activities[] = $row;
}
$stmt->close();

// Apply status filter
if ($status_filter && in_array($status_filter, ['missing', 'completed', 'pending'])) {
    $activities = array_filter($activities, function($activity) use ($status_filter) {
        return $activity['activity_status'] === $status_filter;
    });
}

// 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>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/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 active">Activities</a>
                <a href="grades.php" class="nav-link">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 Activities</h1>
            <p>View and complete your programming activities</p>
        </div>

        <!-- Filter Section -->
        <div class="filter-section">
            <div class="filter-group">
                <label>Filter by Subject:</label>
                <select onchange="applyFilters('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>
            <div class="filter-group">
                <label>Filter by Status:</label>
                <select onchange="applyFilters('status', this.value)" class="form-control" id="status-filter">
                    <option value="">All Status</option>
                    <option value="completed" <?php echo $status_filter == 'completed' ? 'selected' : ''; ?>>✓ Completed</option>
                    <option value="missing" <?php echo $status_filter == 'missing' ? 'selected' : ''; ?>>❌ Missing</option>
                </select>
            </div>
            <?php if ($subject_filter || $status_filter): ?>
                <a href="activities.php" class="btn btn-secondary">Clear Filters</a>
            <?php endif; ?>
        </div>

        <!-- Activities List -->
        <div class="dashboard-section full-width">
            <?php if (!empty($activities)): ?>
                <?php foreach ($activities as $activity): ?>
                    <?php
                        $is_overdue = strtotime($activity['due_date']) < time() && $activity['submitted'] == 0;
                        $is_submitted = $activity['submitted'] > 0;
                    ?>
                    <div class="activity-item" style="margin-bottom: 20px; <?php echo $is_overdue ? 'border-left-color: #dc3545;' : ''; ?>">
                        <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; flex-wrap: wrap;">
                                <span class="due-date">
                                    📅 Due: <?php echo date('M d, Y H:i', strtotime($activity['due_date'])); ?>
                                </span>
                                <?php if ($is_overdue): ?>
                                    <span style="color: #dc3545; font-weight: 600;">❌ Missing</span>
                                <?php endif; ?>
                                <?php if ($is_submitted): ?>
                                    <span style="color: #28a745; font-weight: 600;">✓ Submitted</span>
                                    <?php if (isset($activity['is_auto_submitted']) && $activity['is_auto_submitted']): ?>
                                        <span style="color: #dc3545; font-weight: 600;">🤖 Auto-submitted</span>
                                    <?php endif; ?>
                                    <?php if (isset($activity['violation_count']) && $activity['violation_count'] > 0): ?>
                                        <span style="color: <?php echo $activity['violation_count'] > 2 ? '#dc3545' : '#ffc107'; ?>; font-weight: 600;">
                                            ⚠️ Violations: <?php echo $activity['violation_count']; ?>
                                        </span>
                                    <?php endif; ?>
                                    <?php if ($activity['submission_status'] == 'graded'): ?>
                                        <span style="color: #667eea; font-weight: 600;">
                                            Score: <?php echo number_format($activity['student_score'], 2); ?>%
                                        </span>
                                    <?php else: ?>
                                        <span style="color: #ffc107; font-weight: 600;">⏳ Pending Review</span>
                                    <?php endif; ?>
                                <?php endif; ?>
                            </div>
                        </div>
                        <div style="display: flex; flex-direction: column; gap: 10px;">
                            <a href="take_activity.php?id=<?php echo $activity['id']; ?>" class="btn btn-primary btn-small">
                                <?php echo $is_submitted ? 'View Submission' : 'Start Activity'; ?>
                            </a>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php else: ?>
                <p class="empty-message">
                    <?php if ($subject_filter): ?>
                        No activities found for this subject.
                    <?php else: ?>
                        📚 No activities available yet. Check back later!
                    <?php endif; ?>
                </p>
            <?php endif; ?>
        </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;

                        // Mark notifications as read
                        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 applyFilters(filterType, value) {
            const urlParams = new URLSearchParams(window.location.search);

            if (value) {
                urlParams.set(filterType, value);
            } else {
                urlParams.delete(filterType);
            }

            // Preserve other filters
            const newUrl = urlParams.toString() ?
                'activities.php?' + urlParams.toString() :
                'activities.php';

            window.location.href = newUrl;
        }
    </script>

    <style>
        .filter-section {
            display: flex;
            gap: 15px;
            align-items: flex-end;
            margin-bottom: 20px;
            flex-wrap: wrap;
            background: var(--card-bg);
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        .filter-group {
            display: flex;
            flex-direction: column;
            gap: 8px;
            min-width: 200px;
        }

        .filter-group label {
            font-weight: 600;
            color: var(--text-primary);
            font-size: 0.9em;
        }

        .filter-group .form-control {
            padding: 10px;
            border-radius: 6px;
            border: 1px solid rgba(255, 255, 255, 0.1);
            background: rgba(255, 255, 255, 0.05);
            color: var(--text-primary);
            font-size: 0.95em;
            cursor: pointer;
        }

        .filter-group .form-control:focus {
            outline: none;
            border-color: var(--primary-moss);
            box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
        }

        .filter-group .form-control option {
            background: var(--bg-primary);
            color: var(--text-primary);
        }

        .btn-secondary {
            background: #6c757d;
            color: white;
            padding: 10px 20px;
            border-radius: 6px;
            text-decoration: none;
            border: none;
            cursor: pointer;
            font-size: 0.95em;
            transition: all 0.3s ease;
            height: fit-content;
        }

        .btn-secondary:hover {
            background: #5a6268;
            transform: translateY(-2px);
        }
    </style>
</body>
</html>
