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

if (!$submission_id) {
    header('Location: submissions.php');
    exit();
}

$conn = getDBConnection();

// Get user data including profile picture
$user_query = "SELECT profile_picture FROM users WHERE id = ?";
$stmt = $conn->prepare($user_query);
$stmt->bind_param("i", $instructor_id);
$stmt->execute();
$user_result = $stmt->get_result();
$user = $user_result->fetch_assoc();
$stmt->close();

// Get submission details
$submission_query = "SELECT sub.*, a.title, a.description, a.expected_output, s.subject_name, u.full_name as student_name, u.username as student_username
                     FROM submissions sub
                     JOIN activities a ON sub.activity_id = a.id
                     JOIN subjects s ON a.subject_id = s.id
                     JOIN users u ON sub.student_id = u.id
                     WHERE sub.id = ? AND a.created_by = ?";
$stmt = $conn->prepare($submission_query);
$stmt->bind_param("ii", $submission_id, $instructor_id);
$stmt->execute();
$submission_result = $stmt->get_result();

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

$submission = $submission_result->fetch_assoc();
$stmt->close();

// Handle grading
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['grade_submission'])) {
    requireCSRFToken();
    $score = floatval($_POST['score']);
    $feedback = trim($_POST['feedback']);

    $update_query = "UPDATE submissions SET score = ?, feedback = ?, status = 'graded', graded_at = CURRENT_TIMESTAMP WHERE id = ?";
    $stmt = $conn->prepare($update_query);
    $stmt->bind_param("dsi", $score, $feedback, $submission_id);

    if ($stmt->execute()) {
        // Create notification for student
        $notif_message = "Your submission for '" . $submission['title'] . "' has been graded. Score: " . $score . "%";
        $notif_query = "INSERT INTO notifications (user_id, message, activity_id, is_read) VALUES (?, ?, ?, FALSE)";
        $stmt = $conn->prepare($notif_query);
        $stmt->bind_param("isi", $submission['student_id'], $notif_message, $submission['activity_id']);
        $stmt->execute();

        // Send push notification
        require_once '../api/send_push_notification.php';
        $activity_url = '/Capstone_Project/student/take_activity.php?id=' . $submission['activity_id'];
        sendPushNotification(
            $submission['student_id'],
            'Assignment Graded',
            $notif_message,
            $activity_url,
            $submission['activity_id']
        );

        header('Location: submissions.php?success=graded');
        exit();
    } else {
        $error_message = "Failed to grade submission!";
    }
    $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>Grade Submission - CODELAB</title>
    <link rel="stylesheet" href="../assets/css/style.css">
    <script src="../assets/js/dark-mode.js" defer></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">Activities</a>
                <a href="submissions.php" class="nav-link active">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">
        <?php if (isset($error_message)): ?>
            <div class="alert alert-error"><?php echo $error_message; ?></div>
        <?php endif; ?>

        <div class="activity-details">
            <a href="submissions.php" style="color: #667eea; text-decoration: none; margin-bottom: 10px; display: inline-block;">← Back to Submissions</a>
            <h2><?php echo htmlspecialchars($submission['title']); ?></h2>
            <div class="activity-meta">
                <span class="subject-tag"><?php echo htmlspecialchars($submission['subject_name']); ?></span>
                <div class="meta-item">
                    👤 <strong>Student:</strong> <?php echo htmlspecialchars($submission['student_name']); ?> (<?php echo htmlspecialchars($submission['student_username']); ?>)
                </div>
                <div class="meta-item">
                    📅 <strong>Submitted:</strong> <?php echo date('M d, Y H:i', strtotime($submission['submitted_at'])); ?>
                </div>
                <?php if ($submission['status'] == 'graded'): ?>
                    <div class="meta-item" style="color: #28a745;">
                        ✓ <strong>Graded:</strong> <?php echo date('M d, Y H:i', strtotime($submission['graded_at'])); ?>
                    </div>
                    <div class="meta-item" style="color: #667eea;">
                        🏆 <strong>Score:</strong> <?php echo number_format($submission['score'], 2); ?>%
                    </div>
                <?php endif; ?>
            </div>
            <div class="activity-description">
                <h3>📋 Activity Description:</h3>
                <p><?php echo nl2br(htmlspecialchars($submission['description'])); ?></p>
            </div>
            <?php if ($submission['expected_output']): ?>
                <div class="activity-description">
                    <h3>🎯 Expected Output:</h3>
                    <div class="output-container">
                        <pre><?php echo htmlspecialchars($submission['expected_output']); ?></pre>
                    </div>
                </div>
            <?php endif; ?>
        </div>

<!-- Student's Code -->
        <div class="code-editor-container">
            <h3>💻 Student's Code:</h3>
            <div class="code-editor-wrapper">
                <div class="line-numbers" id="line-numbers"></div>
                <textarea class="code-editor" id="student-code" readonly spellcheck="false"><?php echo htmlspecialchars($submission['code']); ?></textarea>
            </div>

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

                <!-- 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"></textarea>
                    </div>
                </div>
            </div>

            <div style="margin-top: 15px;">
                <button onclick="runCode('c')" class="btn btn-secondary">▶️ Test Run as C</button>
                <button onclick="runCode('cpp')" class="btn btn-secondary">▶️ Test Run as C++</button>
            </div>
        </div>

        <!-- Program Output -->
        <div class="code-editor-container">
            <h3>📤 Program Output:</h3>
            <div class="output-container" id="output-container">
                <pre><?php echo $submission['output'] ? htmlspecialchars($submission['output']) : 'No output recorded'; ?></pre>
            </div>
        </div>

        <!-- Grading Form -->
        <form method="POST" class="grade-form-container">
            <?php echo csrfField(); ?>
            <h3>📊 Grade This Submission:</h3>
            <div class="form-group">
                <label>Score (0-100) *</label>
                <input type="number" name="score" class="score-input" step="0.01" min="0" max="100" required
                       value="<?php echo $submission['status'] == 'graded' ? $submission['score'] : ''; ?>"
                       placeholder="Enter score out of 100">
                <span class="form-helper">Enter a score between 0 and 100</span>
            </div>
            <div class="form-group">
                <label>Feedback *</label>
                <textarea name="feedback" class="feedback-input" rows="6" required placeholder="Provide feedback to the student..."><?php
                    echo $submission['status'] == 'graded' ? htmlspecialchars($submission['feedback']) : '';
                ?></textarea>
                <span class="form-helper">Provide constructive feedback to help the student improve</span>
            </div>
            <div class="form-actions">
                <button type="submit" name="grade_submission" class="btn btn-success">
                    <?php echo $submission['status'] == 'graded' ? '✓ Update Grade' : '✓ Submit Grade'; ?>
                </button>
                <a href="submissions.php" class="btn btn-secondary">Cancel</a>
            </div>
        </form>
    </div>

    <script>
        // Line numbers functionality
        function updateLineNumbers() {
            const codeEditor = document.getElementById('student-code');
            const lineNumbers = document.getElementById('line-numbers');
            const lines = codeEditor.value.split('\n');
            const numberOfLines = lines.length;

            let lineNumbersHtml = '';
            for (let i = 1; i <= numberOfLines; i++) {
                lineNumbersHtml += `<div>${i}</div>`;
            }
            lineNumbers.innerHTML = lineNumbersHtml;
        }

        // Sync scroll between line numbers and code editor
        function syncScroll() {
            const codeEditor = document.getElementById('student-code');
            const lineNumbers = document.getElementById('line-numbers');
            lineNumbers.scrollTop = codeEditor.scrollTop;
        }

        // Initialize line numbers on page load
        document.addEventListener('DOMContentLoaded', function() {
            updateLineNumbers();

            const codeEditor = document.getElementById('student-code');
            codeEditor.addEventListener('scroll', syncScroll);
        });

        function runCode(language) {
            const code = `<?php echo addslashes($submission['code']); ?>`;
            const input = document.getElementById('program-input').value;
            const outputContainer = document.getElementById('output-container');

            outputContainer.innerHTML = '<pre>Compiling and running code...</pre>';

            const formData = new FormData();
            formData.append('code', code);
            formData.append('language', language);
            formData.append('input', input);

            fetch('../api/execute_code.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                const outputClass = data.success ? 'output-success' : 'output-error';
                outputContainer.innerHTML = `<pre class="${outputClass}">${escapeHtml(data.output)}</pre>`;
            })
            .catch(error => {
                outputContainer.innerHTML = '<pre class="output-error">Error: Failed to execute code.</pre>';
            });
        }

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

        // 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 input editor for testing student code
        document.addEventListener('DOMContentLoaded', function() {
            const studentCode = document.getElementById('student-code');

            // Detect input prompts from student's code on page load
            detectInputPromptsFromCode();

            function detectInputPromptsFromCode() {
                const code = studentCode.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]{0,50}?cin\s*>>/g,
                    /cout\s*<<\s*'([^']+)'\s*;[\s\S]{0,50}?cin\s*>>/g,
                    // C printf patterns
                    /printf\s*\(\s*"([^"]+)"\s*\)[\s\S]{0,50}?scanf/g
                ];

                let prompts = [];
                patterns.forEach(pattern => {
                    let match;
                    while ((match = pattern.exec(code)) !== null) {
                        let prompt = match[1].trim();
                        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';
                }

                window.detectedPrompts = prompts;
                updateInputHints();
            }

            // 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();
        });

        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>

    <style>
        /* Fix dark mode visibility for grading form */
        .score-input,
        .feedback-input {
            background: var(--card-bg) !important;
            color: var(--text-primary) !important;
            border: 1px solid rgba(255, 255, 255, 0.1);
        }

        .score-input:focus,
        .feedback-input:focus {
            background: var(--card-bg) !important;
            color: var(--text-primary) !important;
            border-color: var(--primary-moss);
        }

        .form-helper {
            color: #999;
            font-size: 0.85em;
        }

        /* Input hints styling */
        .detected-prompts-box {
            background: #e3f2fd;
            border-left: 4px solid #2196F3;
            padding: 12px;
            margin-top: 10px;
            border-radius: 4px;
        }

        body.dark-mode .detected-prompts-box {
            background: #1a237e;
            border-left-color: #64b5f6;
        }

        .input-hints {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            padding: 10px;
            font-family: 'Consolas', 'Courier New', monospace;
            font-size: 14px;
            line-height: 20px;
            color: #999;
            pointer-events: none;
            overflow: hidden;
            white-space: pre;
        }

        .input-hint-line {
            height: 20px;
            line-height: 20px;
        }

        /* Dark mode specific fixes */
        @media (prefers-color-scheme: dark) {
            .score-input,
            .feedback-input {
                background: #2a2a2a !important;
                color: #e0e0e0 !important;
                border: 1px solid #444;
            }

            .score-input::placeholder,
            .feedback-input::placeholder {
                color: #888 !important;
            }

            .score-input:focus,
            .feedback-input:focus {
                background: #333 !important;
                color: #fff !important;
                border-color: #667eea;
            }
        }
    </style>
</body>
</html>
