<?php  

namespace App\Business\UserProfile\Questions;

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

class QuestionService
{
    public static function createQuestion($question, $answerType, $survey)
    {
        try {
            $questionId = null;
            DB::transaction(function () use ($question, $answerType, &$questionId, $survey) {

                $question = Question::create([
                    'question' => $question,
                    'question_type' => QuestionType::Optional->value,
                    'answer_type' => $answerType,
                    'category_id' => 0,
                    'can_edit' => 0
                ]);
                $questionId = $question->id;
                SurviesQuestions::create([
                    'question_id' => $questionId,
                    'survey_id' => $survey,
                    'is_active' => true
                ]);
            });
            return $questionId;
        } catch (\Throwable $th) {
            throw $th;
        }
    }

    public static function addOptions($question, $answerType, $options)
    {
        if ($answerType != QuestionOptionType::Open->value && $answerType != QuestionOptionType::Range->value) {
            return self::saveOptions($question, $options);
        }
        if ($answerType == QuestionOptionType::Range->value) {
            $range = "{\"min\":{$options[0]},\"max\":{$options[1]}}";
            return self::saveOptions($question, [$range]);
        }
    }

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