<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;
use App\Classes\ValueObjects\Constants\QASystemSourceType;
use App\Models\QAAnswerOptions;
use App\Models\QAQuestions;
use Carbon\Carbon;

class HelpMenuQuestionsAnswersResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        $question = QAQuestions::where('id', $this->question_id)->first();
        $source = new HelpMenuUserSourceResource($this->userSource);
        $user = $this->source_id === 0 ? new UserResource($this->user) : null;
        $answerOption = QAAnswerOptions::where('id', $this->answer_option_id)->first();

        $user_marking = '';
        if($user){
            $companyModule = $user->companyModule()->first();
            $user_marking = $companyModule ? $companyModule->inviters()->withPivot('invitee_reference')->first()->pivot->invitee_reference : "";
        }

        return [
            'question_id' => $this->question_id,
            'questionnaire' => new HelpMenuQuestionnaireSetsResource($this->question->questionnaire),
            'question_text' => $question ? $question->question_text : null,
            'free_text_answer' => $answerOption ? $answerOption->display_text : null,
            'answer_value' => $answerOption ? $answerOption->value : null,
            'source_system' => $user ? QASystemSourceType::getText(QASystemSourceType::IZYIM) : QASystemSourceType::getText($source->system),
            'source_marking' => $user ? $user_marking : $source->marking,
            'source_email' => $user ? $user->email : $source->email,
            'created_at' => Carbon::parse($this->created_at)->format('d-m-Y'),
        ];
    }
}
