<?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;
$assessment = $db->get("SELECT * FROM assessments WHERE id = ? AND created_by = ?", [$id, $user['id']]);
if (!$assessment) redirect('assessments.php');

$submissions = $db->getAll("SELECT s.*, u.first_name, u.last_name FROM assessment_submissions s LEFT JOIN users u ON s.student_id = u.id WHERE s.assessment_id = ? ORDER BY s.id DESC", [$id]);

$pageTitle = 'Assessment - ' . htmlspecialchars($assessment['title']) . ' - Attempts';
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">Attempts - <?php echo htmlspecialchars($assessment['title']); ?></h5>
                <a href="<?php echo APP_URL; ?>/lms/assessments.php" class="btn btn-outline-secondary btn-sm">Back</a>
            </div>
            <div class="card-body">
                <?php if (empty($submissions)): ?>
                    <p class="text-muted">No attempts yet.</p>
                <?php else: ?>
                    <table class="table table-striped">
                        <thead>
                            <tr><th>Student</th><th>Score</th><th>Percentage</th><th>Passed</th><th>Submitted</th><th></th></tr>
                        </thead>
                        <tbody>
                            <?php foreach ($submissions as $s): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars(trim($s['first_name'] . ' ' . $s['last_name'])); ?></td>
                                    <td><?php echo is_null($s['score']) ? '-' : htmlspecialchars($s['score']); ?></td>
                                    <td><?php echo is_null($s['percentage']) ? '-' : htmlspecialchars($s['percentage']) . '%'; ?></td>
                                    <td><?php echo $s['passed'] ? 'Yes' : 'No'; ?></td>
                                    <td><?php echo htmlspecialchars($s['created_at']); ?></td>
                                    <td><a class="btn btn-sm btn-outline-primary" href="<?php echo APP_URL; ?>/lms/assessments_attempt_view.php?id=<?php echo (int)$s['id']; ?>">View</a></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>
<?php include __DIR__ . '/includes/footer.php';
