<?php

namespace App\Http\Middleware;

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

class ProposalMiddleware
{
    /**
     * 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('proposal_id') || $request->route('proposal') != null){
            if(Auth::check()) 
                if(Auth::user()->hasAnyPermission(['control projects', 'control services orders', 'control services'])) return $next($request);

            $proposal = $request->has('proposal_id') ? Proposal::find($request->proposal_id) : $request->route('proposal');

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

            $isFirm = ($request->user()?->firm?->id === $proposal->proposalable?->id) && $proposal->proposalable !=null;
            $isEngineerOrFirm = $isEngineer || $isFirm;

            if($proposal->project->user->id === Auth::user()?->id) {
                return $next($request);
            }
            else if($isEngineerOrFirm){

                return redirect()->route('engineer.proposals.show', ['proposal' => $proposal->id]);
            }else{
                return redirect()->route('projects.index')->with('error', 'You are not allowed to access this project.');

            }
        }
        return $next($request);
    }
}
