<?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'];
$subject_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if (!$subject_id) {
    header('Location: subjects.php');
    exit();
}

$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 subject details (make sure it belongs to this instructor)
$subject_query = "SELECT * FROM subjects WHERE id = ? AND instructor_id = ?";
$stmt = $conn->prepare($subject_query);
$stmt->bind_param("ii", $subject_id, $instructor_id);
$stmt->execute();
$subject_result = $stmt->get_result();
$subject = $subject_result->fetch_assoc();
$stmt->close();

if (!$subject) {
    header('Location: subjects.php');
    exit();
}

// 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 enrolled students with violation statistics
$students_query = "SELECT u.*, e.enrolled_at
                   FROM users u
                   JOIN enrollments e ON u.id = e.student_id
                   WHERE e.subject_id = ?
                   ORDER BY u.year_level, u.section, u.full_name";
$stmt = $conn->prepare($students_query);
$stmt->bind_param("i", $subject_id);
$stmt->execute();
$students_result = $stmt->get_result();
$students = [];
while ($row = $students_result->fetch_assoc()) {
    // Get violation count for each student in this subject
    if ($has_violation_tracking) {
        $violation_query = "SELECT
                            COALESCE(SUM(s.violation_count), 0) as total_violations,
                            COUNT(CASE WHEN s.violation_count > 0 THEN 1 END) as activities_with_violations
                            FROM submissions s
                            JOIN activities a ON s.activity_id = a.id
                            WHERE s.student_id = ? AND a.subject_id = ?";
        $v_stmt = $conn->prepare($violation_query);
        $v_stmt->bind_param("ii", $row['id'], $subject_id);
        $v_stmt->execute();
        $v_result = $v_stmt->get_result();
        $v_data = $v_result->fetch_assoc();
        $row['total_violations'] = $v_data['total_violations'];
        $row['activities_with_violations'] = $v_data['activities_with_violations'];
        $v_stmt->close();
    } else {
        $row['total_violations'] = 0;
        $row['activities_with_violations'] = 0;
    }
    $students[] = $row;
}
$stmt->close();

// Get activities count
$activities_query = "SELECT COUNT(*) as count FROM activities WHERE subject_id = ?";
$stmt = $conn->prepare($activities_query);
$stmt->bind_param("i", $subject_id);
$stmt->execute();
$activities_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><?php echo htmlspecialchars($subject['subject_name']); ?> - 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/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="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>

    <div class="main-content">
        <div class="dashboard-header">
            <div>
                <a href="subjects.php" style="color: var(--primary-moss); text-decoration: none;">← Back to My Subjects</a>
                <h1>📚 <?php echo htmlspecialchars($subject['subject_name']); ?></h1>
                <p><?php echo htmlspecialchars($subject['subject_code']); ?></p>
            </div>
            <div style="display: flex; gap: 10px;">
                <a href="manage_allowed_students.php?id=<?php echo $subject['id']; ?>" class="btn btn-secondary">👥 Manage Allowed Students</a>
                <a href="create_activity.php?subject=<?php echo $subject['id']; ?>" class="btn btn-success">+ Create Activity</a>
            </div>
        </div>

        <!-- Subject Info -->
        <div class="dashboard-section full-width">
            <div class="section-header">
                <h2>📋 Subject Information</h2>
            </div>
            <div class="info-grid">
                <div class="info-item">
                    <strong>Description:</strong>
                    <p><?php echo htmlspecialchars($subject['description']); ?></p>
                </div>
                <div class="info-item">
                    <strong>Statistics:</strong>
                    <p>👥 <?php echo count($students); ?> Students | 📝 <?php echo $activities_count; ?> Activities</p>
                </div>
                <div class="info-item">
                    <strong>Subject Code:</strong>
                    <p style="font-size: 1.2em; color: var(--primary-moss); font-weight: bold;"><?php echo htmlspecialchars($subject['subject_code']); ?></p>
                    <small style="color: var(--text-secondary);">Share this code with students to enroll</small>
                </div>
            </div>
        </div>

        <!-- Enrolled Students -->
        <div class="dashboard-section full-width">
            <div class="section-header">
                <h2>👥 Enrolled Students (<?php echo count($students); ?>)</h2>
            </div>
            <?php if (!empty($students)): ?>
                <div class="students-grid">
                    <?php foreach ($students as $student): ?>
                        <div class="student-card">
                            <div class="student-avatar-container">
                                <?php if (isset($student['profile_picture']) && $student['profile_picture']): ?>
                                    <img src="../<?php echo htmlspecialchars($student['profile_picture']); ?>" alt="Profile" class="student-avatar-large">
                                <?php else: ?>
                                    <div class="student-avatar-large" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; display: flex; align-items: center; justify-content: center; font-size: 48px; font-weight: bold;">
                                        <?php echo strtoupper(substr($student['full_name'], 0, 1)); ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                            <div class="student-info">
                                <h3><?php echo htmlspecialchars($student['full_name']); ?></h3>
                                <p class="student-id">🆔 <?php echo htmlspecialchars($student['id_number'] ?? 'N/A'); ?></p>
                                <p class="student-detail">📧 <?php echo htmlspecialchars($student['email']); ?></p>
                                <p class="student-detail">👤 <?php echo htmlspecialchars($student['username']); ?></p>
                                <p class="student-detail">📚 <?php echo htmlspecialchars($student['year_level'] ?? 'N/A'); ?> - Section <?php echo htmlspecialchars($student['section'] ?? 'N/A'); ?></p>
                                <p class="student-detail"><small>Enrolled: <?php echo date('M d, Y', strtotime($student['enrolled_at'])); ?></small></p>

                                <?php if ($has_violation_tracking): ?>
                                    <div class="violation-badge <?php echo $student['total_violations'] > 0 ? 'has-violations' : 'no-violations'; ?>">
                                        ⚠️ Violations: <strong><?php echo $student['total_violations']; ?></strong>
                                        <?php if ($student['activities_with_violations'] > 0): ?>
                                            <small>(<?php echo $student['activities_with_violations']; ?> activities)</small>
                                        <?php endif; ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php else: ?>
                <p class="empty-message">👥 No students enrolled in this subject yet.</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 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>
                                </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>

    <style>
        .info-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
            margin-top: 15px;
        }

        .info-item {
            padding: 15px;
            background: rgba(255, 255, 255, 0.05);
            border-radius: 10px;
        }

        .info-item strong {
            color: var(--primary-moss);
            display: block;
            margin-bottom: 8px;
        }

        .students-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 20px;
            margin-top: 20px;
        }

        .student-card {
            background: var(--card-bg);
            border-radius: 15px;
            padding: 20px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            display: flex;
            flex-direction: column;
            align-items: center;
            text-align: center;
        }

        .student-avatar-container {
            margin-bottom: 15px;
        }

        .student-avatar-large {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            object-fit: cover;
            border: 3px solid var(--primary-moss);
        }

        .student-info {
            width: 100%;
        }

        .student-info h3 {
            margin: 0 0 10px 0;
            color: var(--text-primary);
            font-size: 1.1em;
        }

        .student-id {
            color: var(--primary-moss);
            font-weight: 600;
            margin: 5px 0;
        }

        .student-detail {
            color: var(--text-secondary);
            margin: 5px 0;
            font-size: 0.9em;
        }

        .violation-badge {
            margin-top: 12px;
            padding: 8px 12px;
            border-radius: 8px;
            font-size: 0.9em;
            display: inline-block;
            width: 100%;
        }

        .violation-badge.has-violations {
            background: rgba(220, 53, 69, 0.1);
            border: 1px solid rgba(220, 53, 69, 0.3);
            color: #dc3545;
        }

        .violation-badge.no-violations {
            background: rgba(40, 167, 69, 0.1);
            border: 1px solid rgba(40, 167, 69, 0.3);
            color: #28a745;
        }

        .violation-badge strong {
            font-size: 1.1em;
            margin: 0 4px;
        }

        .violation-badge small {
            display: block;
            margin-top: 4px;
            opacity: 0.8;
        }
    </style>
</body>
</html>
