<?php

namespace App\Models\UserManagement;


use App\Models\OrderManagement\Order;
use App\Models\OrderManagement\BillingDesk;
use App\Models\OrderManagement\BillingDeskHasUser;
use App\Models\SecurityManagement\Role;
use App\Models\StockManagement\Traits\CanAdjustStock;
use App\Models\StockManagement\Traits\CanManageStock;
use App\Models\StockManagement\Traits\CanManageWarehouse;
use Database\Factories\AdminFactory;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class Admin extends User {

    use CanManageStock,CanManageWarehouse,CanAdjustStock;
    public $table = "user_mgt__admins";
    protected $guarded = ['id'];
   // protected $guard_name = 'admin';

    public function guardName(){
        return "admin";
    }

//    public function getMorphClass(){
//       return User::class;
//    }

//    public function guardName(){
//        return "admin";
//    }

    protected static function newFactory(){
        return AdminFactory::new();
    }

    protected static function booted(){
//        parent::addGlobalScope(new UserGlobalScope); // TODO: Change the autogenerated stub

        //parent::observe();

        parent::created(function(Admin $admin){

        });
    }

    /**
     * @return BelongsToMany
     */
    public function billingDesks(){
        return $this->belongsToMany(
            BillingDesk::class,
            (new BillingDeskHasUser)->getTable(),
            "manager_id",
            "billing_desk_id"
        );
    }

    public function orders(){
        return $this->hasMany(Order::class,"created_by")->latest();
    }

    //SCOPES
    public function scopeStockManagers($query){
        $permissions = array_column(config('stocks-management.permissions'),"name");
        return  $query->whereHas('roles', function ($query) use ($permissions) {
            return $query->whereHas('permissions', function ($query) use ($permissions){
                return $query->whereIn('name', $permissions);
            });
        });
    }
    public function scopeSuperAdmins($query){
        return  $query->whereHas('roles', fn ($query) => $query->where('name',Role::SUPER_ADMIN));
    }


    public function registerMediaCollections(): void{
        $this->addMediaCollection('admins')
            ->singleFile() // ne doit contenir qu'un seul fichier sur la collection ( utilisateur n'a qu'un seul avatar )
//            ->useFallbackUrl(get_gravatar($this->email)) // retouné lorsque getUrl = null
            ->useFallbackUrl(url("img/avatar.png")) // retouné lorsque getUrl = null
        ;

    }



}
