<?php

namespace App\Http\Middleware;

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

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

            if(isset($request->route()?->parameters['slug']))
//                dd($request->route()->parameters['slug'],Project::where('slug',$request->route()->parameters['slug'])->first());
                $project = Project::where('slug',$request->route()->parameters['slug'])->first() ?? Project::getAllDrafts()->where('slug',$request->route()->parameters['slug'])->first();
            else
                $project = $request->has('project_id') ? Project::find($request->project_id) : $request->route('project');

            if($project==null) return redirect()->back()->with('error', 'You are not allowed to access this project.');

            if($project->status == 'Drafted') return $next($request);
            $isProjectOwner = $request->user()?->id === $project->user_id;


            $projectOwnerRedirect = $isProjectOwner && Route::currentRouteName() != 'client.projects.show';

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

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

            $isEngineerOrFirm = $isEngineer || $isFirm;

            // if the user is an engineer and has a proposal on the project
            $engineerHasProposal = $request->user()?->engineer ? $project->proposals()
            ->where('proposalable_id', $request->user()?->engineer?->id)
            ->where('proposalable_type', 'App\Models\Engineer')
            ->exists() : false;


            // if the user is a firm and has a proposal on the project
            $firmHasProposal = $request->user()?->firm ? $project->proposals()
            ->where('proposalable_id', $request->user()?->firm?->id)
            ->where('proposalable_type', 'App\Models\Firm')
            ->exists() : false;

            $hasProposal = $engineerHasProposal || $firmHasProposal;

            $isProjectWorker = (($isEngineerOrFirm || $hasProposal) && (Route::currentRouteName() != 'engineer.projects.show' || Route::currentRouteName() != 'firm.projects.show')) && !$isProjectOwner;

            $isAuthorized = $isProjectOwner || $isProjectWorker;

            if($projectOwnerRedirect) {
                if(!Route::currentRouteName() == "client.projects.edit")
                    return redirect()->route('client.projects.show',$project->slug);
            }

            else if($isProjectWorker) {
                if($isEngineer || $engineerHasProposal)

                    return redirect()->route('engineer.projects.show', ['project' => $project->slug])->with(['status' => 'You can view your proposal/contract here']);

                else if($isFirm || $firmHasProposal)
                    return redirect()->route('firm.projects.show', ['project' => $project->slug])->with(['status' => 'You can view your proposal/contract here']);
            }

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

            if (($project->status != 'Open' || $project->proposals()->where('accepted',true)->exists()) && !$isAuthorized){
                    return redirect()->route('projects.index')->with('error', 'You are not allowed to access this project.');
            }
        }
        return $next($request);
    }
}
