<?php

declare(strict_types=1);

namespace App\Models;

use CodeIgniter\Model;

class QuizAttemptModel extends Model
{
    protected $table            = 'quiz_attempts';
    protected $primaryKey       = 'id';
    protected $returnType       = 'array';
    protected $useSoftDeletes   = false;
    protected $allowedFields    = [
        'quiz_setting_id',
        'user_id',
        'attempt_no',
        'status',
        'started_at',
        'completed_at',
        'total_questions',
        'answered_count',
        'correct_count',
        'score_pct',
        'passed',
        'ai_feedback',
        'raw_questions_json',
    ];
    protected $useTimestamps    = true;
    protected $createdField     = 'created_at';
    protected $updatedField     = 'updated_at';
    protected $validationRules  = [];
    protected $skipValidation   = false;

    public function listWithSettingAndUser(?int $quizSettingId = null, ?int $userId = null, ?string $fromDate = null, ?string $toDate = null): array
    {
        $builder = $this->builder('quiz_attempts', false);
        $builder->select('quiz_attempts.*, users.full_name as user_name, users.email as user_email, quiz_settings.title as quiz_title, quiz_settings.question_type as quiz_type');
        $builder->join('users', 'users.id = quiz_attempts.user_id', 'left');
        $builder->join('quiz_settings', 'quiz_settings.id = quiz_attempts.quiz_setting_id', 'left');
        if ($quizSettingId !== null) $builder->where('quiz_attempts.quiz_setting_id', $quizSettingId);
        if ($userId !== null) $builder->where('quiz_attempts.user_id', $userId);
        if ($fromDate !== null && $fromDate !== '') $builder->where('DATE(quiz_attempts.created_at) >=', $fromDate);
        if ($toDate !== null && $toDate !== '') $builder->where('DATE(quiz_attempts.created_at) <=', $toDate);
        $builder->orderBy('quiz_attempts.created_at', 'DESC');
        return $builder->get()->getResultArray();
    }

    public function getWithQuestions(int $id): ?array
    {
        $attempt = $this->find($id);
        if (!$attempt) return null;
        $questionModel = new QuizAttemptQuestionModel();
        $attempt['questions'] = $questionModel
            ->where('quiz_attempt_id', $id)
            ->orderBy('question_index', 'ASC')
            ->findAll();
        return $attempt;
    }
}
