<?php

namespace App\Http\Middleware;

use App\Models\ServiceOrder;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class ServiceOrderMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        if($request->has('service_order_id')||$request->route('service_order')!=null){
            if(Auth::check()) 
                if(Auth::user()->hasAnyPermission(['control services orders', 'control services'])) return $next($request);
                
            $serviceOrder = $request->has('service_order_id')?
                ServiceOrder::find($request->service_order) :
                $request->route('service_order');
            if($request->user()?->id === $serviceOrder->user_id
                || (($request->user()->engineer?->id === $serviceOrder->service->serviceable_id)&& $serviceOrder->service->serviceable_type == "App\Models\Engineer")
                || (($request->user()->firm?->id === $serviceOrder->service->serviceable_id)&& $serviceOrder->service->serviceable_type == "App\Models\Firm")){
                return $next($request);
            }else{
                return redirect()->route('services.index')->with('error', 'You are not allowed to access this service.');
            }
        }
        return $next($request);
    }
}
