<?php

namespace App\Policies;

use App\Models\User;
use App\Models\Project;
use Illuminate\Auth\Access\HandlesAuthorization;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Laravel\Nova\Http\Requests\NovaRequest;
use Laravel\Nova\Nova;

class ProjectPolicy
{
    use HandlesAuthorization;

    /**
     * Create a new policy instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }
    public function create(User $user){
       return Nova::whenServing(function (NovaRequest $request) use ($user) {
            return false;
        }, function (Request $request) use ($user) {
            return true;
        });
    }
    public function update(User $user,Project $project){
        return Nova::whenServing(function (NovaRequest $request) use ($user) {
            return false;
        }, function (Request $request) use ($user,$project) {
            return $project->user->id === $user->id;
        });
    }
    public function view(User $user,Project $project){
        return Nova::whenServing(function (NovaRequest $request) use ($user) {
            return $user->hasAnyPermission(['control projects']);
        }, function (Request $request) use ($user,$project) {
            if($project->user->id === $user->id ||
                ($project->projectable_id === $user->engineer?->id && $project->projectable_type === "App\Models\Engineer")
                ||($project->projectable_id === $user->firm?->id && $project->projectable_type === "App\Models\Firm")) {
                return true;
            }
            return url()->previous();
        });
    }
    public function delete(User $user,){
        return Nova::whenServing(function (NovaRequest $request) use ($user) {
            return $user->hasAnyPermission(['control projects']);
        });
    }
    public function viewAny(User $user){
        return Nova::whenServing(function (NovaRequest $request) use ($user) {
            return $user->hasAnyPermission(['control projects']);
        });
    }
}
