<?php

declare(strict_types=1);

namespace App\Models;

use App\Core\Model;
use PDO;

/**
 * ExamQuestion Model
 *
 * Handles multiple-choice exam questions with bulk creation
 * support for adding multiple questions at once.
 */
class ExamQuestion extends Model
{
    /**
     * The database table associated with the model.
     */
    protected string $table = 'exam_questions';

    /**
     * Get all questions for a specific exam, ordered by sort_order.
     *
     * @param int $examId The exam ID
     * @return array<int, array<string, mixed>> Array of question records
     */
    public function getByExam(int $examId): array
    {
        $sql = sprintf(
            'SELECT * FROM `%s` WHERE `exam_id` = :exam_id ORDER BY `sort_order` ASC',
            $this->table
        );

        $stmt = $this->db->prepare($sql);
        $stmt->execute([':exam_id' => $examId]);

        return $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
    }

    /**
     * Create multiple questions for an exam in a single transaction.
     *
     * Each question array must contain: question_text, option_a, option_b,
     * option_c, option_d, correct_answer, marks, sort_order.
     *
     * @param int $examId The exam ID to associate questions with
     * @param array<int, array<string, mixed>> $questions Array of question data
     * @return void
     */
    public function createBulk(int $examId, array $questions): void
    {
        $this->db->beginTransaction();

        try {
            $sql = sprintf(
                'INSERT INTO `%s` (`exam_id`, `question_text`, `option_a`, `option_b`, `option_c`, `option_d`, `correct_answer`, `marks`, `sort_order`)
                 VALUES (:exam_id, :question_text, :option_a, :option_b, :option_c, :option_d, :correct_answer, :marks, :sort_order)',
                $this->table
            );

            $stmt = $this->db->prepare($sql);

            foreach ($questions as $question) {
                $stmt->execute([
                    ':exam_id'        => $examId,
                    ':question_text'  => $question['question_text'],
                    ':option_a'       => $question['option_a'],
                    ':option_b'       => $question['option_b'],
                    ':option_c'       => $question['option_c'],
                    ':option_d'       => $question['option_d'],
                    ':correct_answer' => $question['correct_answer'],
                    ':marks'          => $question['marks'] ?? 1,
                    ':sort_order'     => $question['sort_order'] ?? 0,
                ]);
            }

            $this->db->commit();
        } catch (\Throwable $e) {
            $this->db->rollBack();
            throw $e;
        }
    }
}
