<?php

namespace App\Models;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use OwenIt\Auditing\Contracts\Auditable;

use App\Traits\Permissions\HasPermissionsTrait;

class User extends Authenticatable implements Auditable
{
    use \OwenIt\Auditing\Auditable;
    use Notifiable,HasPermissionsTrait;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name','username', 'email', 'password','branch_id', 'phone1', 'phone2', 'address', 'status'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function branch() {
        return $this->belongsTo(Branch::class);
    }

    public function branches() {
        return $this->belongsToMany(Branch::class);
    }

    public function sales(){
        return $this->hasMany(Sale::class);
    }
    public function purchases(){
        return $this->hasMany(Purchase::class);
    }

    public function getRouteKeyName():string
    {
        return 'username';
    }

    public function getAccessibleBranchIds()
    {
        if ($this->hasRole('superadmin')) {
            return Branch::pluck('id');
        }
        $ids = $this->branches->pluck('id');
        if ($ids->isEmpty() && $this->branch_id) {
            $ids->push($this->branch_id);
        }
        return $ids;
    }

}
