<?php

namespace App\Http\Middleware;

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

class ServiceMiddleware
{
    /**
     * 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_id') || $request->route('service') != null || isset($request->route()?->parameters['slug'])){

            if(Auth::check())
            if(Auth::user()->hasAnyPermission(['control services orders', 'control services'])) return $next($request);

            if($request->route()->parameters['slug'])
                $service = Service::where('slug', $request->route()->parameters['slug'])->first() ?? Service::getAllDrafts()->where('slug', $request->route()->parameters['slug'])->first();
            else
                $service = $request->has('service_id') ? Service::find($request->service_id) : $request->route('service');
            if ($service==null) return redirect()->back()->with('error', 'Service not found.');
            if($service->status == 'Draft') return $next($request);

            $userMadeOrder = $service?->orders()->where('user_id',$request->user()?->id)->where(function ($query) {
                $query->where('status','pending')->orWhere('status','accepted')->orWhere('status','in progress');
            })->exists();

            if($userMadeOrder)
            {
                $userOrders = $service->orders()->with('milestones.transaction')->where('user_id',$request->user()?->id)->get();

                $userOrders->each(function($order) use ($service){
                        $order->milestones?->each(function($milestone) use ($order , $service){
                            if(!$milestone->transaction)
                               {
                                   $order->delete();
                                   $service->refresh();
                            }
                        });
                    });
                $userMadeOrder = $service?->orders()->where('user_id',$request->user()?->id)->where(function ($query) {
                    $query->where('status','pending')->orWhere('status','accepted')->orWhere('status','in progress');
                })->exists();
                    }


            $isEngineer = $request->user()?->engineer?->id === $service->serviceable?->id && $service->serviceable !=null;

            $isFirm = ($request->user()?->firm?->id === $service->serviceable?->id) && $service->serviceable !=null;

            $isEngineerOrFirm = $isEngineer || $isFirm;

            $serviceIsPublished = $service->status == 'Published';

            $isAuthorizedToSee = $isEngineerOrFirm || $userMadeOrder || $serviceIsPublished;

            $shouldRedirectToGuestView = !$isEngineerOrFirm && Route::currentRouteName() != 'service.show' && !$userMadeOrder && $serviceIsPublished;

            $shouldRedirectToEngineerOrFirmView = ($isEngineerOrFirm && Route::currentRouteName() != 'engineer.services.show' && Route::currentRouteName() != 'firm.services.show') && !$userMadeOrder;


            $shouldRedirectToClientOrderView = $userMadeOrder && Route::currentRouteName() != 'service.orders.show';

            if($shouldRedirectToGuestView) return redirect()->route('service.show',$service->slug);

            else if($shouldRedirectToEngineerOrFirmView)
            {
                if($isEngineer) {
                    if(!(Route::currentRouteName() == "engineer.services.edit"))
                     return redirect()->route('engineer.services.show',$service->slug);
                    }

                else if($isFirm) {
                    if(!(Route::currentRouteName() == "firm.services.edit"))
                        return redirect()->route('firm.services.show',$service->slug);
                }
            }

            else if($shouldRedirectToClientOrderView) return redirect()->route('service.orders.show', $service->orders()->where('user_id',$request->user()?->id)->where('status', 'pending')->latest()->firstOrFail()->id);

            else if(!$isAuthorizedToSee) return redirect()->route('services.index')->with('error', 'You are not allowed to access this service.');

        }
        return $next($request);
    }
}
