<?php

namespace App\Classes\Modules\HelpMenu\ControllersLogic;


use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\HelpMenu\DataTransferObjects\UrlObject;
use App\Classes\Modules\HelpMenu\Standards\Rules\CanGenerateFeedbackUrl;
use App\Classes\Modules\HelpMenu\Services\CreatesUrl;
use App\Classes\Modules\HelpMenu\DataTransferObjects\GenerateFeedbackUrlObject;
use ErrorException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Log;

class GenerateFeedbackUrlLogic extends AbstractControllerLogic
{

    /**
     * @return array
     */
    protected function notification():array {
        return [
            'title' => 'Generate Feedback Url',
            'message' => 'You have successfully generated a feedback url'
        ];
    }

    /** @var CanGenerateFeedbackUrl */
    private $canGenerateFeedbackUrl;

    /** @var CreatesUrl */
    private $createsUrl;

    /**
     * GenerateFeedbackUrlLogic constructor.
     * @param CanGenerateFeedbackUrl $canGenerateFeedbackUrl
     * @param CreatesUrl $createsUrl
     */
    public function __construct(CanGenerateFeedbackUrl $canGenerateFeedbackUrl, CreatesUrl $createsUrl)
    {
        $this->canGenerateFeedbackUrl = $canGenerateFeedbackUrl;
        $this->createsUrl = $createsUrl;
    }


    /**
     * @param Request $request
     * @return JsonResponse
     * @throws ErrorException
     */
    public function logic(Request $request) : JsonResponse
    {
        $apiKey = "";
        if($request->get('apiKeyExist'))
        {
            $apiKey = $request->get('apiKeyExist');
        }
        $object = new GenerateFeedbackUrlObject($apiKey, $request->input('system'), $request->input('customer_marking'), $request->input('email'), $request->input('question_set'));
        $this->canGenerateFeedbackUrl->passes($object);

        $shortUrl = Str::random(20);
        $originalText = $object->getSystem() . '|' . $object->getCustomerMarking(). '|' . $object->getEmail(). '|' . $object->getQuestionSet() . '|' . $shortUrl;
        $originalUrl =  Crypt::encryptString($originalText);


        $url = $this->createsUrl->execute(new UrlObject('feedback', $shortUrl, $originalUrl));
        $resource = ['token' => $url->short_url];

        return $this->response(['data' => $resource]);
    }

}
