<?php
session_start();
date_default_timezone_set('Asia/Manila'); // Set to your timezone
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'];
$activity_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if (!$activity_id) {
    header('Location: activities.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", $student_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, s.subject_code
                   FROM activities a
                   JOIN subjects s ON a.subject_id = s.id
                   WHERE a.id = ?";
$stmt = $conn->prepare($activity_query);
$stmt->bind_param("i", $activity_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();

// Track activity start time for time-limited activities
$start_timestamp = null;
$activity_started = false;
if ($activity['time_limit']) {
    // Check if student has already started this activity
    $attempt_query = "SELECT start_time FROM activity_attempts WHERE student_id = ? AND activity_id = ?";
    $stmt = $conn->prepare($attempt_query);
    $stmt->bind_param("ii", $student_id, $activity_id);
    $stmt->execute();
    $attempt_result = $stmt->get_result();

    if ($attempt_result->num_rows > 0) {
        // Activity already started - get existing start time
        $attempt = $attempt_result->fetch_assoc();

        // Convert MySQL TIMESTAMP to Unix timestamp
        // MySQL TIMESTAMP is stored in UTC, so we need to handle it properly
        $start_datetime = new DateTime($attempt['start_time'], new DateTimeZone('UTC'));
        $start_timestamp = $start_datetime->getTimestamp();
        $activity_started = true;

        // Debug: Log the values
        error_log("Start time from DB: " . $attempt['start_time']);
        error_log("Start timestamp: " . $start_timestamp);
        error_log("Current time: " . time());
        error_log("Elapsed: " . (time() - $start_timestamp));
        error_log("Time limit: " . $activity['time_limit'] . " minutes");

        // Additional debug: Calculate remaining time
        if ($activity['time_limit']) {
            $elapsed = time() - $start_timestamp;
            $remaining = ($activity['time_limit'] * 60) - $elapsed;
            error_log("Remaining seconds: " . $remaining);
        }
    }
    $stmt->close();
}

// Check if student is enrolled in this subject
$enrollment_query = "SELECT * FROM enrollments WHERE student_id = ? AND subject_id = ?";
$stmt = $conn->prepare($enrollment_query);
$stmt->bind_param("ii", $student_id, $activity['subject_id']);
$stmt->execute();
$enrollment_result = $stmt->get_result();

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

// Get previous submission if exists
$submission_query = "SELECT * FROM submissions WHERE activity_id = ? AND student_id = ? ORDER BY submitted_at DESC LIMIT 1";
$stmt = $conn->prepare($submission_query);
$stmt->bind_param("ii", $activity_id, $student_id);
$stmt->execute();
$submission_result = $stmt->get_result();
$previous_submission = $submission_result->fetch_assoc();
$stmt->close();

// Check if submission is locked (already submitted or auto-submitted)
$is_locked = false;
$lock_reason = '';
if ($previous_submission) {
    // Check if violation tracking columns exist
    $check_columns = $conn->query("SHOW COLUMNS FROM submissions LIKE 'is_auto_submitted'");
    $has_auto_submit_column = $check_columns->num_rows > 0;

    // Always lock if there's a submission
    $is_locked = true;

    if ($has_auto_submit_column && $previous_submission['is_auto_submitted'] == 1) {
        $lock_reason = 'auto_submitted';
    } else {
        $lock_reason = 'submitted';
    }
}

// Handle submission
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['submit_code'])) {
    // CSRF Protection
    requireCSRFToken();

    // Block submission if locked
    if ($is_locked) {
        $error_message = "This activity has been locked. You cannot resubmit.";
    } else {
        $code = $_POST['code'];
        $output = $_POST['output'] ?? '';
        $violation_count = isset($_POST['violation_count']) ? intval($_POST['violation_count']) : 0;
        $is_auto_submitted = isset($_POST['is_auto_submitted']) ? 1 : 0;

        // Check if violation tracking columns exist
        $check_columns = $conn->query("SHOW COLUMNS FROM submissions LIKE 'violation_count'");
        $has_violation_columns = $check_columns->num_rows > 0;

        if ($previous_submission) {
            // Update existing submission
            if ($has_violation_columns) {
                $update_query = "UPDATE submissions SET code = ?, output = ?, violation_count = ?, is_auto_submitted = ?, submitted_at = CURRENT_TIMESTAMP WHERE activity_id = ? AND student_id = ?";
                $stmt = $conn->prepare($update_query);
                $stmt->bind_param("ssiiii", $code, $output, $violation_count, $is_auto_submitted, $activity_id, $student_id);
            } else {
                $update_query = "UPDATE submissions SET code = ?, output = ?, submitted_at = CURRENT_TIMESTAMP WHERE activity_id = ? AND student_id = ?";
                $stmt = $conn->prepare($update_query);
                $stmt->bind_param("ssii", $code, $output, $activity_id, $student_id);
            }
            $stmt->execute();
            $stmt->close();

            // Lock after submission
            $is_locked = true;
        } else {
            // Create new submission
            if ($has_violation_columns) {
                $insert_query = "INSERT INTO submissions (activity_id, student_id, code, output, violation_count, is_auto_submitted) VALUES (?, ?, ?, ?, ?, ?)";
                $stmt = $conn->prepare($insert_query);
                $stmt->bind_param("iissii", $activity_id, $student_id, $code, $output, $violation_count, $is_auto_submitted);
            } else {
                $insert_query = "INSERT INTO submissions (activity_id, student_id, code, output) VALUES (?, ?, ?, ?)";
                $stmt = $conn->prepare($insert_query);
                $stmt->bind_param("iiss", $activity_id, $student_id, $code, $output);
            }
            $stmt->execute();
            $stmt->close();

            // Create notification for instructor
            $notif_message = $_SESSION['full_name'] . " submitted a solution for '" . $activity['title'] . "'";
            $notif_query = "INSERT INTO notifications (user_id, message, activity_id, is_read)
                            SELECT created_by, ?, ?, FALSE FROM activities WHERE id = ?";
            $stmt = $conn->prepare($notif_query);
            $stmt->bind_param("sii", $notif_message, $activity_id, $activity_id);
            $stmt->execute();
            $stmt->close();

            // Lock after submission
            $is_locked = true;
        }

        $success_message = "Your code has been submitted successfully! This activity is now locked.";

        // Refresh submission data
        $stmt = $conn->prepare($submission_query);
        $stmt->bind_param("ii", $activity_id, $student_id);
        $stmt->execute();
        $submission_result = $stmt->get_result();
        $previous_submission = $submission_result->fetch_assoc();
        $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();

$is_overdue = strtotime($activity['due_date']) < time();
?>
<!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($activity['title']); ?> - CODELAB</title>
    <link rel="stylesheet" href="../assets/css/style.css">
    <script src="../assets/js/dark-mode.js" defer></script>
    <script src="../assets/js/interactive-pet.js" defer></script>
    <script src="../assets/js/push-notifications.js" defer></script>
    <style>
        .modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.85);
            z-index: 999999;
            overflow-y: auto;
            display: flex !important;
            align-items: center;
            justify-content: center;
            padding: 10px;
        }

        .modal-content {
            background: white;
            padding: 20px;
            border-radius: 10px;
            max-width: 500px;
            width: 100%;
            position: relative;
            z-index: 1000000;
            margin: auto;
        }

        .modal-content button {
            pointer-events: all !important;
            cursor: pointer !important;
        }

        @media (max-width: 768px) {
            .modal-content {
                padding: 15px;
                max-width: 95%;
            }
        }

        @keyframes modalFadeIn {
            from {
                opacity: 0;
                transform: translateY(-20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        body.dark-mode .modal-content {
            background: #1e1e1e;
            color: #e0e0e0;
        }

        body.dark-mode .modal-content h2 {
            color: #667eea;
        }

        body.dark-mode .modal-content ul li {
            color: #c0c0c0;
        }
    </style>
</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 active">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>

    <!-- Time Limit Warning Modal -->
    <?php if ($activity['time_limit'] && !$activity_started): ?>
    <div id="time-limit-warning-modal" class="modal-overlay" style="display: flex;">
        <div class="modal-content" style="color:#333">
            <h2 style="color:#667eea;text-align:center;margin-top:0">⏱️ Timed Activity</h2>

            <div style="background:#fff3cd;border-left:4px solid #ffc107;padding:10px;border-radius:5px;margin:15px 0;color:#856404">
                <strong>⚠️ Time Limit:</strong> <?php echo $activity['time_limit']; ?> minutes
            </div>

            <div style="margin-bottom:12px">
                <p style="margin:5px 0;font-weight:bold;color:#333">📋 Rules:</p>
                <ul style="line-height:1.6;color:#333;margin:5px 0">
                    <li>Timer starts when you click "Start"</li>
                    <li>Auto-submits when time is up</li>
                    <li>Timer continues if you leave page</li>
                    <li>Warnings at 5 min & 1 min left</li>
                </ul>
            </div>

            <div style="background:#ffebee;border:3px solid #d32f2f;padding:15px;border-radius:5px;margin:15px 0">
                <p style="margin:0 0 10px 0;font-weight:bold;color:#d32f2f !important;font-size:16px">🚫 DO NOT (3 violations = Auto-Submit):</p>
                <ul style="line-height:1.8;color:#000 !important;margin:5px 0;padding-left:20px;font-size:15px;font-weight:600">
                    <li style="color:#000 !important;margin-bottom:5px">Switch to another tab or window</li>
                    <li style="color:#000 !important;margin-bottom:5px">Minimize or leave this page</li>
                    <li style="color:#000 !important;margin-bottom:5px">Open Developer Tools (F12, Right-click)</li>
                    <li style="color:#000 !important;margin-bottom:5px">Press Ctrl+Shift+I, Ctrl+U, or inspect</li>
                </ul>
            </div>

            <p style="text-align:center;font-weight:bold;margin:15px 0;color:#333">Ready to begin?</p>

            <button type="button" id="start-activity-btn" class="btn btn-success" style="width:100%;padding:15px;font-size:18px;margin-bottom:10px;cursor:pointer;border:none" onclick="startTimedActivity()">
                ✓ Start Now
            </button>
            <a href="activities.php" class="btn btn-secondary" style="width:100%;padding:12px;text-align:center;display:block;text-decoration:none">
                ← Go Back
            </a>
        </div>
    </div>

    <script>
    function startTimedActivity() {
        var btn = document.getElementById('start-activity-btn');
        btn.disabled = true;
        btn.innerHTML = '⏳ Starting...';
        btn.style.opacity = '0.5';

        var formData = new FormData();
        formData.append('activity_id', '<?php echo $activity_id; ?>');

        fetch('start_activity.php', {
            method: 'POST',
            body: formData
        })
        .then(function(response) {
            return response.json();
        })
        .then(function(data) {
            if (data.success) {
                document.getElementById('time-limit-warning-modal').style.display = 'none';
                window.location.reload();
            } else {
                alert('Error: ' + (data.message || 'Failed to start'));
                btn.disabled = false;
                btn.innerHTML = '✓ Start Now';
                btn.style.opacity = '1';
            }
        })
        .catch(function(error) {
            alert('Error: ' + error.message);
            btn.disabled = false;
            btn.innerHTML = '✓ Start Now';
            btn.style.opacity = '1';
        });
    }
    </script>
    <?php endif; ?>

    <div class="main-content">
        <?php if (isset($error_message)): ?>
            <div class="alert alert-error" style="background: #fee; border-left: 4px solid #dc3545; color: #dc3545;">
                <?php echo $error_message; ?>
            </div>
        <?php endif; ?>

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

        <?php if ($is_locked): ?>
            <div class="alert alert-error" style="background: <?php echo $lock_reason == 'auto_submitted' ? '#fee' : '#fff3cd'; ?>; border-left: 4px solid <?php echo $lock_reason == 'auto_submitted' ? '#dc3545' : '#ffc107'; ?>; color: <?php echo $lock_reason == 'auto_submitted' ? '#dc3545' : '#856404'; ?>;">
                <?php if ($lock_reason == 'auto_submitted'): ?>
                    🚫 <strong>Activity Auto-Submitted Due to Violations:</strong> This activity was automatically submitted because you violated the anti-cheat policy (<?php echo isset($previous_submission['violation_count']) ? $previous_submission['violation_count'] : 0; ?> violations detected). You cannot retake this activity.
                    <br><br>
                    <strong>Violations included:</strong> Tab switching, window minimizing, or attempting to leave the activity page.
                <?php else: ?>
                    🔒 <strong>Activity Locked:</strong> This activity has been submitted and is now locked. You cannot make changes or resubmit.
                <?php endif; ?>
            </div>
        <?php endif; ?>

        <!-- Activity Details -->
        <div class="activity-details">
            <a href="activities.php" style="color: #667eea; text-decoration: none; margin-bottom: 10px; display: inline-block;">← Back to Activities</a>
            <h2><?php echo htmlspecialchars($activity['title']); ?></h2>

            <?php if ($activity['time_limit']): ?>
            <div class="timer-container" style="background: linear-gradient(135deg, <?php echo $is_locked ? '#6c757d 0%, #495057 100%' : '#667eea 0%, #764ba2 100%'; ?>); color: white; padding: 15px; border-radius: 10px; text-align: center; margin: 20px 0; box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);">
                <div style="font-size: 14px; opacity: 0.9; margin-bottom: 5px;">⏱️ Time Limit: <?php echo $activity['time_limit']; ?> minutes</div>
                <div id="timer-display" style="font-size: 36px; font-weight: bold; font-family: 'Courier New', monospace;">
                    <?php
                    if ($is_locked) {
                        echo 'SUBMITTED';
                    } elseif ($start_timestamp) {
                        $elapsed = time() - $start_timestamp;
                        $remaining = ($activity['time_limit'] * 60) - $elapsed;
                        if ($remaining <= 0) {
                            echo '00:00';
                        } else {
                            echo '--:--';
                        }
                    } else {
                        echo '--:--';
                    }
                    ?>
                </div>
                <div style="font-size: 12px; opacity: 0.8; margin-top: 5px;">
                    <?php echo $is_locked ? 'Activity has been submitted' : 'Activity will auto-submit when timer reaches 0:00'; ?>
                </div>
            </div>
            <?php endif; ?>

            <div class="activity-meta">
                <span class="subject-tag"><?php echo htmlspecialchars($activity['subject_name']); ?></span>
                <div class="meta-item">
                    📅 <strong>Due:</strong> <?php echo date('M d, Y H:i', strtotime($activity['due_date'])); ?>
                </div>
                <?php if ($is_overdue && !$previous_submission): ?>
                    <div class="meta-item" style="color: #dc3545;">
                        ⚠️ <strong>Overdue</strong>
                    </div>
                <?php endif; ?>
                <?php if ($previous_submission): ?>
                    <div class="meta-item" style="color: #28a745;">
                        ✓ <strong>Submitted:</strong> <?php echo date('M d, Y H:i', strtotime($previous_submission['submitted_at'])); ?>
                    </div>
                    <?php if ($previous_submission['status'] == 'graded'): ?>
                        <div class="meta-item" style="color: #667eea;">
                            🏆 <strong>Score:</strong> <?php echo number_format($previous_submission['score'], 2); ?>%
                        </div>
                    <?php else: ?>
                        <div class="meta-item" style="color: #ffc107;">
                            ⏳ <strong>Status:</strong> Pending Review
                        </div>
                    <?php endif; ?>
                <?php endif; ?>
            </div>
            <div class="activity-description">
                <h3>📋 Description:</h3>
                <p><?php echo nl2br(htmlspecialchars($activity['description'])); ?></p>
            </div>
            <?php if ($activity['expected_output']): ?>
                <div class="activity-description">
                    <h3>🎯 Expected Output:</h3>
                    <div class="output-container">
                        <pre><?php echo htmlspecialchars($activity['expected_output']); ?></pre>
                    </div>
                </div>
            <?php endif; ?>
            <?php if ($previous_submission && $previous_submission['feedback']): ?>
                <div class="activity-description">
                    <h3>💬 Instructor Feedback:</h3>
                    <div style="background: #f8f9ff; padding: 15px; border-radius: 8px; border-left: 4px solid #667eea;">
                        <p><?php echo nl2br(htmlspecialchars($previous_submission['feedback'])); ?></p>
                    </div>
                </div>
            <?php endif; ?>
        </div>

        <!-- Code Editor -->
        <form method="POST" id="submit-form">
            <?php echo csrfField(); ?>
            <input type="hidden" name="violation_count" id="violation-count-field" value="0">
            <input type="hidden" name="is_auto_submitted" id="is-auto-submitted-field" value="0">
            <div class="code-editor-container">
                <h3>💻 Your Code:</h3>
                <div class="code-editor-wrapper">
                    <div class="line-nums" id="lineNums">1</div>
                    <textarea name="code" id="code-editor" class="code-editor" placeholder="Write your C/C++ code here..." spellcheck="false" <?php echo $is_locked ? 'readonly disabled style="background: #f5f5f5; cursor: not-allowed;"' : ''; ?>><?php
                        if ($previous_submission) {
                            echo htmlspecialchars($previous_submission['code']);
                        } elseif ($activity['starter_code']) {
                            echo htmlspecialchars($activity['starter_code']);
                        }
                    ?></textarea>
                </div>

                <!-- Input Box for cin/scanf -->
                <div style="margin-top: 15px;">
                    <label for="program-input" style="display: block; margin-bottom: 5px; font-weight: bold;">
                        ⌨️ Program Input (for cin/scanf):
                    </label>

                    <!-- Detected Prompts -->
                    <div id="detected-prompts" class="detected-prompts-box" style="display: none;">
                        <strong style="color: var(--primary-hunter);">📋 Your program needs these inputs:</strong>
                        <div id="prompts-list" style="margin-top: 8px; font-family: 'Courier New', monospace; font-size: 0.9em;"></div>
                    </div>

                    <!-- Input Container with Line Numbers and Hints -->
                    <div class="input-container">
                        <div class="input-line-nums" id="input-line-nums">1</div>
                        <div style="position: relative; flex: 1;">
                            <div id="input-hints" class="input-hints"></div>
                            <textarea id="program-input" class="input-editor" <?php echo $is_locked ? 'readonly disabled style="background: #f5f5f5; cursor: not-allowed;"' : ''; ?>></textarea>
                        </div>
                    </div>
                </div>

                <input type="hidden" name="output" id="output-field">
                <div style="display: flex; gap: 10px; margin-top: 15px; flex-wrap: wrap;">
                    <?php if (!$is_locked): ?>
                        <button type="button" onclick="runCode('c')" class="btn btn-secondary">▶️ Run as C</button>
                        <button type="button" onclick="runCode('cpp')" class="btn btn-secondary">▶️ Run as C++</button>
                        <button type="submit" name="submit_code" class="btn btn-success">✓ Submit Solution</button>
                    <?php else: ?>
                        <button type="button" class="btn btn-secondary" disabled style="cursor: not-allowed; opacity: 0.5;">🔒 Activity Locked</button>
                        <a href="activities.php" class="btn btn-primary">← Back to Activities</a>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Output Container -->
            <div class="code-editor-container">
                <h3>📤 Program Output:</h3>
                <div class="output-container interactive-terminal" id="output-container">
                    <pre id="terminal-output">Run your code to see the output here...</pre>
                    <div id="input-line" style="display: none;">
                        <span id="prompt-text"></span>
                        <input type="text" id="terminal-input" style="background: transparent; border: none; color: inherit; font-family: 'Courier New', monospace; outline: none; width: 300px;">
                    </div>
                </div>
            </div>
        </form>
    </div>

    <script>
        // Anti-Cheat System
        const isActivityLocked = <?php echo $is_locked ? 'true' : 'false'; ?>;
        const activityStarted = <?php echo ($activity_started && $start_timestamp) ? 'true' : 'false'; ?>;
        let antiCheatEnabled = false; // Start disabled
        let violationCount = 0;
        const MAX_VIOLATIONS = 2; // Allow 2 warnings before action
        let warningTimeout = null;
        let isSubmitting = false;
        let lastViolationTime = 0; // Track last violation to prevent duplicates

        // Enable anti-cheat after 3 seconds if activity is started
        if (activityStarted && !isActivityLocked) {
            setTimeout(function() {
                antiCheatEnabled = true;
                console.log('Anti-cheat protection activated');
            }, 3000); // 3 second grace period
        }

        // Add violation with debounce to prevent duplicate counting
        function addViolation(message) {
            const now = Date.now();
            // If last violation was less than 100ms ago, skip (it's a duplicate)
            if (now - lastViolationTime < 100) {
                console.log('Duplicate violation skipped');
                return;
            }

            lastViolationTime = now;
            violationCount++;
            console.log('Violation detected:', message, 'Count:', violationCount);

            if (violationCount <= MAX_VIOLATIONS) {
                showWarning(message);
            } else {
                autoSubmitCode();
            }
        }

        // Show warning modal
        function showWarning(message) {
            // Clear any existing timeout
            if (warningTimeout) {
                clearTimeout(warningTimeout);
            }

            // Create or update warning modal
            let modal = document.getElementById('anti-cheat-modal');
            if (!modal) {
                modal = document.createElement('div');
                modal.id = 'anti-cheat-modal';
                modal.style.cssText = 'position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.95); z-index: 999999; display: flex; align-items: center; justify-content: center;';
                document.body.appendChild(modal);
            }

            modal.innerHTML = `
                <div style="background: white; padding: 30px; border-radius: 10px; max-width: 400px; width: 90%; text-align: center; box-shadow: 0 4px 20px rgba(0,0,0,0.3); color: #333;">
                    <h2 style="color: #dc3545; margin-bottom: 15px;">⚠️ Warning!</h2>
                    <p style="font-size: 16px; margin-bottom: 10px; color: #333;">${message}</p>
                    <p style="color: #666; margin-bottom: 15px; font-weight: bold;">Violations: ${violationCount}/${MAX_VIOLATIONS}</p>
                    <p style="color: #dc3545; font-weight: bold; margin-bottom: 20px;">Stay focused on the activity!</p>
                    <button onclick="closeWarning()" style="background: #dc3545; color: white; border: none; padding: 12px 30px; border-radius: 5px; font-size: 16px; cursor: pointer; font-weight: bold;">
                        Okay, I Understand
                    </button>
                </div>
            `;
            modal.style.display = 'flex';
        }

        // Close warning modal
        function closeWarning() {
            const modal = document.getElementById('anti-cheat-modal');
            if (modal) {
                modal.style.display = 'none';
            }
        }

        // Auto-submit code
        function autoSubmitCode() {
            if (isSubmitting) return;
            isSubmitting = true;

            // Disable anti-cheat before auto-submit to prevent false violations
            antiCheatEnabled = false;

            const code = document.getElementById('code-editor').value;
            const output = document.getElementById('output-field').value;
            const csrfToken = document.querySelector('input[name="csrf_token"]').value;

            const formData = new FormData();
            formData.append('csrf_token', csrfToken);
            formData.append('submit_code', '1');
            formData.append('code', code);
            formData.append('output', output);
            formData.append('violation_count', violationCount);
            formData.append('is_auto_submitted', '1');

            fetch(window.location.href, {
                method: 'POST',
                body: formData
            })
            .then(response => response.text())
            .then(() => {
                alert('⚠️ Your code has been auto-submitted due to multiple violations!');
                window.location.href = 'activities.php';
            })
            .catch(error => {
                console.error('Auto-submit failed:', error);
                isSubmitting = false;
            });
        }

        // Reset code editor
        function resetCode() {
            const codeEditor = document.getElementById('code-editor');
            const starterCode = `<?php echo $activity['starter_code'] ? addslashes($activity['starter_code']) : ''; ?>`;

            if (confirm('⚠️ Your code will be reset due to multiple violations. Continue?')) {
                codeEditor.value = starterCode;
                document.getElementById('program-input').value = '';
                document.getElementById('output-container').innerHTML = '<pre id="terminal-output">Run your code to see the output here...</pre>';
                document.getElementById('output-field').value = '';

                alert('⚠️ Your code has been reset! Please stay focused on the activity.');
                violationCount = 0; // Reset violations after penalty
            }
        }

        // Handle visibility change (tab switch, minimize, leaving page)
        document.addEventListener('visibilitychange', function() {
            // Skip anti-cheat if not enabled yet, locked, or not started
            if (!antiCheatEnabled || isActivityLocked || !activityStarted) return;

            if (document.hidden) {
                addViolation('You switched tabs or left the page!');
            }
        });


        // Update violation count field when form is submitted normally
        document.getElementById('submit-form').addEventListener('submit', function() {
            // Disable anti-cheat when submitting to prevent false violations
            antiCheatEnabled = false;
            document.getElementById('violation-count-field').value = violationCount;
        });

        // NOTE: Anti-cheat temporarily disabled for testing purposes
        // Prevent right-click (inspect element)
        /*
        document.addEventListener('contextmenu', function(e) {
            if (!antiCheatEnabled || isActivityLocked || !activityStarted) return;
            e.preventDefault();
            addViolation('Right-click is disabled during the activity!');
            return false;
        });

        // Block F12 and DevTools shortcuts
        document.addEventListener('keydown', function(e) {
            if (!antiCheatEnabled || isActivityLocked || !activityStarted) return;

            // Block F12
            if (e.key === 'F12') {
                e.preventDefault();
                addViolation('Developer tools are not allowed!');
                return false;
            }

            // Block Ctrl+Shift+I (Inspect)
            if ((e.ctrlKey || e.metaKey) && e.shiftKey && (e.key === 'I' || e.key === 'i')) {
                e.preventDefault();
                addViolation('Developer tools are not allowed!');
                return false;
            }

            // Block Ctrl+Shift+J (Console)
            if ((e.ctrlKey || e.metaKey) && e.shiftKey && (e.key === 'J' || e.key === 'j')) {
                e.preventDefault();
                addViolation('Developer tools are not allowed!');
                return false;
            }

            // Block Ctrl+Shift+C (Inspect Element)
            if ((e.ctrlKey || e.metaKey) && e.shiftKey && (e.key === 'C' || e.key === 'c')) {
                e.preventDefault();
                addViolation('Developer tools are not allowed!');
                return false;
            }

            // Block Ctrl+U (View Source)
            if ((e.ctrlKey || e.metaKey) && (e.key === 'U' || e.key === 'u')) {
                e.preventDefault();
                addViolation('Viewing page source is not allowed!');
                return false;
            }
        });
        */

        // Time Limit Timer
        <?php if ($activity['time_limit'] && !$is_locked && $start_timestamp): ?>
        (function() {
            let timeLimit = <?php echo $activity['time_limit'] * 60; ?>; // Convert to seconds
            let startTime = <?php echo $start_timestamp; ?>; // Unix timestamp when started

            console.log('Time Limit:', <?php echo $activity['time_limit']; ?>, 'minutes');
            console.log('Time Limit in seconds:', timeLimit);
            console.log('Start Time:', startTime);

            let currentTime = Math.floor(Date.now() / 1000);
            console.log('Current Time:', currentTime);

            let elapsed = currentTime - startTime;
            console.log('Elapsed seconds:', elapsed);

            let remainingSeconds = timeLimit - elapsed;
            console.log('Remaining seconds:', remainingSeconds);

            // Auto-submit if time already expired
            if (remainingSeconds <= 0) {
                autoSubmitActivity();
                return;
            }

            // Update timer display initially
            updateTimerDisplay();

            // Countdown timer
            let timerInterval = setInterval(function() {
                remainingSeconds--;

                if (remainingSeconds <= 0) {
                    clearInterval(timerInterval);
                    autoSubmitActivity();
                    return;
                }

                updateTimerDisplay();

                // Warning when 5 minutes left
                if (remainingSeconds === 300) {
                    antiCheatEnabled = false; // Disable temporarily
                    alert('⏰ Warning: 5 minutes remaining!');
                    setTimeout(function() { antiCheatEnabled = true; }, 1000); // Re-enable after 1 second
                }

                // Warning when 1 minute left
                if (remainingSeconds === 60) {
                    antiCheatEnabled = false; // Disable temporarily
                    alert('⏰ Warning: 1 minute remaining!');
                    setTimeout(function() { antiCheatEnabled = true; }, 1000); // Re-enable after 1 second
                }

                // Change color when under 5 minutes
                if (remainingSeconds < 300) {
                    document.getElementById('timer-display').style.color = '#ff6b6b';
                }
            }, 1000);

            function updateTimerDisplay() {
                let minutes = Math.floor(remainingSeconds / 60);
                let seconds = remainingSeconds % 60;

                document.getElementById('timer-display').textContent =
                    String(minutes).padStart(2, '0') + ':' + String(seconds).padStart(2, '0');
            }

            function autoSubmitActivity() {
                if (isSubmitting) return;
                isSubmitting = true;

                // Disable anti-cheat before auto-submit to prevent false violations
                antiCheatEnabled = false;

                const code = document.getElementById('code-editor').value;
                const output = document.getElementById('output-field').value;
                const csrfToken = document.querySelector('input[name="csrf_token"]').value;

                const formData = new FormData();
                formData.append('csrf_token', csrfToken);
                formData.append('submit_code', '1');
                formData.append('code', code);
                formData.append('output', output);
                formData.append('violation_count', violationCount);
                formData.append('is_auto_submitted', '1');

                fetch(window.location.href, {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.text())
                .then(() => {
                    alert('⏰ Time\'s up! Your activity will be submitted automatically.');
                    window.location.reload();
                })
                .catch(error => {
                    console.error('Auto-submit failed:', error);
                    alert('⏰ Time\'s up! Your activity will be submitted automatically.');
                    // Fallback: set the flag and submit the form
                    document.getElementById('is-auto-submitted-field').value = '1';
                    document.getElementById('violation-count-field').value = violationCount;
                    document.getElementById('submit-form').submit();
                });
            }
        })();
        <?php endif; ?>

        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>${notif.message}</p>
                                    <span class="notif-time">${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');
            }
        });

        function runCode(language) {
            const code = document.getElementById('code-editor').value;
            const programInput = document.getElementById('program-input').value;
            const outputContainer = document.getElementById('output-container');

            if (!code.trim()) {
                outputContainer.innerHTML = '<pre class="output-error">Error: No code to execute!</pre>';
                return;
            }

            // Show loading animation
            outputContainer.innerHTML = `<pre>⏳ Running...</pre>`;

            const startTime = Date.now();
            const formData = new FormData();
            formData.append('code', code);
            formData.append('language', language);
            formData.append('input', programInput);

            fetch('../api/execute_code_piston.php', {
                method: 'POST',
                body: formData,
                signal: AbortSignal.timeout(600000) // 10 minute timeout
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('HTTP error ' + response.status);
                }
                return response.json();
            })
            .then(data => {
                const executionTime = ((Date.now() - startTime) / 1000).toFixed(2);
                const outputClass = data.success ? 'output-success' : 'output-error';
                const timeInfo = `\n\n⏱️ Total time: ${executionTime}s`;
                outputContainer.innerHTML = `<pre class="${outputClass}">${escapeHtml(data.output)}${timeInfo}</pre>`;
                document.getElementById('output-field').value = data.output;
            })
            .catch(error => {
                const executionTime = ((Date.now() - startTime) / 1000).toFixed(2);
                outputContainer.innerHTML = `<pre class="output-error">Error: ${error.message}\nTime elapsed: ${executionTime}s\n\nPossible causes:\n- Windows Defender is scanning compiled files\n- Antivirus blocking execution\n- PHP timeout\n\nAdd temp folder to antivirus exclusions!</pre>`;
            });
        }

        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }

        // Detect input prompts from code
        function detectInputPrompts() {
            const code = document.getElementById('code-editor').value;
            const promptsContainer = document.getElementById('detected-prompts');
            const promptsList = document.getElementById('prompts-list');

            // Regex patterns to find cout/printf statements followed by cin/scanf
            const patterns = [
                // C++ cout patterns
                /cout\s*<<\s*"([^"]+)"\s*;[\s\S]*?cin\s*>>/g,
                /cout\s*<<\s*'([^']+)'\s*;[\s\S]*?cin\s*>>/g,
                // C printf patterns
                /printf\s*\(\s*"([^"]+)"\s*\)[\s\S]*?scanf/g
            ];

            let prompts = [];
            patterns.forEach(pattern => {
                let match;
                while ((match = pattern.exec(code)) !== null) {
                    // Extract the prompt text
                    let prompt = match[1].trim();
                    // Clean up escape sequences
                    prompt = prompt.replace(/\\n/g, '').replace(/\\t/g, ' ');
                    if (prompt && !prompts.includes(prompt)) {
                        prompts.push(prompt);
                    }
                }
            });

            if (prompts.length > 0) {
                let html = '<ol style="margin: 5px 0; padding-left: 20px;">';
                prompts.forEach(prompt => {
                    html += `<li>${escapeHtml(prompt)}</li>`;
                });
                html += '</ol>';
                html += `<small style="color: #6c757d;">💡 Enter ${prompts.length} value${prompts.length > 1 ? 's' : ''} (one per line)</small>`;
                promptsList.innerHTML = html;
                promptsContainer.style.display = 'block';
            } else {
                promptsContainer.style.display = 'none';
                prompts = []; // Clear prompts array
            }

            // Store prompts globally for hints
            window.detectedPrompts = prompts;
            updateInputHints();
        }

        // Update input hints to show prompts inline
        function updateInputHints() {
            const inputEditor = document.getElementById('program-input');
            const hintsContainer = document.getElementById('input-hints');
            const prompts = window.detectedPrompts || [];

            if (!inputEditor || !hintsContainer) return;

            const inputLines = inputEditor.value.split('\n');
            let hintsHTML = '';

            inputLines.forEach((line, index) => {
                if (index < prompts.length) {
                    // Show hint only if line is empty
                    if (line.trim() === '') {
                        hintsHTML += `<div class="input-hint-line">  // ${prompts[index]}</div>`;
                    } else {
                        hintsHTML += `<div class="input-hint-line"></div>`;
                    }
                } else {
                    hintsHTML += `<div class="input-hint-line"></div>`;
                }
            });

            hintsContainer.innerHTML = hintsHTML;
        }

        // Initialize code editor
        document.addEventListener('DOMContentLoaded', function() {
            const codeEditor = document.getElementById('code-editor');
            const lineNums = document.getElementById('lineNums');

            // Detect prompts on page load
            detectInputPrompts();

            // Update line numbers
            function updateLines() {
                const lines = codeEditor.value.split('\n');
                let numbers = '';
                for (let i = 1; i <= lines.length; i++) {
                    numbers += i + '\n';
                }
                lineNums.textContent = numbers;
            }

            // Sync scroll
            codeEditor.addEventListener('scroll', function() {
                lineNums.scrollTop = codeEditor.scrollTop;
            });

            // Update on input
            codeEditor.addEventListener('input', function() {
                updateLines();
                detectInputPrompts(); // Detect prompts in real-time
            });

            // Input editor line numbers
            const inputEditor = document.getElementById('program-input');
            const inputLineNums = document.getElementById('input-line-nums');

            function updateInputLines() {
                const lines = inputEditor.value.split('\n');
                let numbers = '';
                for (let i = 1; i <= lines.length; i++) {
                    numbers += i + '\n';
                }
                inputLineNums.textContent = numbers;
            }

            // Sync scroll for input
            inputEditor.addEventListener('scroll', function() {
                inputLineNums.scrollTop = inputEditor.scrollTop;
                const hintsContainer = document.getElementById('input-hints');
                if (hintsContainer) {
                    hintsContainer.scrollTop = inputEditor.scrollTop;
                }
            });

            // Update input line numbers and hints
            inputEditor.addEventListener('input', function() {
                updateInputLines();
                updateInputHints();
            });
            updateInputLines();
            updateInputHints();

            // Tab indentation
            codeEditor.addEventListener('keydown', function(e) {
                if (e.key === 'Tab') {
                    e.preventDefault();
                    const start = this.selectionStart;
                    const end = this.selectionEnd;
                    this.value = this.value.substring(0, start) + '    ' + this.value.substring(end);
                    this.selectionStart = this.selectionEnd = start + 4;
                    updateLines();
                }
            });

            // Initial line numbers
            updateLines();
        });
    </script>
</body>
</html>
