<?php

namespace Mtc\Plugins\Clinic\Http\Controllers;

use Illuminate\Routing\Controller;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\Routing\ResponseFactory;
use Illuminate\Contracts\View\Factory;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Routing\Redirector;
use Illuminate\View\View;
use Mtc\Modules\Members\Classes\Auth;
use Mtc\Plugins\Clinic\Src\Models\Review;

class ReviewController extends Controller
{
    /**
     * Access review and redirect
     *
     * @param $hash
     * @param Request $request
     * @return Application|ResponseFactory|RedirectResponse|Response|Redirector
     */
    public function access($hash, Request $request)
    {
        /** @var Review $review */
        $review = Review::query()
            ->whereNotNull('hash')
            ->where('medium', Review::MEDIUM_ONLINE)
            ->where('hash', $hash)
            ->first();

        if (empty($review)) {
            return response('Not found', 404);
        }

        // Login member, so that previous assessment answers can be accessed.
        Auth::login($review->member);

        if ($review->status === Review::STATUS_PENDING) {
            return redirect($review->getAssessmentURL());
        }

        return redirect(route('reviews-result', [
            'hash' => $hash,
        ]));
    }

    /**
     * Show review result page
     *
     * @param $hash
     * @param Request $request
     * @return Application|ResponseFactory|Factory|Response|View
     */
    public function result($hash, Request $request)
    {

        /** @var Review $review */
        $review = Review::query()
            ->whereNotNull('hash')
            ->where('medium', Review::MEDIUM_ONLINE)
            ->where('hash', $hash)
            ->first();

        if (empty($review)) {
            return response('Not found', 404);
        }

        if ($review->status === Review::STATUS_PENDING) {
            return redirect($review->getAssessmentURL());
        }

        $title = match ($review->status) {
            Review::STATUS_SUBMITTED => 'Questionnaire Submitted',
            Review::STATUS_COMPLETE => 'Assessment Complete',
            Review::STATUS_CANCELLED => 'Assessment Cancelled',
        };
        $page_meta['title'] = config('app.name') . ' | ' . $title;

        return template('reviews/result.twig', [
            'review' => $review,
            'title' => $title,
            'subtitle' => match ($review->status) {
                Review::STATUS_SUBMITTED => 'Your answers have been submitted and review is pending!',
                Review::STATUS_COMPLETE => 'Your assessment is already complete!',
                Review::STATUS_CANCELLED => 'Your assessment has been cancelled!',
            },
            'page_meta' => $page_meta,
        ]);
    }
}