<?php

namespace App\Http\Middleware;

use App\Models\AppSession;
use Closure;

class EnsureProCanAccessPatient
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $sessionKey = $request->cookie('sessionKey');
        $appSession = AppSession::where('session_key', $sessionKey)->where('is_active', true)->first();
        $authenticated = $sessionKey && $appSession && $appSession->pro;
       
        if (!$authenticated) {
            abort(403);
        }

        $patient = \request()->route('patient');

        if(!!$patient) {
            if(!$appSession->pro->canAccess($patient->uid)) {
                abort(403);
            }
        }

        return $next($request);
    }
}
