<?php
require_once __DIR__ . '/config/database.php';
requireLogin();
if (!hasRole('instructor') && !hasPermission('can_view_reports')) redirect('dashboard.php');
$db = Database::getInstance();
$user = getCurrentUser();

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$submission = $db->get("SELECT s.*, a.title as assessment_title, u.first_name, u.last_name FROM assessment_submissions s JOIN assessments a ON s.assessment_id = a.id LEFT JOIN users u ON s.student_id = u.id WHERE s.id = ?", [$id]);
if (!$submission) redirect('assessments.php');

$answers = json_decode($submission['answers'], true) ?: [];
// Fetch questions
$questions = $db->getAll("SELECT * FROM assessment_questions WHERE assessment_id = ? ORDER BY sort_order ASC", [$submission['assessment_id']]);

$pageTitle = 'Attempt - ' . htmlspecialchars($submission['assessment_title']);
include __DIR__ . '/includes/header.php';
?>
<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-header d-flex align-items-center justify-content-between">
                <h5 class="m-0">Attempt by <?php echo htmlspecialchars(trim($submission['first_name'] . ' ' . $submission['last_name'])); ?></h5>
                <a href="<?php echo APP_URL; ?>/lms/assessments_report_detail.php?id=<?php echo (int)$submission['assessment_id']; ?>" class="btn btn-outline-secondary btn-sm">Back</a>
            </div>
            <div class="card-body">
                <p><strong>Score:</strong> <?php echo is_null($submission['score']) ? '-' : htmlspecialchars($submission['score']); ?> / <?php echo htmlspecialchars($submission['max_score']); ?></p>
                <p><strong>Percentage:</strong> <?php echo is_null($submission['percentage']) ? '-' : htmlspecialchars($submission['percentage']) . '%'; ?></p>

                <?php foreach ($questions as $q): ?>
                    <div class="mb-3">
                        <div><strong><?php echo htmlspecialchars($q['question_text']); ?></strong> <small class="text-muted">(<?php echo htmlspecialchars($q['question_type']); ?>)</small></div>
                        <div class="mt-1">
                            <em>Student answer:</em>
                            <div class="p-2 bg-light border rounded mt-1"><?php echo nl2br(htmlspecialchars($answers[$q['id']] ?? '')); ?></div>
                        </div>
                        <div class="mt-1 text-muted small">Correct answer: <?php echo htmlspecialchars($q['correct_answer'] ?? '-'); ?> &bull; Points: <?php echo htmlspecialchars($q['points']); ?></div>
                    </div>
                <?php endforeach; ?>

            </div>
        </div>
    </div>
</div>

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