<?php

namespace App\Models;

use Carbon\Carbon;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Support\Facades\Auth;
use Spatie\Permission\Traits\HasRoles;
use Illuminate\Notifications\Notifiable;
use Spatie\Permission\Models\Permission;
use Spatie\Activitylog\Contracts\Activity;
use Spatie\Activitylog\Traits\LogsActivity;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable, HasRoles, SoftDeletes, LogsActivity;

    protected $fillable = [
        'id',
        'name',
        'code',
        'branch_id',
        'currency_id',
        'nickname',
        'gender',
        'email',
        'password',
        'contact_number',
        'photo',
        'attach_file',
        'status',
        'last_seen',
        'address',
        'type',
        'date_start_working',
        'type_document',
        'id_card',
        'place_of_birth',
        'date_of_birth',
        'create_card_date',
        'expired_card_date',
        'work_place',
        'institution',
        'position',
        'province_id',
        'district_id',
        'commune_id',
        'is_representative',
        'representative_branch_id',
        'village_id'
    ];

    protected static $logAttributes = [
        'id',
        'name',
        'code',
        'branch_id',
        'currency_id',
        'nickname',
        'gender',
        'email',
        'password',
        'contact_number',
        'photo',
        'attach_file',
        'status',
        'last_seen',
        'address',
        'type',
        'date_start_working',
        'type_document',
        'id_card',
        'place_of_birth',
        'date_of_birth',
        'create_card_date',
        'expired_card_date',
        'work_place',
        'institution',
        'position',
        'province_id',
        'district_id',
        'commune_id',
        'is_representative',
        'representative_branch_id',
        'village_id'
    ];

    protected static $recordEvents = ['deleted', 'created', 'updated'];
    protected static $logName = 'User Model';
    protected static $logOnlyDirty = true;

    public function getDescriptionForEvent(string $eventName): string
    {
        return "This user has been {$eventName}";
    }

    public function tapActivity(Activity $activity, string $eventName)
    {
        $activity->ip = request()->ip();
        $activity->agent = request()->header('user-agent');
    }

    public function scopeSearch($query, $searchText)
    {
        if (isset($searchText)) {
            $query->Name($searchText);
            $query->Email($searchText);
            $query->ContactNumber($searchText);
        }
        return $query;
    }

    public function scopeName($query,$searchText)
    {
        return $query->where("name","LIKE","$searchText%");
    }
    public function scopeEmail($query, $searchText)
    {
        $query->orWhere("email", "LIKE", "$searchText%");
    }
    public function scopeContactNumber($query, $searchText)
    {
        $query->orWhere("contact_number", "LIKE", "$searchText%");
    }

    protected $hidden = [
        'password',
        'remember_token',
    ];

    protected $casts = [
        'email_verified_at' => 'datetime',
        'is_representative' => 'boolean',
    ];

    public function getAllPermissionsAttribute()
    {
        $permissions = [];
        foreach (Permission::all() as $permission) {
            if (Auth::user()->can($permission->name)) {
                $permissions[] = $permission->name;
            }
        }
        return $permissions;
    }
    public function loan()
    {
        return $this->hasMany(Loan::class, 'co_id','id');
    }
    public function userHasCO(){
        return $this->hasMany(Group::class, 'user_id','id');
    }
    public function village()
    {
        return $this->belongsTo(Village::class, 'village_id');
    }
    public function commune()
    {
        return $this->belongsTo(Commune::class, 'commune_id');
    }
    public function district()
    {
        return $this->belongsTo(District::class, 'district_id');
    }
    public function province()
    {
        return $this->belongsTo(Province::class, 'province_id');
    }
    public function userDetails(){
        return $this->hasMany(UserBranch::class,'user_id');
    }

    public function BranRepre()
    {
        return $this->hasOne(Branch::class,'representative_branch_id');
    }

    public function userBranchSelect()
    {
        return Branch::get()->map(function($value){
            $selected = array_search($value->id, array_column($this->userDetails->toArray(), 'branch_id'));
            $representative = $this->representative_branch_id == $value->id;
            return [
                'id'      => $value->id,
                'name_en' => $value->name_en,
                'name_km' => $value->name_km,
                'selected'=> (string)$selected ==""?false:true,
                'is_representative' => (string)$representative ==""?false:true,
            ];
        });
    }

    public function branchs()
    {
        return $this->belongsTo(Branch::class, 'branch_id');
    }
}
