<?php
session_start();
require_once '../config/database.php';
require_once '../config/security.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();

// Handle enrollment with subject code
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['enroll'])) {
    requireCSRFToken();
    $subject_code = strtoupper(trim($_POST['subject_code']));

    if (empty($subject_code)) {
        $error_message = "Please enter a subject code!";
    } else {
        // Find subject by code
        $subject_query = "SELECT id, subject_name FROM subjects WHERE subject_code = ?";
        $stmt = $conn->prepare($subject_query);
        $stmt->bind_param("s", $subject_code);
        $stmt->execute();
        $subject_result = $stmt->get_result();

        if ($subject_result->num_rows == 0) {
            $error_message = "Invalid subject code! Please check the code and try again.";
        } else {
            $subject = $subject_result->fetch_assoc();
            $subject_id = $subject['id'];

            // Check if already enrolled
            $check_query = "SELECT * FROM enrollments WHERE student_id = ? AND subject_id = ?";
            $stmt = $conn->prepare($check_query);
            $stmt->bind_param("ii", $student_id, $subject_id);
            $stmt->execute();
            $check_result = $stmt->get_result();

            if ($check_result->num_rows > 0) {
                $error_message = "You are already enrolled in this subject!";
            } else {
                // Check if student is in the allowed list (if list exists)
                $allowed_check = "SELECT COUNT(*) as total FROM allowed_students WHERE subject_id = ?";
                $stmt = $conn->prepare($allowed_check);
                $stmt->bind_param("i", $subject_id);
                $stmt->execute();
                $allowed_count = $stmt->get_result()->fetch_assoc()['total'];

                // If there's an allowed list, check if student is in it
                if ($allowed_count > 0) {
                    // Get student's full name
                    $student_query = "SELECT full_name FROM users WHERE id = ?";
                    $stmt = $conn->prepare($student_query);
                    $stmt->bind_param("i", $student_id);
                    $stmt->execute();
                    $student_data = $stmt->get_result()->fetch_assoc();
                    $student_name = $student_data['full_name'];

                    // Check if student name is in allowed list
                    $name_check = "SELECT * FROM allowed_students WHERE subject_id = ? AND student_name = ?";
                    $stmt = $conn->prepare($name_check);
                    $stmt->bind_param("is", $subject_id, $student_name);
                    $stmt->execute();
                    $name_result = $stmt->get_result();

                    if ($name_result->num_rows == 0) {
                        $error_message = "You are not authorized to enroll in this subject. Please contact your instructor if you believe this is an error.";
                    }
                }

                // Enroll student only if authorized
                if (!isset($error_message)) {
                    $enroll_query = "INSERT INTO enrollments (student_id, subject_id) VALUES (?, ?)";
                    $stmt = $conn->prepare($enroll_query);
                    $stmt->bind_param("ii", $student_id, $subject_id);

                    if ($stmt->execute()) {
                    // Create notification for student
                    $notif_message = "You have successfully enrolled in " . $subject['subject_name'] . "!";
                    $notif_query = "INSERT INTO notifications (user_id, message, is_read) VALUES (?, ?, FALSE)";
                    $stmt = $conn->prepare($notif_query);
                    $stmt->bind_param("is", $student_id, $notif_message);
                    $stmt->execute();

                    // Notify instructor
                    $instructor_notif = $_SESSION['full_name'] . " enrolled in " . $subject['subject_name'];
                    $notif_instructor_query = "INSERT INTO notifications (user_id, message, is_read)
                                               SELECT instructor_id, ?, FALSE FROM subjects WHERE id = ?";
                    $stmt = $conn->prepare($notif_instructor_query);
                    $stmt->bind_param("si", $instructor_notif, $subject_id);
                    $stmt->execute();

                        $success_message = "Successfully enrolled in " . htmlspecialchars($subject['subject_name']) . "!";
                    } else {
                        $error_message = "Failed to enroll. Please try again.";
                    }
                }
            }
        }
        $stmt->close();
    }
}

// Get enrolled subjects
$enrolled_query = "SELECT s.*, u.full_name as instructor_name
                   FROM subjects s
                   JOIN enrollments e ON s.id = e.subject_id
                   LEFT JOIN users u ON s.instructor_id = u.id
                   WHERE e.student_id = ?
                   ORDER BY e.enrolled_at DESC";
$stmt = $conn->prepare($enrolled_query);
$stmt->bind_param("i", $student_id);
$stmt->execute();
$enrolled_result = $stmt->get_result();
$enrolled_subjects = [];
while ($row = $enrolled_result->fetch_assoc()) {
    $enrolled_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", $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>Enroll in 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/interactive-pet.js" defer></script>
    <script src="../assets/js/burger-menu.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">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>📚 Enroll in Subject</h1>
            <p>Enter the subject code provided by your instructor</p>
        </div>

        <?php if (isset($success_message)): ?>
            <div class="alert alert-success">
                ✓ <?php echo $success_message; ?>
            </div>
        <?php endif; ?>

        <?php if (isset($error_message)): ?>
            <div class="alert alert-error">
                ✗ <?php echo $error_message; ?>
            </div>
        <?php endif; ?>

        <!-- Enrollment Form -->
        <div class="dashboard-section" style="max-width: 600px; margin: 0 auto 30px;">
            <div class="section-header">
                <h2>🔑 Enter Subject Code</h2>
            </div>
            <form method="POST">
                <?php echo csrfField(); ?>
                <div style="background: #e8f8f5; padding: 20px; border-radius: 10px; margin-bottom: 20px; border-left: 4px solid #11998e;">
                    <p style="color: #333; line-height: 1.6; margin-bottom: 10px;">
                        <strong>📋 How to enroll:</strong>
                    </p>
                    <ol style="color: #666; line-height: 1.8; margin-left: 20px;">
                        <li>Get the subject code from your instructor (via email, messenger, etc.)</li>
                        <li>Enter the code in the field below</li>
                        <li>Click "Enroll" to join the subject</li>
                    </ol>
                    <p style="color: #11998e; margin-top: 15px; font-size: 0.9em;">
                        💡 <strong>Example codes:</strong> CPP101, PROG101, CS101
                    </p>
                </div>

                <div class="form-group">
                    <label>Subject Code *</label>
                    <input type="text"
                           name="subject_code"
                           placeholder="Enter subject code (e.g., CPP101)"
                           required
                           style="text-transform: uppercase; font-size: 1.2em; font-weight: 600; letter-spacing: 1px;"
                           maxlength="20"
                           autofocus>
                    <small style="color: #666;">The code is case-insensitive and usually 4-10 characters</small>
                </div>

                <button type="submit" name="enroll" class="btn btn-primary" style="width: 100%; padding: 15px; font-size: 1.1em;">
                    🎓 Enroll in Subject
                </button>
            </form>
        </div>

        <!-- Currently Enrolled Subjects -->
        <div class="dashboard-section full-width">
            <div class="section-header">
                <h2>📚 My Enrolled Subjects</h2>
            </div>
            <?php if (!empty($enrolled_subjects)): ?>
                <div class="subjects-grid">
                    <?php foreach ($enrolled_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: 10px; padding-top: 10px; border-top: 1px solid rgba(255,255,255,0.3);">
                                <p style="font-size: 0.9em; opacity: 0.9;">
                                    👤 Instructor: <?php echo htmlspecialchars($subject['instructor_name'] ?? 'Not assigned'); ?>
                                </p>
                                <p style="font-size: 0.9em; opacity: 0.9;">
                                    ✓ Enrolled
                                </p>
                            </div>
                            <div class="subject-footer" style="margin-top: 15px;">
                                <a href="activities.php?subject=<?php echo $subject['id']; ?>" class="btn btn-small" style="width: 100%;">
                                    View Activities
                                </a>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php else: ?>
                <p class="empty-message">
                    📚 You haven't enrolled in any subjects yet. Enter a subject code above to get started!
                </p>
            <?php endif; ?>
        </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>
                                    ${notif.activity_id ? `<a href="take_activity.php?id=${notif.activity_id}" class="notif-link">View Activity →</a>` : ''}
                                </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');
            }
        });

        // Auto-uppercase the subject code input
        document.querySelector('input[name="subject_code"]').addEventListener('input', function(e) {
            this.value = this.value.toUpperCase();
        });
    </script>
</body>
</html>
