<?php
namespace App\Services;

class AssessmentService {
    public function __construct(private \PDO $pdo) {}

    public function assignedQuestions(int $attemptId): array {
        $stmt = $this->pdo->prepare("SELECT q.*, taq.sort_order, taq.options_order_json FROM test_attempt_questions taq JOIN questions q ON taq.question_id = q.id WHERE taq.attempt_id = ? ORDER BY taq.sort_order");
        $stmt->execute([$attemptId]);
        return $stmt->fetchAll();
    }

    public function canStudentAttempt(int $studentId, int $testId): bool {
        $stmt = $this->pdo->prepare("SELECT max_attempts FROM tests WHERE id = ?");
        $stmt->execute([$testId]);
        $max = (int)$stmt->fetchColumn();
        $stmt = $this->pdo->prepare("SELECT COUNT(*) FROM test_attempts WHERE student_id = ? AND test_id = ? AND status IN ('completed','auto_submitted')");
        $stmt->execute([$studentId, $testId]);
        return (int)$stmt->fetchColumn() < $max;
    }
}
