<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;
use App\Models\QAQuestions;
use App\Models\QAAnswerOptions;
use App\Models\QAUserAnswerSelected;

class HelpMenuQuestionResource extends JsonResource
{
    /** @var integer */
    private $userId;

    /** @var QAQuestions*/
    private $question;

    public function __construct($question, $userId) {
        $this->question = $question;
        $this->userId = $userId;
    }
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        if($this->question){
            $q = (object)$this->question;
            return [
                'id' => $q->id,
                'question_number' => $q->question_number,
                'question_text' => $q->question_text,
                'question_type' => $q->question_type,
                'question_answers' => HelpMenuAnswerOptionsResource::collection(QAAnswerOptions::where('question_number', $q->question_number)->where('questionnaire_set_id', $q->questionnaire_set_id)->orderBy('order', 'ASC')->get()),
                'questionnaire_set_id' => $q->questionnaire_set_id,
                'next_nested_question' => $q->next_nested_question,
                'next_main_question' => $q->next_main_question,
                'is_start' => $q->is_start,
                'is_end' => $q->is_end,
                'end_text' => $q->end_text,
                'order' => $q->order,
                'answer' => QAUserAnswerSelected::where('question_id', $q->id)->where('user_id', $this->userId)->first(),
                'questionnaire_answers' => $q->is_end ? HelpMenuQuestionnaireAnswersResource::collection(QAUserAnswerSelected::where('user_id', $this->userId)->get()) : null,
            ];
        }
        else{
            return [];
        }
    }
}
