<?php

namespace App\Classes\Modules\HelpMenu\Processors;

use App\Models\QAUserAnswerSelected;
use App\Classes\Modules\HelpMenu\Services\FetchesHelpMenuUserAnswerSelected;
use App\Classes\Modules\HelpMenu\Services\ListsHelpMenuUserAnswerSelected;

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

    /** @var ListsHelpMenuUserAnswerSelected */
    private $listsHelpMenuUserAnswerSelected;

    /**
     * DeleteAnswerQAProcessor constructor.
     * @param FetchesHelpMenuUserAnswerSelected $fetchesHelpMenuUserAnswerSelected
     * @param ListsHelpMenuUserAnswerSelected $listsHelpMenuUserAnswerSelected
     */
    public function __construct(FetchesHelpMenuUserAnswerSelected $fetchesHelpMenuUserAnswerSelected, ListsHelpMenuUserAnswerSelected $listsHelpMenuUserAnswerSelected)
    {
        $this->fetchesHelpMenuUserAnswerSelected = $fetchesHelpMenuUserAnswerSelected;
        $this->listsHelpMenuUserAnswerSelected = $listsHelpMenuUserAnswerSelected;
    }


    /**
     * @param int $userId
     * @param int $questionId
     * @param Request $request
     * @return void
     * @throws ResourceNotFoundException
     */
    public function execute($userId, $questionId, $request){
        if ($request->has('isPrevious')) {
            //Get current and previous question's answer
            try{
                $selectedAnswer = $this->listsHelpMenuUserAnswerSelected->execute(['user_id' => $userId, 'question_id' => $questionId, 'order_by' => (object)['column' => 'id','DESC' => true]])[0];
            } catch (\Exception $exception){
                $selectedAnswer = null;
            }

            if($selectedAnswer)
            {
                $this->fetchesHelpMenuUserAnswerSelected->execute(['id' => $selectedAnswer['id']])->delete();
            }
        }
        else{
            //Delete all answer's belongs to the user
            $currentQuestion = $request->question;
            $isStart = $currentQuestion['is_start'];
            if($isStart){
                QAUserAnswerSelected::where('user_id', $userId)->delete();
            }
        }
    }
}
