<?php


namespace Mehrab\Service\Repositories;


use Mehrab\Service\Models\Question_Answer_Service;

class QuestionRepo
{
    public function findById($service)
    {
        return Question_Answer_Service::query()->findOrFail($service);
    }

    public function save_options_for_question(array $options, $questionId)
    {
        $data = [];
        foreach ($options as $option) {
            if ($option) {
                $data[] = [
                    'content' => $option,
                    'parent_id' => $questionId,
                ];
            }
        }
        return Question_Answer_Service::query()->insert($data);
    }

    public function set_price_options($request,$optionID){
         return Question_Answer_Service::query()
            ->where('id',$optionID)
            ->update([
                'price' => $request->price,
            ]);
    }

    public function set_priority_options($request,$optionID){
         return Question_Answer_Service::query()
            ->where('id',$optionID)
            ->update([
                'priority' => $request->priority,
            ]);
    }
    public function set_parent_question_options($request,$optionID){
        return Question_Answer_Service::query()
            ->where('id',$optionID)
            ->update([
                'parent_question' => $request->parent_question,
            ]);
    }

    public function question_delete($service, $question)
    {
        $question = Question_Answer_Service::query()->findOrFail($question);
        return $question->delete();
    }

    public function find_checkbox_answers(array $array)
    {
        $arrayQuestionsIDs = array_keys($array);

        $questions = Question_Answer_Service::query()
            ->with('children')
            ->whereIn('id',$arrayQuestionsIDs)
            ->get();

        $answersCheckbox = [];

        foreach ($questions as $question){
            $answerIDs = $array[$question->id];
            $answers = $question->children
                ->whereIn('id',$answerIDs)
                ->pluck('content')
                ->toArray();
            $answersCheckbox[$question->content] = $answers;
        }
        return $answersCheckbox;
    }

    public function find_radio_answers(array $radioAnswers)
    {
        $arrayQuestionsIDs = array_keys($radioAnswers);

        $questions = Question_Answer_Service::query()
            ->with(['children'])
            ->whereIn('id',$arrayQuestionsIDs)
            ->get();

        $answersRadio = [];
        foreach ($questions as $question){
            $answerID = $radioAnswers[$question->id];
            $answers = $question->children
                ->where('id',$answerID)
                ->first()->content;
            $answersRadio[$question->content] = $answers;
        }
        return $answersRadio;
    }

}
