<?php
require_once '../../config/database.php';
require_once '../../config/auth.php';
require_once '../../includes/functions.php';
require_once '../../includes/middleware.php';
require_once '../../includes/ExamGradingService.php';

if (!hasAnyRole(['student'])) {
    header('Location: ../../login.php');
    exit;
}

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

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

try {
    $submission = ExamGradingService::getSubmission($db, (int) $attemptId, $userId, $role);
} catch (Throwable $e) {
    $_SESSION['error_message'] = $e->getMessage();
    header('Location: ../dashboard.php');
    exit;
}

$examAttempt = $submission['attempt'];
$questions = $submission['questions'];

$allowedStatuses = ['submitted', 'graded', 'timed_out', 'completed'];
if (!in_array($examAttempt['status'], $allowedStatuses, true)) {
    $_SESSION['error_message'] = 'Exam attempt is not ready for review.';
    header('Location: ../dashboard.php');
    exit;
}

$results = [
    'total_questions' => count($questions),
    'correct_answers' => 0,
    'total_points_earned' => 0.0,
    'total_points_possible' => 0.0,
    'question_breakdown' => []
];

foreach ($questions as $question) {
    $questionId = (int) $question['question_id'];
    $maxPoints = floatval($question['points']);
    $earnedPoints = 0.0;
    $isCorrect = false;

    if ($question['grade'] && $question['grade']['graded_at']) {
        $earnedPoints = floatval($question['grade']['points_earned'] ?? 0);
        $isCorrect = (bool) $question['grade']['is_correct'];
    } elseif (in_array($question['question_type'], ['essay', 'short_answer', 'code'], true)) {
        $isCorrect = null;
    } else {
        $earnedPoints = ExamGradingService::gradeObjectiveQuestion($question, $question['student_answer']);
        $isCorrect = $earnedPoints >= $maxPoints;
    }

    if ($isCorrect === true) {
        $results['correct_answers']++;
    }

    $results['total_points_earned'] += $earnedPoints;
    $results['total_points_possible'] += $maxPoints;

    $results['question_breakdown'][] = [
        'question' => $question,
        'is_correct' => $isCorrect,
        'points_earned' => round($earnedPoints, 2)
    ];
}

$results['total_points_earned'] = round($results['total_points_earned'], 2);
$results['total_points_possible'] = round($results['total_points_possible'], 2);
$results['percentage'] = $results['total_points_possible'] > 0 ?
    round(($results['total_points_earned'] / $results['total_points_possible']) * 100, 1) : 0;

$results['passed'] = $results['percentage'] >= floatval($examAttempt['passing_score']);

$page_title = 'Exam Results - ' . htmlspecialchars($examAttempt['exam_title']) . ' - Mutalex Academy';
include '../../includes/header.php';
?>

<div class="exam-results-page">
    <div class="container">
        <!-- Results Header -->
        <div class="results-header">
            <div class="row">
                <div class="col-lg-8">
                    <h1 class="exam-title"><?php echo htmlspecialchars($examAttempt['exam_title']); ?></h1>
                    <p class="course-info">
                        <i class="fas fa-graduation-cap me-1"></i>
                        <?php echo htmlspecialchars($examAttempt['course_title']); ?>
                    </p>
                    <div class="exam-meta">
                        <span><i class="fas fa-calendar me-1"></i>Completed: <?php echo date('M j, Y \a\t g:i A', strtotime($examAttempt['completed_at'])); ?></span>
                        <span><i class="fas fa-clock me-1"></i>Time Spent: <?php echo gmdate('H:i:s', $examAttempt['time_spent']); ?></span>
                    </div>
                </div>

                <div class="col-lg-4">
                    <div class="score-card <?php echo $results['passed'] ? 'passed' : 'failed'; ?>">
                        <div class="score-display">
                            <div class="score-percentage"><?php echo $results['percentage']; ?>%</div>
                            <div class="score-status">
                                <i class="fas fa-<?php echo $results['passed'] ? 'check-circle' : 'times-circle'; ?>"></i>
                                <?php echo $results['passed'] ? 'PASSED' : 'FAILED'; ?>
                            </div>
                        </div>
                        <div class="score-details">
                            <div class="score-item">
                                <span class="label">Score:</span>
                                <span class="value"><?php echo $results['total_points_earned']; ?>/<?php echo $results['total_points_possible']; ?></span>
                            </div>
                            <div class="score-item">
                                <span class="label">Passing Score:</span>
                                <span class="value"><?php echo $examAttempt['passing_score']; ?>%</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Quick Stats -->
        <div class="stats-overview">
            <div class="row">
                <div class="col-md-3">
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-question-circle"></i>
                        </div>
                        <div class="stat-content">
                            <div class="stat-number"><?php echo $results['total_questions']; ?></div>
                            <div class="stat-label">Total Questions</div>
                        </div>
                    </div>
                </div>

                <div class="col-md-3">
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-check-circle"></i>
                        </div>
                        <div class="stat-content">
                            <div class="stat-number"><?php echo $results['correct_answers']; ?></div>
                            <div class="stat-label">Correct Answers</div>
                        </div>
                    </div>
                </div>

                <div class="col-md-3">
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-trophy"></i>
                        </div>
                        <div class="stat-content">
                            <div class="stat-number"><?php echo $results['total_points_earned']; ?></div>
                            <div class="stat-label">Points Earned</div>
                        </div>
                    </div>
                </div>

                <div class="col-md-3">
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-clock"></i>
                        </div>
                        <div class="stat-content">
                            <div class="stat-number"><?php echo gmdate('i:s', $examAttempt['time_spent']); ?></div>
                            <div class="stat-label">Time Spent</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Question Review -->
        <div class="question-review">
            <div class="review-header">
                <h2>Detailed Review</h2>
                <p>Review your answers and see correct solutions</p>
            </div>

            <div class="questions-list">
                <?php foreach ($results['question_breakdown'] as $index => $item): ?>
                    <div class="question-item <?php echo $item['is_correct'] === true ? 'correct' : ($item['is_correct'] === false ? 'incorrect' : 'pending'); ?>">
                        <div class="question-header">
                            <div class="question-number">
                                Question <?php echo $index + 1; ?>
                                <span class="question-type"><?php echo ucfirst(str_replace('_', ' ', $item['question']['question_type'])); ?></span>
                            </div>
                            <div class="question-status">
                                <?php if ($item['is_correct'] === true): ?>
                                    <span class="badge bg-success">
                                        <i class="fas fa-check me-1"></i>Correct (<?php echo $item['points_earned']; ?> pts)
                                    </span>
                                <?php elseif ($item['is_correct'] === false): ?>
                                    <span class="badge bg-danger">
                                        <i class="fas fa-times me-1"></i>Incorrect (0 pts)
                                    </span>
                                <?php else: ?>
                                    <span class="badge bg-warning">
                                        <i class="fas fa-clock me-1"></i>Pending Review
                                    </span>
                                <?php endif; ?>
                            </div>
                        </div>

                        <div class="question-content">
                            <?php if (!empty($item['question']['title'])): ?>
                                <h4 class="text-lg font-bold text-gray-800 mb-2"><?php echo htmlspecialchars($item['question']['title']); ?></h4>
                            <?php endif; ?>
                            <div class="<?php echo !empty($item['question']['title']) ? 'text-gray-600' : 'text-gray-800 font-medium'; ?>">
                                <?php echo nl2br(htmlspecialchars($item['question']['content'])); ?>
                            </div>
                        </div>

                        <div class="answer-review">
                            <div class="row">
                                <div class="col-md-6">
                                    <h5>Your Answer:</h5>
                                    <div class="student-answer">
                                        <?php
                                        $studentAnswer = $item['question']['student_answer'];
                                        if ($item['question']['question_type'] === 'mcq_single' || $item['question']['question_type'] === 'true_false') {
                                            // Get option text for multiple choice
                                            if (is_numeric($studentAnswer)) {
                                                $stmt = $db->prepare("SELECT option_text FROM question_options WHERE id = ?");
                                                $stmt->execute([$studentAnswer]);
                                                $option = $stmt->fetch(PDO::FETCH_ASSOC);
                                                echo htmlspecialchars($option['option_text'] ?? 'No answer');
                                            } else {
                                                echo htmlspecialchars($studentAnswer ?? 'No answer');
                                            }
                                        } elseif ($item['question']['question_type'] === 'mcq_multiple') {
                                            $answers = is_array($studentAnswer) ? $studentAnswer : (json_decode($studentAnswer, true) ?? []);
                                            if (!empty($answers)) {
                                                echo '<ul>';
                                                foreach ($answers as $answerId) {
                                                    $stmt = $db->prepare("SELECT option_text FROM question_options WHERE id = ?");
                                                    $stmt->execute([$answerId]);
                                                    $option = $stmt->fetch(PDO::FETCH_ASSOC);
                                                    echo '<li>' . htmlspecialchars($option['option_text'] ?? 'Unknown') . '</li>';
                                                }
                                                echo '</ul>';
                                            } else {
                                                echo 'No answer selected';
                                            }
                                        } elseif ($item['question']['question_type'] === 'essay' || $item['question']['question_type'] === 'short_answer') {
                                            // For essay/short answer, decode HTML entities and sanitize to render formatted content safely
                                            $decodedAnswer = html_entity_decode($studentAnswer ?? '', ENT_QUOTES, 'UTF-8');
                                            $sanitizedAnswer = sanitizeContent($decodedAnswer);
                                            if (!empty(trim($sanitizedAnswer))) {
                                                echo $sanitizedAnswer;
                                            } else {
                                                echo 'No answer provided';
                                            }
                                        } else {
                                            echo htmlspecialchars($studentAnswer ?? 'No answer provided');
                                        }
                                        ?>
                                    </div>
                                </div>

                                <div class="col-md-6">
                                    <h5>Correct Answer:</h5>
                                    <div class="correct-answer">
                                        <?php
                                        $correctAnswer = $item['question']['correct_answer'];
                                        if ($item['question']['question_type'] === 'mcq_single' || $item['question']['question_type'] === 'true_false') {
                                            if (is_numeric($correctAnswer)) {
                                                $stmt = $db->prepare("SELECT option_text FROM question_options WHERE id = ?");
                                                $stmt->execute([$correctAnswer]);
                                                $option = $stmt->fetch(PDO::FETCH_ASSOC);
                                                echo htmlspecialchars($option['option_text'] ?? 'N/A');
                                            } else {
                                                echo htmlspecialchars($correctAnswer ?? 'N/A');
                                            }
                                        } elseif ($item['question']['question_type'] === 'mcq_multiple') {
                                            $answers = is_array($correctAnswer) ? $correctAnswer : (json_decode($correctAnswer, true) ?? []);
                                            if (!empty($answers)) {
                                                echo '<ul>';
                                                foreach ($answers as $answerId) {
                                                    $stmt = $db->prepare("SELECT option_text FROM question_options WHERE id = ?");
                                                    $stmt->execute([$answerId]);
                                                    $option = $stmt->fetch(PDO::FETCH_ASSOC);
                                                    echo '<li>' . htmlspecialchars($option['option_text'] ?? 'Unknown') . '</li>';
                                                }
                                                echo '</ul>';
                                            } else {
                                                echo 'No correct answer specified';
                                            }
                                        } else {
                                            echo htmlspecialchars($correctAnswer ?? 'To be reviewed by instructor');
                                        }
                                        ?>
                                    </div>
                                </div>
                            </div>

                            <?php if ($item['question']['explanation']): ?>
                                <div class="answer-explanation">
                                    <h5>Explanation:</h5>
                                    <div><?php echo htmlspecialchars($item['question']['explanation']); ?></div>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>

        <!-- Actions -->
        <div class="results-actions">
            <div class="row">
                <div class="col-md-6">
                    <a href="../dashboard.php" class="btn btn-outline-primary">
                        <i class="fas fa-tachometer-alt me-2"></i>Back to Dashboard
                    </a>
                    <a href="../../courses/learn.php?id=<?php echo $examAttempt['course_id']; ?>" class="btn btn-outline-secondary">
                        <i class="fas fa-play me-2"></i>Continue Learning
                    </a>
                </div>

                <div class="col-md-6 text-end">
                    <?php if ($results['passed']): ?>
                        <button class="btn btn-success" onclick="downloadCertificate()">
                            <i class="fas fa-certificate me-2"></i>Download Certificate
                        </button>
                    <?php endif; ?>

                    <button class="btn btn-primary" onclick="printResults()">
                        <i class="fas fa-print me-2"></i>Print Results
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
.exam-results-page {
    background: #f8f9fa;
    min-height: 100vh;
    padding: 2rem 0;
}

.results-header {
    background: white;
    border-radius: 12px;
    padding: 2rem;
    box-shadow: 0 4px 6px rgba(0,0,0,0.1);
    margin-bottom: 2rem;
}

.exam-title {
    font-size: 2rem;
    font-weight: 700;
    color: #2c3e50;
    margin-bottom: 0.5rem;
}

.course-info {
    color: #6c757d;
    font-size: 1.1rem;
    margin-bottom: 1rem;
}

.exam-meta {
    display: flex;
    gap: 2rem;
    font-size: 0.9rem;
    color: #6c757d;
}

.score-card {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 12px;
    padding: 2rem;
    color: white;
    text-align: center;
    box-shadow: 0 8px 25px rgba(0,0,0,0.2);
}

.score-card.failed {
    background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%);
}

.score-percentage {
    font-size: 3rem;
    font-weight: 700;
    margin-bottom: 0.5rem;
}

.score-status {
    font-size: 1.2rem;
    font-weight: 600;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 0.5rem;
}

.score-details {
    margin-top: 1.5rem;
    padding-top: 1.5rem;
    border-top: 1px solid rgba(255,255,255,0.2);
}

.score-item {
    display: flex;
    justify-content: space-between;
    margin-bottom: 0.5rem;
    font-size: 0.9rem;
}

.stats-overview {
    margin-bottom: 2rem;
}

.stat-card {
    background: white;
    border-radius: 8px;
    padding: 1.5rem;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    display: flex;
    align-items: center;
    gap: 1rem;
    text-align: center;
}

.stat-icon {
    width: 50px;
    height: 50px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.2rem;
    flex-shrink: 0;
}

.stat-content {
    flex: 1;
}

.stat-number {
    font-size: 1.8rem;
    font-weight: 700;
    color: #2c3e50;
    margin-bottom: 0.25rem;
}

.stat-label {
    color: #6c757d;
    font-size: 0.9rem;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.question-review {
    background: white;
    border-radius: 12px;
    padding: 2rem;
    box-shadow: 0 4px 6px rgba(0,0,0,0.1);
    margin-bottom: 2rem;
}

.review-header h2 {
    margin-bottom: 0.5rem;
    color: #2c3e50;
}

.review-header p {
    color: #6c757d;
    margin-bottom: 0;
}

.questions-list {
    margin-top: 2rem;
}

.question-item {
    border: 1px solid #e9ecef;
    border-radius: 8px;
    padding: 1.5rem;
    margin-bottom: 1.5rem;
}

.question-item.correct {
    border-left: 4px solid #28a745;
    background: #f8fff8;
}

.question-item.incorrect {
    border-left: 4px solid #dc3545;
    background: #fff8f8;
}

.question-item.pending {
    border-left: 4px solid #ffc107;
    background: #fffef8;
}

.question-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 1rem;
}

.question-number {
    font-weight: 600;
    color: #2c3e50;
}

.question-type {
    font-size: 0.8rem;
    color: #6c757d;
    margin-left: 0.5rem;
}

.question-content {
    margin-bottom: 1.5rem;
}

.question-content h4 {
    color: #2c3e50;
    margin-bottom: 0.5rem;
}

.answer-review {
    background: #f8f9fa;
    border-radius: 8px;
    padding: 1.5rem;
}

.student-answer, .correct-answer {
    background: white;
    padding: 1rem;
    border-radius: 6px;
    border: 1px solid #e9ecef;
}

.answer-explanation {
    margin-top: 1rem;
    padding-top: 1rem;
    border-top: 1px solid #e9ecef;
}

.answer-explanation h5 {
    color: #2c3e50;
    margin-bottom: 0.5rem;
}

.results-actions {
    background: white;
    border-radius: 12px;
    padding: 2rem;
    box-shadow: 0 4px 6px rgba(0,0,0,0.1);
}

.results-actions .btn {
    margin-right: 0.5rem;
    margin-bottom: 0.5rem;
}

@media (max-width: 768px) {
    .exam-meta {
        flex-direction: column;
        gap: 0.5rem;
    }

    .score-card {
        margin-top: 2rem;
    }

    .question-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 0.5rem;
    }

    .answer-review .row > div {
        margin-bottom: 1rem;
    }

    .results-actions .row > div {
        text-align: center !important;
        margin-bottom: 1rem;
    }
}
</style>

<script>
function downloadCertificate() {
    // This would typically generate and download a PDF certificate
    alert('Certificate download feature coming soon!');
    // You could implement PDF generation here using libraries like TCPDF or similar
}

function printResults() {
    window.print();
}
</script>

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