<?php

namespace App\Classes\Modules\HelpMenu\Processors;

use App\Models\QAUserAnswerSelected;
use App\Classes\Modules\HelpMenu\Services\FetchesHelpMenuUserAnswerSelected;
use App\Classes\Modules\Documents\Processors\UploadDocumentForHelpMenuProcessor;


class SaveAnswerProcessor
{
    /** @var FetchesHelpMenuUserAnswerSelected */
    private $fetchesHelpMenuUserAnswerSelected;

    /** @var UploadDocumentForHelpMenuProcessor */
    private $uploadDocumentForHelpMenuProcessor;

    /**
     * SaveAnswerProcessor constructor.
     * @param FetchesHelpMenuUserAnswerSelected $fetchesHelpMenuUserAnswerSelected
     * @param UploadDocumentForHelpMenuProcessor $uploadDocumentForHelpMenuProcessor
     */
    public function __construct(FetchesHelpMenuUserAnswerSelected $fetchesHelpMenuUserAnswerSelected, UploadDocumentForHelpMenuProcessor $uploadDocumentForHelpMenuProcessor)
    {
        $this->fetchesHelpMenuUserAnswerSelected = $fetchesHelpMenuUserAnswerSelected;
        $this->uploadDocumentForHelpMenuProcessor = $uploadDocumentForHelpMenuProcessor;
    }

    public function execute($userId, $sourceId, $questionId, $answerInText, $answerOptionId, $filesUpload, $reference = null){

        $answer = null;
        // try{
        //      // $answer = $this->fetchesHelpMenuUserAnswerSelected->execute(['user_id' => $userId, 'question_id' => $questionId, 'order_by' => ['column' => 'id','DESC' => 1]]);
        //     $answer = $this->fetchesHelpMenuUserAnswerSelected->execute(['user_id' => $userId, 'user_id' => $sourceId, 'question_id' => $questionId]);
        // } catch (\Exception $exception){
        //     $answer = null;
        // }

        if(is_null($answer))
        {
            $answer = new QAUserAnswerSelected;
        }
        $answer->user_id = $userId;
        $answer->source_id = $sourceId;
        $answer->question_id = $questionId;
        $answer->answer_option_id = intval($answerOptionId);
        $answer->free_text_answer = $answerInText;
        if($reference){
            $answer->reference = $reference;
        }
        $answer->save();

        if($filesUpload){
            $result = $this->uploadDocumentForHelpMenuProcessor->execute($filesUpload, $answer);
            $newData = array_map(function ($item) {
                return [
                    'document_id' => $item->document_id,
                    'file_id' => $item->id,
                ];
            }, $result);
            $answer->free_text_answer = json_encode($newData);
            $answer->save();
        }
    }
}
