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

// 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 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 = ?
                   ORDER BY s.created_at DESC";
$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()) {
    // Get violation statistics for this subject
    if ($has_violation_tracking) {
        $violation_query = "SELECT
                            COUNT(DISTINCT sub.student_id) as students_with_violations,
                            SUM(sub.violation_count) as total_violations
                            FROM submissions sub
                            JOIN activities a ON sub.activity_id = a.id
                            WHERE a.subject_id = ? AND sub.violation_count > 0";
        $v_stmt = $conn->prepare($violation_query);
        $v_stmt->bind_param("i", $row['id']);
        $v_stmt->execute();
        $v_result = $v_stmt->get_result();
        $v_data = $v_result->fetch_assoc();
        $v_stmt->close();

        $row['students_with_violations'] = $v_data['students_with_violations'] ?? 0;
        $row['total_violations'] = $v_data['total_violations'] ?? 0;
    } else {
        $row['students_with_violations'] = 0;
        $row['total_violations'] = 0;
    }

    $subjects[] = $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>My Subjects - 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 active">My Subjects</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>

    <div class="main-content">
        <div class="dashboard-header">
            <h1>📚 My Subjects</h1>
            <a href="create_subject.php" class="btn btn-success">+ Create New Subject</a>
        </div>

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

        <div class="dashboard-section full-width">
            <?php if (!empty($subjects)): ?>
                <div class="subjects-grid">
                    <?php foreach ($subjects as $subject): ?>
                        <div class="subject-card" style="cursor: pointer;" onclick="window.location.href='subject_details.php?id=<?php echo $subject['id']; ?>'">
                            <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</p>
                                <p style="font-size: 0.9em; opacity: 0.9;">📝 <?php echo $subject['activity_count']; ?> Activities</p>

                                <?php if ($subject['students_with_violations'] > 0): ?>
                                    <div style="margin-top: 12px; padding: 10px; background: rgba(220, 53, 69, 0.1); border-radius: 8px; border-left: 4px solid #dc3545;">
                                        <strong style="color: #dc3545; font-size: 0.95em;">
                                            ⚠️ <?php echo $subject['students_with_violations']; ?> Student<?php echo $subject['students_with_violations'] != 1 ? 's' : ''; ?> with Violations
                                        </strong>
                                        <div style="font-size: 0.85em; color: #dc3545; margin-top: 4px;">
                                            Total violations: <?php echo $subject['total_violations']; ?>
                                        </div>
                                    </div>
                                <?php else: ?>
                                    <div style="margin-top: 12px; padding: 10px; background: rgba(40, 167, 69, 0.1); border-radius: 8px; border-left: 4px solid #28a745;">
                                        <small style="color: #28a745; font-size: 0.85em;">
                                            ✓ No violations detected
                                        </small>
                                    </div>
                                <?php endif; ?>
                            </div>
                            <div class="subject-footer" style="margin-top: 15px; gap: 10px;">
                                <a href="edit_subject.php?id=<?php echo $subject['id']; ?>" class="btn btn-small" onclick="event.stopPropagation()">Edit</a>
                                <a href="create_activity.php?subject=<?php echo $subject['id']; ?>" class="btn btn-small" onclick="event.stopPropagation()">+ Activity</a>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php else: ?>
                <p class="empty-message">📚 No subjects yet. <a href="create_subject.php">Create your first subject</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>
