<?php

namespace App\Classes\Modules\HelpMenu\ControllersLogic;

use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\HelpMenu\Processors\SaveAnswerProcessor;
use App\Classes\Modules\HelpMenu\Processors\UserSourceForQAProcessor;
use App\Classes\Modules\HelpMenu\Services\FetchesUrl;
use ErrorException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Crypt;

class SubmitQAQuestionsLogic extends AbstractControllerLogic
{

    /**
     * @return array
     */
    protected function notification():array {
        return [
            'title' => 'Feedback Submission',
            'message' => 'You have successfully submitted yours answers'
        ];
    }

    /** @var SaveAnswerProcessor */
    private $saveAnswerProcessor;

    /** @var UserSourceForQAProcessor */
    private $userSourceForQAProcessor;

    /** @var FetchesUrl */
    private $fetchesUrl;

    /**
     * SubmitQAQuestionsLogic constructor.
     * @param SaveAnswerProcessor $saveAnswerProcessor
     * @param UserSourceForQAProcessor $userSourceForQAProcessor
     * @param FetchesUrl $fetchesUrl
     */
    public function __construct(SaveAnswerProcessor $saveAnswerProcessor, UserSourceForQAProcessor $userSourceForQAProcessor, FetchesUrl $fetchesUrl)
    {
        $this->saveAnswerProcessor = $saveAnswerProcessor;
        $this->userSourceForQAProcessor = $userSourceForQAProcessor;
        $this->fetchesUrl = $fetchesUrl;
    }


    /**
     * @param Request $request
     * @return JsonResponse
     * @throws ErrorException
     */
    public function logic(Request $request) : JsonResponse
    {
        $originalToken = '';
        $shortToken = $request->input('token');
        $userId = 0;
        $sourceId = 0;
        try {
            $url = $this->fetchesUrl->execute(['short_url' => $shortToken]);
            $originalToken = $url->original_url;
            $decriptedToken = Crypt::decryptString($originalToken);
            $delimiter = "|";
            $parts = explode($delimiter, $decriptedToken);
            $system = $parts[0];
            $customerMarking = $parts[1];
            $email = $parts[2];

            $result = $this->userSourceForQAProcessor->execute($system, $customerMarking, $email);
            $userId = $result['userId'];
            $sourceId = $result['sourceId'];

        } catch (\Throwable $e) {
            Log::error($e);
        }

        $answers = $request->input('answers');
        foreach ($answers as $answer) {
            $filesUpload = $request->input('files');
            $this->saveAnswerProcessor->execute($userId, $sourceId, $answer['questionId'], $answer['answer'], $answer['answerId'], $filesUpload, $shortToken);
        }

        $response =  ['message' => 'Thank you for your feedback.'];
        return $this->response(['data' => $response]);
    }
}
