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

// Get instructor's subjects
$subjects_query = "SELECT s.*,
                   (SELECT COUNT(*) FROM enrollments e WHERE e.subject_id = s.id) as student_count,
                   (SELECT COUNT(*) FROM activities a WHERE a.subject_id = s.id) as activity_count
                   FROM subjects s
                   WHERE s.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 pending submissions
$pending_query = "SELECT s.*, a.title, sub.subject_name, u.full_name as student_name
                  FROM submissions s
                  JOIN activities a ON s.activity_id = a.id
                  JOIN subjects sub ON a.subject_id = sub.id
                  JOIN users u ON s.student_id = u.id
                  WHERE a.created_by = ? AND s.status = 'pending'
                  ORDER BY s.submitted_at DESC
                  LIMIT 10";
$stmt = $conn->prepare($pending_query);
$stmt->bind_param("i", $instructor_id);
$stmt->execute();
$pending_result = $stmt->get_result();
$pending_submissions = [];
while ($row = $pending_result->fetch_assoc()) {
    $pending_submissions[] = $row;
}
$stmt->close();

// Get recent activities
$activities_query = "SELECT a.*, s.subject_name,
                     (SELECT COUNT(*) FROM submissions sub WHERE sub.activity_id = a.id) as submission_count
                     FROM activities a
                     JOIN subjects s ON a.subject_id = s.id
                     WHERE a.created_by = ?
                     ORDER BY a.created_at DESC
                     LIMIT 5";
$stmt = $conn->prepare($activities_query);
$stmt->bind_param("i", $instructor_id);
$stmt->execute();
$activities_result = $stmt->get_result();
$recent_activities = [];
while ($row = $activities_result->fetch_assoc()) {
    $recent_activities[] = $row;
}
$stmt->close();

// Calculate statistics
$total_students_query = "SELECT COUNT(DISTINCT e.student_id) as count
                         FROM enrollments e
                         JOIN subjects s ON e.subject_id = s.id
                         WHERE s.instructor_id = ?";
$stmt = $conn->prepare($total_students_query);
$stmt->bind_param("i", $instructor_id);
$stmt->execute();
$total_students = $stmt->get_result()->fetch_assoc()['count'];
$stmt->close();

$total_activities_query = "SELECT COUNT(*) as count FROM activities WHERE created_by = ?";
$stmt = $conn->prepare($total_activities_query);
$stmt->bind_param("i", $instructor_id);
$stmt->execute();
$total_activities = $stmt->get_result()->fetch_assoc()['count'];
$stmt->close();

$pending_count_query = "SELECT COUNT(*) as count
                        FROM submissions s
                        JOIN activities a ON s.activity_id = a.id
                        WHERE a.created_by = ? AND s.status = 'pending'";
$stmt = $conn->prepare($pending_count_query);
$stmt->bind_param("i", $instructor_id);
$stmt->execute();
$pending_count = $stmt->get_result()->fetch_assoc()['count'];
$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>Instructor Dashboard - CODELAB</title>
    <link rel="stylesheet" href="../assets/css/style.css">
    <link rel="stylesheet" href="../assets/css/tutorial.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/tutorial.js" defer></script>
    <script src="../assets/js/instructor-tutorial-steps.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 active">Dashboard</a>
                <a href="subjects.php" class="nav-link">My Subjects</a>
                <a href="students.php" class="nav-link">My Students</a>
                <a href="activities.php" class="nav-link">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>

    <!-- 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">
            <div class="welcome-section">
                <h1>Welcome back, <?php echo htmlspecialchars($_SESSION['full_name']); ?>! 👋</h1>
                <p>Manage your subjects, activities, and grade student submissions</p>
            </div>
        </div>

        <!-- Stats Cards -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-icon">📚</div>
                <div class="stat-info">
                    <h3>My Subjects</h3>
                    <p class="stat-value"><?php echo count($subjects); ?></p>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon">👥</div>
                <div class="stat-info">
                    <h3>Total Students</h3>
                    <p class="stat-value"><?php echo $total_students; ?></p>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon">📝</div>
                <div class="stat-info">
                    <h3>Total Activities</h3>
                    <p class="stat-value"><?php echo $total_activities; ?></p>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon">⏳</div>
                <div class="stat-info">
                    <h3>Pending Submissions</h3>
                    <p class="stat-value"><?php echo $pending_count; ?></p>
                </div>
            </div>
        </div>

        <!-- Main Dashboard Grid -->
        <div class="dashboard-grid">
            <!-- Pending Submissions Section -->
            <div class="dashboard-section">
                <div class="section-header">
                    <h2>⏳ Pending Submissions</h2>
                    <a href="submissions.php" class="view-all-link">View All →</a>
                </div>
                <div class="activities-list">
                    <?php if (!empty($pending_submissions)): ?>
                        <?php foreach ($pending_submissions as $submission): ?>
                            <div class="activity-item">
                                <div class="activity-info">
                                    <h4><?php echo htmlspecialchars($submission['title']); ?></h4>
                                    <p class="subject-tag"><?php echo htmlspecialchars($submission['subject_name']); ?></p>
                                    <p style="color: #666; margin-top: 5px;">
                                        👤 <?php echo htmlspecialchars($submission['student_name']); ?>
                                    </p>
                                    <p class="submitted-date">
                                        Submitted: <?php echo date('M d, Y H:i', strtotime($submission['submitted_at'])); ?>
                                    </p>
                                </div>
                                <a href="grade_submission.php?id=<?php echo $submission['id']; ?>" class="btn btn-small btn-primary">
                                    Grade
                                </a>
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <p class="empty-message">🎉 No pending submissions!</p>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Recent Activities Section -->
            <div class="dashboard-section">
                <div class="section-header">
                    <h2>📝 Recent Activities</h2>
                    <a href="activities.php" class="view-all-link">View All →</a>
                </div>
                <div class="scores-list">
                    <?php if (!empty($recent_activities)): ?>
                        <?php foreach ($recent_activities as $activity): ?>
                            <div class="score-item">
                                <div class="score-info">
                                    <h4><?php echo htmlspecialchars($activity['title']); ?></h4>
                                    <p class="subject-tag"><?php echo htmlspecialchars($activity['subject_name']); ?></p>
                                    <p class="submitted-date">
                                        Due: <?php echo date('M d, Y', strtotime($activity['due_date'])); ?>
                                    </p>
                                </div>
                                <div style="text-align: right;">
                                    <p style="color: #667eea; font-weight: 600; font-size: 1.2em;">
                                        <?php echo $activity['submission_count']; ?>
                                    </p>
                                    <p style="color: #666; font-size: 0.85em;">Submissions</p>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <p class="empty-message">📋 No activities yet. <a href="create_activity.php">Create one</a></p>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- My Subjects Section -->
        <div class="dashboard-section full-width">
            <div class="section-header">
                <h2>📚 My Subjects</h2>
                <a href="create_subject.php" class="btn btn-small btn-success">+ Create New Subject</a>
            </div>
            <div class="subjects-grid">
                <?php if (!empty($subjects)): ?>
                    <?php foreach ($subjects as $subject): ?>
                        <div class="subject-card">
                            <div class="subject-header">
                                <h3><?php echo htmlspecialchars($subject['subject_name']); ?></h3>
                                <span class="subject-code"><?php echo htmlspecialchars($subject['subject_code']); ?></span>
                            </div>
                            <p class="subject-description"><?php echo htmlspecialchars($subject['description']); ?></p>
                            <div style="margin-top: 15px; padding-top: 15px; border-top: 1px solid rgba(255,255,255,0.3);">
                                <p style="font-size: 0.9em; opacity: 0.9;">
                                    👥 <?php echo $subject['student_count']; ?> Students Enrolled
                                </p>
                                <p style="font-size: 0.9em; opacity: 0.9;">
                                    📝 <?php echo $subject['activity_count']; ?> Activities
                                </p>
                            </div>
                            <div class="subject-footer" style="margin-top: 15px;">
                                <a href="edit_subject.php?id=<?php echo $subject['id']; ?>" class="btn btn-small">Edit</a>
                                <a href="activities.php?subject=<?php echo $subject['id']; ?>" class="btn btn-small">View Activities</a>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <p class="empty-message">📚 You haven't created any subjects yet. <a href="create_subject.php">Create one</a></p>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <script src="../student/get_notifications.php"></script>
    <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('../student/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="submissions.php?activity=${notif.activity_id}" class="notif-link">View Submissions →</a>` : ''}
                                </div>
                            `;
                        });
                        content.innerHTML = html;

                        fetch('../student/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');
            }
        });

        // Initialize tutorial for new instructors
        window.addEventListener('load', function() {
            // Wait for tutorial steps to load
            setTimeout(function() {
                if (typeof Tutorial !== 'undefined' && typeof instructorTutorialSteps !== 'undefined') {
                    const tutorial = new Tutorial(instructorTutorialSteps, 'instructor');
                    tutorial.init();
                }
            }, 500);
        });
    </script>
</body>
</html>
