<?php

namespace App\Providers;

use App\Models\Permision;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;
use App\Models\User;
use App\Models\UserHasPermition;


class AuthServiceProvider extends ServiceProvider
{
    /**
     * The model to policy mappings for the application.
     *
     * @var array<class-string, class-string>
     */
    protected $policies = [
        //
    ];

    /**
     * Register any authentication / authorization services.
     */
    public function boot(Request $request)
    {   
        try
        {
            $name_permision = Permision::query()->select("name")->get();
            foreach ($name_permision as $permision_row){
                Gate::define($permision_row->name, function (User $user) use ($permision_row) 
                {     
                    $result = UserHasPermition::query()
                        ->join("permisions", "id_permitions","=", "id")
                        ->where("id_user", $user->id)
                        ->where("name", $permision_row->name)
                        ->get()
                        ->toArray();
                
                    if (count($result) > 0)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                });
            }
        }catch(Exception $e){}
    }
    
}