<?php
require_once '../../config/database.php';
require_once '../../config/auth.php';
require_once '../../config/rbac.php';
$lms_config = require '../../config/lms.php';
require_once '../../includes/functions.php';
require_once '../../includes/middleware.php';

// Check if user is instructor or admin
anyRoleMiddleware(['instructor', 'admin']);

$user = getUserContext();
$db = getDB();
$userId = $_SESSION['user_id'];

$attemptId = $_GET['id'] ?? 0;
if (!$attemptId) {
    header('Location: index.php');
    exit;
}

// Get attempt details with exam and student info
$stmt = $db->prepare("
    SELECT
        ea.*,
        e.title as exam_title,
        e.description as exam_description,
        e.instructions,
        e.total_points,
        e.passing_score,
        c.title as course_title,
        up.first_name,
        up.last_name,
        u.email,
        up.avatar
    FROM exam_attempts ea
    JOIN exams e ON ea.exam_id = e.id
    LEFT JOIN courses c ON e.course_id = c.id
    JOIN users u ON ea.student_id = u.id
    LEFT JOIN user_profiles up ON u.id = up.user_id
    WHERE ea.id = ? AND e.instructor_id = ?
");
$stmt->execute([$attemptId, $userId]);
$attempt = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$attempt) {
    $_SESSION['error_message'] = 'Submission not found or access denied.';
    header('Location: index.php');
    exit;
}

// Get exam questions with student answers
$stmt = $db->prepare("
    SELECT
        eq.*,
        q.title,
        q.content,
        q.question_type,
        q.points as default_points,
        q.explanation,
        q.hints,
        qo.id as option_id,
        qo.option_text,
        qo.is_correct
    FROM exam_questions eq
    JOIN questions q ON eq.question_id = q.id
    LEFT JOIN question_options qo ON q.id = qo.question_id
    WHERE eq.exam_id = ?
    ORDER BY eq.sort_order, qo.sort_order
");
$stmt->execute([$attempt['exam_id']]);
$questionData = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Group questions and options
$questions = [];
foreach ($questionData as $row) {
    $qid = $row['question_id'];
    if (!isset($questions[$qid])) {
        $questions[$qid] = [
            'id' => $qid,
            'title' => $row['title'],
            'content' => $row['content'],
            'type' => $row['question_type'],
            'points' => $row['points'],
            'explanation' => $row['explanation'],
            'hints' => json_decode($row['hints'], true) ?: [],
            'options' => []
        ];
    }
    if ($row['option_id']) {
        $questions[$qid]['options'][] = [
            'id' => $row['option_id'],
            'text' => $row['option_text'],
            'is_correct' => $row['is_correct']
        ];
    }
}

// Get student's answers
$studentAnswers = json_decode($attempt['answers'], true) ?: [];

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $db->beginTransaction();

        $questionScores = $_POST['question_scores'] ?? [];
        $feedback = $_POST['feedback'] ?? '';
        $totalScore = 0;
        $maxScore = 0;

        // Calculate scores for each question
        foreach ($questions as $questionId => $question) {
            $maxScore += $question['points'];

            if (isset($questionScores[$questionId])) {
                $score = floatval($questionScores[$questionId]);
                $totalScore += min($score, $question['points']); // Don't allow scores above max
            } else {
                // For objective questions, use existing score if available
                if (in_array($question['type'], ['mcq_single', 'mcq_multiple', 'true_false', 'matching'])) {
                    // Recalculate objective score
                    $studentAnswer = $studentAnswers[$questionId] ?? null;
                    if ($studentAnswer) {
                        $score = calculateQuestionScore($question, $studentAnswer);
                        $totalScore += $score;
                    }
                }
            }
        }

        $percentage = $maxScore > 0 ? round(($totalScore / $maxScore) * 100, 2) : 0;
        $isPassed = $percentage >= $attempt['passing_score'];

        // Update attempt with final grades
        $stmt = $db->prepare("
            UPDATE exam_attempts
            SET score = ?, max_score = ?, percentage = ?, is_passed = ?, feedback = ?, graded_at = NOW(), graded_by = ?
            WHERE id = ?
        ");
        $stmt->execute([$totalScore, $maxScore, $percentage, $isPassed ? 1 : 0, $feedback, $userId, $attemptId]);

        // Store individual question grades if provided
        if (!empty($questionScores)) {
            foreach ($questionScores as $questionId => $score) {
                // You might want to create a separate table for question-level grading
                // For now, we'll store this in the feedback or extend the schema
            }
        }

        $db->commit();

        $_SESSION['success_message'] = 'Submission graded successfully!';
        header('Location: index.php');
        exit;

    } catch (Exception $e) {
        $db->rollBack();
        $_SESSION['error_message'] = 'Error grading submission: ' . $e->getMessage();
    }
}

function calculateQuestionScore($question, $studentAnswer) {
    switch ($question['type']) {
        case 'mcq_single':
        case 'true_false':
            foreach ($question['options'] as $option) {
                if ($option['id'] == $studentAnswer && $option['is_correct']) {
                    return $question['points'];
                }
            }
            return 0;

        case 'mcq_multiple':
            if (is_array($studentAnswer)) {
                $correctOptions = array_filter($question['options'], fn($opt) => $opt['is_correct']);
                $selectedCorrect = 0;
                $totalCorrect = count($correctOptions);

                foreach ($studentAnswer as $selectedId) {
                    foreach ($correctOptions as $correctOption) {
                        if ($correctOption['id'] == $selectedId) {
                            $selectedCorrect++;
                            break;
                        }
                    }
                }

                if ($totalCorrect > 0) {
                    return ($selectedCorrect / $totalCorrect) * $question['points'];
                }
            }
            return 0;

        case 'matching':
            if (is_array($studentAnswer)) {
                $correctMatches = 0;
                $totalMatches = 0;

                foreach ($question['options'] as $option) {
                    if ($option['is_correct']) {
                        $totalMatches++;
                        if (isset($studentAnswer[$option['id']]) &&
                            $studentAnswer[$option['id']] == $option['id']) {
                            $correctMatches++;
                        }
                    }
                }

                if ($totalMatches > 0) {
                    return ($correctMatches / $totalMatches) * $question['points'];
                }
            }
            return 0;

        default:
            return 0; // Manual grading required
    }
}

function formatStudentAnswer($answer, $question) {
    if (!$answer) {
        return '<em class="text-muted">No answer provided</em>';
    }

    switch ($question['type']) {
        case 'mcq_single':
        case 'true_false':
            foreach ($question['options'] as $option) {
                if ($option['id'] == $answer) {
                    return htmlspecialchars($option['text']);
                }
            }
            break;

        case 'mcq_multiple':
            if (is_array($answer)) {
                $texts = [];
                foreach ($answer as $optionId) {
                    foreach ($question['options'] as $option) {
                        if ($option['id'] == $optionId) {
                            $texts[] = htmlspecialchars($option['text']);
                            break;
                        }
                    }
                }
                return implode('<br>', $texts);
            }
            break;

        case 'essay':
        case 'short_answer':
        case 'code':
            return '<pre>' . htmlspecialchars($answer) . '</pre>';

        case 'matching':
            if (is_array($answer)) {
                $matches = [];
                foreach ($answer as $leftId => $rightId) {
                    $matches[] = "Match {$leftId} -> {$rightId}";
                }
                return implode('<br>', $matches);
            }
            break;

        case 'fill_blanks':
            return htmlspecialchars($answer);
    }

    return htmlspecialchars($answer);
}

function formatCorrectAnswer($question) {
    $correctAnswers = [];

    switch ($question['type']) {
        case 'mcq_single':
        case 'true_false':
            foreach ($question['options'] as $option) {
                if ($option['is_correct']) {
                    $correctAnswers[] = htmlspecialchars($option['text']);
                }
            }
            break;

        case 'mcq_multiple':
            foreach ($question['options'] as $option) {
                if ($option['is_correct']) {
                    $correctAnswers[] = htmlspecialchars($option['text']);
                }
            }
            break;

        case 'essay':
        case 'short_answer':
        case 'code':
        case 'fill_blanks':
            return '<em class="text-muted">Manual grading required</em>';

        case 'matching':
            return '<em class="text-muted">See explanation above</em>';
    }

    return implode('<br>', $correctAnswers);
}

$page_title = 'Grade Submission - ' . htmlspecialchars($attempt['exam_title']) . ' - ' . $lms_config['lms']['site_name'];
include '../../includes/header.php';
?>

<div class="admin-container">
    <div class="admin-sidebar">
        <div class="admin-logo">
            <h2><?php echo htmlspecialchars($lms_config['lms']['site_name']); ?></h2>
            <p><?php echo htmlspecialchars($lms_config['lms']['site_name']); ?></p>
        </div>

        <nav class="admin-nav">
            <ul>
                <li><a href="../dashboard.php">Dashboard</a></li>
                <li><a href="../courses/">My Courses</a></li>
                <li><a href="../courses/new.php">Create Course</a></li>
                <li><a href="/lms/instructor/questions/index.php">Question Bank</a></li>
                <li><a href="/lms/instructor/exams/index.php">Exams</a></li>
                <li><a href="index.php" class="active">Grading</a></li>
                <li><a href="../resources.php">Resources</a></li>
                <li><a href="../students.php">Students</a></li>
                <li><a href="../assignments.php">Assignments</a></li>
                <li><a href="/lms/instructor/grading/index.php">Grades</a></li>
                <li><a href="../../logout.php">Logout</a></li>
            </ul>
        </nav>
    </div>

    <div class="admin-content">
        <div class="admin-header">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <h1>Grade Submission</h1>
                    <p class="text-muted">
                        <?php echo htmlspecialchars($attempt['exam_title']); ?> -
                        <?php echo htmlspecialchars($attempt['first_name'] . ' ' . $attempt['last_name']); ?>
                    </p>
                </div>
                <a href="index.php" class="btn btn-secondary">
                    <i class="fas fa-arrow-left me-2"></i>Back to Queue
                </a>
            </div>
        </div>

        <!-- Student and Exam Info -->
        <div class="card mb-4">
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <h6>Student Information</h6>
                        <div class="d-flex align-items-center mb-2">
                            <?php if ($attempt['avatar']): ?>
                                <img src="<?php echo htmlspecialchars($attempt['avatar']); ?>"
                                     class="rounded-circle me-3" width="48" height="48" alt="Avatar">
                            <?php else: ?>
                                <div class="bg-primary text-white rounded-circle d-flex align-items-center justify-content-center me-3"
                                     style="width: 48px; height: 48px; font-size: 18px;">
                                    <?php echo strtoupper(substr($attempt['first_name'], 0, 1) . substr($attempt['last_name'], 0, 1)); ?>
                                </div>
                            <?php endif; ?>
                            <div>
                                <h6 class="mb-0"><?php echo htmlspecialchars($attempt['first_name'] . ' ' . $attempt['last_name']); ?></h6>
                                <small class="text-muted"><?php echo htmlspecialchars($attempt['email']); ?></small>
                            </div>
                        </div>
                        <p class="mb-1"><strong>Attempt:</strong> <?php echo $attempt['attempt_number']; ?></p>
                        <p class="mb-1"><strong>Started:</strong> <?php echo date('M j, Y g:i A', strtotime($attempt['started_at'])); ?></p>
                        <?php if ($attempt['completed_at']): ?>
                            <p class="mb-1"><strong>Completed:</strong> <?php echo date('M j, Y g:i A', strtotime($attempt['completed_at'])); ?></p>
                            <p class="mb-0"><strong>Time Spent:</strong> <?php echo gmdate('H:i:s', $attempt['time_spent']); ?></p>
                        <?php endif; ?>
                    </div>
                    <div class="col-md-6">
                        <h6>Exam Information</h6>
                        <p class="mb-1"><strong>Exam:</strong> <?php echo htmlspecialchars($attempt['exam_title']); ?></p>
                        <?php if ($attempt['course_title']): ?>
                            <p class="mb-1"><strong>Course:</strong> <?php echo htmlspecialchars($attempt['course_title']); ?></p>
                        <?php endif; ?>
                        <p class="mb-1"><strong>Total Points:</strong> <?php echo $attempt['total_points']; ?></p>
                        <p class="mb-1"><strong>Passing Score:</strong> <?php echo $attempt['passing_score']; ?>%</p>
                        <?php if ($attempt['score'] !== null): ?>
                            <p class="mb-1"><strong>Current Score:</strong> <?php echo round($attempt['percentage'], 1); ?>%</p>
                            <p class="mb-0"><strong>Status:</strong>
                                <span class="badge bg-<?php echo $attempt['is_passed'] ? 'success' : 'danger'; ?>">
                                    <?php echo $attempt['is_passed'] ? 'PASSED' : 'FAILED'; ?>
                                </span>
                            </p>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Grading Form -->
        <form method="POST">
            <div class="row">
                <div class="col-lg-8">
                    <!-- Questions Review -->
                    <div class="card mb-4">
                        <div class="card-header">
                            <h5 class="mb-0">Question Review</h5>
                        </div>
                        <div class="card-body">
                            <?php $questionNumber = 1; ?>
                            <?php foreach ($questions as $questionId => $question): ?>
                                <div class="question-grading-item mb-4 p-3 border rounded">
                                    <div class="d-flex justify-content-between align-items-start mb-3">
                                        <h6>
                                            Question <?php echo $questionNumber++; ?>:
                                            <?php echo htmlspecialchars($question['title']); ?>
                                        </h6>
                                        <div class="text-end">
                                            <span class="badge bg-secondary"><?php echo $question['points']; ?> pts</span>
                                            <small class="text-muted ms-2"><?php echo ucfirst(str_replace('_', ' ', $question['type'])); ?></small>
                                        </div>
                                    </div>

                                    <div class="question-content mb-3">
                                        <div><?php echo $question['content']; ?></div>
                                    </div>

                                    <div class="row">
                                        <div class="col-md-6">
                                            <h6>Student's Answer:</h6>
                                            <div class="answer-display p-3 bg-light rounded">
                                                <?php echo formatStudentAnswer($studentAnswers[$questionId] ?? null, $question); ?>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <h6>Correct Answer:</h6>
                                            <div class="correct-answer p-3 bg-success bg-opacity-10 rounded">
                                                <?php echo formatCorrectAnswer($question); ?>
                                            </div>
                                        </div>
                                    </div>

                                    <?php if ($question['explanation']): ?>
                                        <div class="explanation mt-3 p-3 bg-info bg-opacity-10 rounded">
                                            <h6>Explanation:</h6>
                                            <div><?php echo $question['explanation']; ?></div>
                                        </div>
                                    <?php endif; ?>

                                    <!-- Grading Controls (only for manual grading questions) -->
                                    <?php if (in_array($question['type'], ['essay', 'short_answer', 'code', 'fill_blanks'])): ?>
                                        <div class="grading-controls mt-3 p-3 bg-warning bg-opacity-10 rounded">
                                            <h6>Grading:</h6>
                                            <div class="row align-items-end">
                                                <div class="col-md-4">
                                                    <label class="form-label">Points Awarded</label>
                                                    <input type="number" class="form-control question-score"
                                                           name="question_scores[<?php echo $questionId; ?>]"
                                                           min="0" max="<?php echo $question['points']; ?>"
                                                           step="0.5" value="<?php echo $question['points']; ?>">
                                                </div>
                                                <div class="col-md-8">
                                                    <label class="form-label">Comments (optional)</label>
                                                    <textarea class="form-control" name="question_comments[<?php echo $questionId; ?>]"
                                                              rows="2" placeholder="Feedback for this question..."></textarea>
                                                </div>
                                            </div>
                                        </div>
                                    <?php else: ?>
                                        <!-- Show auto-calculated score for objective questions -->
                                        <div class="auto-score mt-3 p-2 bg-success bg-opacity-10 rounded">
                                            <small class="text-success">
                                                <i class="fas fa-check-circle me-1"></i>
                                                Auto-graded: <?php echo calculateQuestionScore($question, $studentAnswers[$questionId] ?? null); ?>/<?php echo $question['points']; ?> points
                                            </small>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>

                <div class="col-lg-4">
                    <!-- Grading Summary -->
                    <div class="card mb-4">
                        <div class="card-header">
                            <h5 class="mb-0">Grading Summary</h5>
                        </div>
                        <div class="card-body">
                            <div class="mb-3">
                                <label class="form-label">Overall Feedback</label>
                                <textarea class="form-control" name="feedback" rows="4"
                                          placeholder="General feedback for the student..."><?php echo htmlspecialchars($attempt['feedback'] ?? ''); ?></textarea>
                            </div>

                            <div class="row mb-3">
                                <div class="col-6">
                                    <div class="p-2 bg-light rounded text-center">
                                        <div class="fw-bold" id="total-score">0</div>
                                        <small class="text-muted">Total Score</small>
                                    </div>
                                </div>
                                <div class="col-6">
                                    <div class="p-2 bg-light rounded text-center">
                                        <div class="fw-bold" id="total-max"><?php echo array_sum(array_column($questions, 'points')); ?></div>
                                        <small class="text-muted">Maximum</small>
                                    </div>
                                </div>
                            </div>

                            <div class="mb-3">
                                <div class="p-2 bg-primary bg-opacity-10 rounded text-center">
                                    <div class="fw-bold fs-5" id="final-percentage">0%</div>
                                    <small class="text-muted">Final Grade</small>
                                </div>
                            </div>

                            <div class="d-grid gap-2">
                                <button type="submit" class="btn btn-success">
                                    <i class="fas fa-save me-2"></i>Save Grades
                                </button>
                                <button type="button" class="btn btn-outline-secondary" onclick="previewFeedback()">
                                    <i class="fas fa-eye me-2"></i>Preview Feedback
                                </button>
                            </div>
                        </div>
                    </div>

                    <!-- Quick Actions -->
                    <div class="card">
                        <div class="card-header">
                            <h6 class="mb-0">Quick Actions</h6>
                        </div>
                        <div class="card-body">
                            <div class="d-grid gap-2">
                                <button type="button" class="btn btn-outline-primary btn-sm" onclick="viewRubric()">
                                    <i class="fas fa-book me-1"></i>View Rubric
                                </button>
                                <button type="button" class="btn btn-outline-info btn-sm" onclick="viewSimilarSubmissions()">
                                    <i class="fas fa-users me-1"></i>Similar Submissions
                                </button>
                                <button type="button" class="btn btn-outline-warning btn-sm" onclick="requestReview()">
                                    <i class="fas fa-user-friends me-1"></i>Request Review
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Auto-calculate total score
    updateTotalScore();

    // Listen for score changes
    document.querySelectorAll('.question-score').forEach(input => {
        input.addEventListener('input', updateTotalScore);
    });
});

function updateTotalScore() {
    let totalScore = 0;
    const maxScore = <?php echo array_sum(array_column($questions, 'points')); ?>;

    // Add auto-calculated scores for objective questions
    <?php foreach ($questions as $questionId => $question): ?>
        <?php if (!in_array($question['type'], ['essay', 'short_answer', 'code', 'fill_blanks'])): ?>
            totalScore += <?php echo calculateQuestionScore($question, $studentAnswers[$questionId] ?? null); ?>;
        <?php endif; ?>
    <?php endforeach; ?>

    // Add manual scores
    document.querySelectorAll('.question-score').forEach(input => {
        totalScore += parseFloat(input.value) || 0;
    });

    const percentage = maxScore > 0 ? ((totalScore / maxScore) * 100).toFixed(1) : 0;

    document.getElementById('total-score').textContent = totalScore.toFixed(1);
    document.getElementById('final-percentage').textContent = percentage + '%';
}

function previewFeedback() {
    const feedback = document.querySelector('textarea[name="feedback"]').value;
    alert('Feedback Preview:\n\n' + (feedback || 'No feedback provided'));
}

function viewRubric() {
    alert('Rubric viewing functionality will be implemented');
}

function viewSimilarSubmissions() {
    alert('Similar submissions functionality will be implemented');
}

function requestReview() {
    if (confirm('Request review from another instructor?')) {
        alert('Review request functionality will be implemented');
    }
}
</script>

<style>
.question-grading-item {
    background-color: #f8f9fa;
}

.question-grading-item:hover {
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.answer-display, .correct-answer {
    min-height: 80px;
    max-height: 200px;
    overflow-y: auto;
}

.grading-controls {
    border-left: 4px solid #ffc107;
}

.auto-score {
    border-left: 4px solid #28a745;
}

.explanation {
    border-left: 4px solid #17a2b8;
}
</style>

<?php include '../../includes/footer.php'; ?>