<?php  

namespace App\Admin\Question;

use App\Models\Question;
use App\Models\QuestionOption;
use App\Models\Entities\QuestionOptionType;
use App\Models\Entities\QuestionType;
use Illuminate\Support\Facades\DB;

class QuestionService 
{
    public static function createQuestion($question,$answerType, $category, $options = null) {
        try {
            $questionId = null;
            DB::transaction(function() use ($question, $answerType, $category, $options, &$questionId){
                
                $question = Question::create([
                    'question' => $question,
                    'question_type' => QuestionType::Required->value,
                    'answer_type' => $answerType,
                    'category_id' => $category,
                    'can_edit' => 0
                ]);
                $questionId = $question->id;
                if ($answerType != QuestionOptionType::Open->value && $answerType != QuestionOptionType::Range->value) {
                    self::addOptions($questionId, $options);                    
                }
                if($answerType == QuestionOptionType::Range->value){
                    $range = "{\"min\":{$options[0]},\"max\":{$options[1]}}";
                    self::addOptions($questionId, [$range]);
                }
            });
            return $questionId;
        } catch (\Throwable $th) {
            throw $th;
        }
    }

    private static function addOptions($question, $options){
        foreach ($options as $option) {
            QuestionOption::create([
                'answers' => $option,
                'question_id' => $question
            ]);
        }
    }
}
