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

if (!$activity_id) {
    header('Location: activities.php');
    exit();
}

$conn = getDBConnection();

// Add passing_grade column if it doesn't exist
$conn->query("ALTER TABLE activities ADD COLUMN IF NOT EXISTS passing_grade DECIMAL(5,2) DEFAULT 75.00");

// 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 activity details
$activity_query = "SELECT a.*, s.subject_name FROM activities a
                   JOIN subjects s ON a.subject_id = s.id
                   WHERE a.id = ? AND a.created_by = ?";
$stmt = $conn->prepare($activity_query);
$stmt->bind_param("ii", $activity_id, $instructor_id);
$stmt->execute();
$activity_result = $stmt->get_result();

if ($activity_result->num_rows == 0) {
    header('Location: activities.php');
    exit();
}

$activity = $activity_result->fetch_assoc();
$stmt->close();

// Handle update
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $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;

    $update_query = "UPDATE activities SET title = ?, description = ?, starter_code = ?, expected_output = ?, due_date = ?, passing_grade = ? WHERE id = ? AND created_by = ?";
    $stmt = $conn->prepare($update_query);
    $stmt->bind_param("sssssdii", $title, $description, $starter_code, $expected_output, $due_date, $passing_grade, $activity_id, $instructor_id);

    if ($stmt->execute()) {
        header('Location: activities.php?success=updated');
        exit();
    } else {
        $error_message = "Failed to update 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>Edit 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/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>📝 Edit Activity</h1>
            <p>Update activity information</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">
                <div class="form-group">
                    <label>Subject</label>
                    <input type="text" value="<?php echo htmlspecialchars($activity['subject_name']); ?>" disabled style="background: #f0f0f0;">
                </div>

                <div class="form-group">
                    <label>Activity Title *</label>
                    <input type="text" name="title" value="<?php echo htmlspecialchars($activity['title']); ?>" required>
                </div>

                <div class="form-group">
                    <label>Description *</label>
                    <textarea name="description" required rows="5"><?php echo htmlspecialchars($activity['description']); ?></textarea>
                </div>

                <div class="form-group">
                    <label>Starter Code (Optional)</label>
                    <textarea name="starter_code" rows="10" class="code-editor"><?php echo htmlspecialchars($activity['starter_code']); ?></textarea>
                </div>

                <div class="form-group">
                    <label>Expected Output (Optional)</label>
                    <textarea name="expected_output" rows="5" class="code-editor"><?php echo htmlspecialchars($activity['expected_output']); ?></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" value="<?php echo date('Y-m-d\TH:i', strtotime($activity['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="<?php echo isset($activity['passing_grade']) ? $activity['passing_grade'] : '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>
                </div>

                <div style="display: flex; gap: 10px; margin-top: 20px;">
                    <button type="submit" class="btn btn-success">Save Changes</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');
            }
        });
    </script>
</body>
</html>
