<?php

declare(strict_types=1);

namespace App\Models;

use CodeIgniter\Model;

class QuizAttemptQuestionModel extends Model
{
    protected $table            = 'quiz_attempt_questions';
    protected $primaryKey       = 'id';
    protected $returnType       = 'array';
    protected $useSoftDeletes   = false;
    protected $allowedFields    = [
        'quiz_attempt_id',
        'question_index',
        'question_text',
        'question_type',
        'options_json',
        'correct_answer',
        'source_document_id',
        'source_chunk_index',
        'timer_seconds',
        'user_answer',
        'is_correct',
        'answered',
        'timed_out',
        'answered_at',
        'time_spent_seconds',
        'ai_rationale',
    ];
    protected $useTimestamps    = true;
    protected $createdField     = 'created_at';
    protected $updatedField     = 'updated_at';
    protected $validationRules  = [];
    protected $skipValidation   = false;

    public function usedQuestionSignatures(int $quizSettingId, int $userId): array
    {
        $builder = $this->builder('quiz_attempt_questions', false);
        $builder->distinct();
        $builder->select("SHA1(CONCAT(quiz_settings.id, '|', LOWER(question_text))) AS sig");
        $builder->join('quiz_attempts', 'quiz_attempts.id = quiz_attempt_questions.quiz_attempt_id', 'inner');
        $builder->join('quiz_settings', 'quiz_settings.id = quiz_attempts.quiz_setting_id', 'inner');
        $builder->where('quiz_settings.id', $quizSettingId);
        $builder->where('quiz_attempts.user_id', $userId);
        $rows = $builder->get()->getResultArray();
        $out = [];
        foreach ($rows as $r) { $s = (string)($r['sig'] ?? ''); if ($s !== '') $out[$s] = true; }
        return $out;
    }
}
