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

$selected_subject = isset($_GET['subject']) ? intval($_GET['subject']) : null;

// Add passing_grade column if it doesn't exist
$check = $conn->query("SHOW COLUMNS FROM activities LIKE 'passing_grade'");
if ($check && $check->num_rows == 0) {
    $conn->query("ALTER TABLE activities ADD COLUMN passing_grade DECIMAL(5,2) DEFAULT 75.00");
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    requireCSRFToken();
    $subject_id = intval($_POST['subject_id']);
    $title = trim($_POST['title']);
    $description = trim($_POST['description']);
    $starter_code = $_POST['starter_code'] ?? '';
    $expected_output = $_POST['expected_output'] ?? '';
    $due_date = $_POST['due_date'];
    $passing_grade = isset($_POST['passing_grade']) ? floatval($_POST['passing_grade']) : 75.00;
    $time_limit = isset($_POST['enable_time_limit']) && $_POST['enable_time_limit'] == '1' ? intval($_POST['time_limit']) : NULL;

    $insert_query = "INSERT INTO activities (subject_id, title, description, starter_code, expected_output, due_date, passing_grade, time_limit, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
    $stmt = $conn->prepare($insert_query);
    $stmt->bind_param("isssssdii", $subject_id, $title, $description, $starter_code, $expected_output, $due_date, $passing_grade, $time_limit, $instructor_id);

    if ($stmt->execute()) {
        $activity_id = $conn->insert_id;

        // Create notifications for all enrolled students
        $notif_message = "New activity available: " . $title;
        $notif_query = "INSERT INTO notifications (user_id, message, activity_id, is_read)
                        SELECT student_id, ?, ?, FALSE FROM enrollments WHERE subject_id = ?";
        $stmt = $conn->prepare($notif_query);
        $stmt->bind_param("sii", $notif_message, $activity_id, $subject_id);
        $stmt->execute();

        // Send push notifications to all enrolled students
        require_once '../api/send_push_notification.php';
        $students_query = "SELECT student_id FROM enrollments WHERE subject_id = ?";
        $stmt = $conn->prepare($students_query);
        $stmt->bind_param("i", $subject_id);
        $stmt->execute();
        $students_result = $stmt->get_result();

        $activity_url = '/Capstone_Project/student/take_activity.php?id=' . $activity_id;
        while ($student = $students_result->fetch_assoc()) {
            sendPushNotification(
                $student['student_id'],
                'New Activity Available',
                $notif_message,
                $activity_url,
                $activity_id
            );
        }

        header('Location: activities.php?success=created');
        exit();
    } else {
        $error_message = "Failed to create activity!";
    }

    $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>Create Activity - 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">My Subjects</a>
                <a href="students.php" class="nav-link">My Students</a>
                <a href="activities.php" class="nav-link active">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">
            <h1>📝 Create New Activity</h1>
            <p>Create a programming activity for your students</p>
        </div>

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

        <div class="dashboard-section" style="max-width: 1000px; margin: 0 auto;">
            <form method="POST">
                <?php echo csrfField(); ?>
                <div class="form-group">
                    <label>Subject *</label>
                    <select name="subject_id" required>
                        <option value="">Select a subject</option>
                        <?php foreach ($subjects as $subject): ?>
                            <option value="<?php echo $subject['id']; ?>" <?php echo $selected_subject == $subject['id'] ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($subject['subject_name']) . ' (' . $subject['subject_code'] . ')'; ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="form-group">
                    <label>Activity Title *</label>
                    <input type="text" name="title" required placeholder="e.g., Hello World Program">
                </div>

                <div class="form-group">
                    <label>Description *</label>
                    <textarea name="description" required rows="5" placeholder="Describe the task students need to complete..."></textarea>
                </div>

                <div class="form-group">
                    <label>Starter Code (Optional)</label>
                    <textarea name="starter_code" rows="10" class="code-editor" placeholder="Provide starter code for students..."></textarea>
                </div>

                <div class="form-group">
                    <label>Expected Output (Optional)</label>
                    <textarea name="expected_output" rows="5" class="code-editor" placeholder="What output should students' programs produce?"></textarea>
                </div>

                <!-- Activity Settings Card -->
                <div class="activity-settings-card">
                    <h3 style="margin: 0 0 20px 0; color: var(--primary-moss); font-size: 1.1em; display: flex; align-items: center; gap: 8px;">
                        <span>⚙️</span> Activity Settings
                    </h3>

                    <div class="settings-grid">
                        <div class="setting-item">
                            <label class="setting-label">
                                <span class="label-icon">📅</span>
                                <span>Due Date</span>
                                <span class="required-badge">*</span>
                            </label>
                            <input type="datetime-local" name="due_date" required class="setting-input">
                            <small class="setting-hint">Deadline for student submissions</small>
                        </div>

                        <div class="setting-item">
                            <label class="setting-label">
                                <span class="label-icon">🎯</span>
                                <span>Passing Grade</span>
                                <span class="required-badge">*</span>
                            </label>
                            <div class="grade-input-wrapper">
                                <input type="number" name="passing_grade" min="0" max="100" step="0.01" value="75.00" required class="setting-input grade-input">
                                <span class="grade-suffix">%</span>
                            </div>
                            <small class="setting-hint">Minimum score required to pass</small>
                        </div>

                        <div class="setting-item">
                            <label class="setting-label">
                                <span class="label-icon">⏱️</span>
                                <span>Time Limit</span>
                            </label>
                            <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 8px;">
                                <label style="display: flex; align-items: center; gap: 8px; cursor: pointer;">
                                    <input type="checkbox" name="enable_time_limit" id="enable_time_limit" value="1" onchange="toggleTimeLimit()" style="width: 18px; height: 18px; cursor: pointer;">
                                    <span style="font-weight: 500;">Enable time limit for this activity</span>
                                </label>
                            </div>
                            <div id="time_limit_input" style="display: none;">
                                <div class="grade-input-wrapper">
                                    <input type="number" name="time_limit" id="time_limit" min="1" max="999" value="60" class="setting-input grade-input">
                                    <span class="grade-suffix">minutes</span>
                                </div>
                            </div>
                            <small class="setting-hint">Students must complete within time limit (activity will auto-submit)</small>
                        </div>
                    </div>
                </div>

                <div style="display: flex; gap: 10px; margin-top: 20px;">
                    <button type="submit" class="btn btn-success">Create Activity</button>
                    <a href="activities.php" class="btn btn-secondary">Cancel</a>
                </div>
            </form>
        </div>
    </div>

    <style>
        .activity-settings-card {
            background: linear-gradient(135deg, rgba(102, 126, 234, 0.05) 0%, rgba(118, 75, 162, 0.05) 100%);
            border: 2px solid rgba(102, 126, 234, 0.2);
            border-radius: 12px;
            padding: 25px;
            margin-top: 20px;
        }

        .settings-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
        }

        .setting-item {
            display: flex;
            flex-direction: column;
            gap: 8px;
        }

        .setting-label {
            display: flex;
            align-items: center;
            gap: 8px;
            font-weight: 600;
            color: var(--text-primary);
            font-size: 1em;
        }

        .label-icon {
            font-size: 1.2em;
        }

        .required-badge {
            color: #dc3545;
            font-weight: bold;
            font-size: 1.1em;
        }

        .setting-input {
            padding: 12px 15px;
            border: 2px solid rgba(102, 126, 234, 0.3);
            border-radius: 8px;
            font-size: 1em;
            background: var(--card-bg);
            color: var(--text-primary);
            transition: all 0.3s ease;
        }

        .setting-input:focus {
            outline: none;
            border-color: var(--primary-moss);
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .grade-input-wrapper {
            position: relative;
            display: flex;
            align-items: center;
        }

        .grade-input {
            padding-right: 45px;
        }

        .grade-suffix {
            position: absolute;
            right: 15px;
            font-weight: 600;
            color: var(--primary-moss);
            font-size: 1.1em;
            pointer-events: none;
        }

        .setting-hint {
            color: #666;
            font-size: 0.85em;
            font-style: italic;
            margin-top: 4px;
        }

        /* Dark mode support */
        @media (prefers-color-scheme: dark) {
            .activity-settings-card {
                background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%);
                border-color: rgba(102, 126, 234, 0.3);
            }
        }
    </style>

    <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;

                        // Mark notifications as read
                        fetch('mark_notifications_read.php');
                    }
                })
                .catch(error => {
                    content.innerHTML = '<p class="error-message">Failed to load notifications.</p>';
                });
        }

        // Close notifications panel when clicking outside
        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');
            }
        });

        // Toggle time limit input visibility
        function toggleTimeLimit() {
            const checkbox = document.getElementById('enable_time_limit');
            const timeInput = document.getElementById('time_limit_input');
            const timeLimitField = document.getElementById('time_limit');

            if (checkbox.checked) {
                timeInput.style.display = 'block';
                timeLimitField.required = true;
            } else {
                timeInput.style.display = 'none';
                timeLimitField.required = false;
            }
        }
    </script>
</body>
</html>
