<?php

namespace App\Models;

use App\Models\User_details;
use Illuminate\Support\Carbon;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Traits\HasRoles;
use Illuminate\Notifications\Notifiable;
use Spatie\Permission\Models\Permission;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Spatie\Permission\Contracts\Role as ContractsRole;
use Illuminate\Foundation\Auth\User as Authenticatable;


class User extends Authenticatable
{
    use HasFactory, Notifiable, HasRoles;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $guarded = [
        'id'
    ];

    /**
     * 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 userdetails()
    {
        return $this->hasOne(User_details::class, 'user_id', 'id');
    }

    public function role()
    {
        // return $this->belongsTo(Role::class,'model_id',);
        return $this->belongsToMany(Role::class, 'model_has_roles', 'model_id', 'role_id');
    }

    // public function permissions()
    // {
    //     return $this->belongsToMany(Permission::class,'permission_id','role_id');
    // }

    public function resellers()
    {
        return $this->belongsToMany(Reseller::class);
    }

    public function pops()
    {
        return $this->belongsToMany(Pop::class);
    }



    public function tokens()
    {
        $today_start = Carbon::now()->format('Y-m-d 00:00:00');
        $today_end = Carbon::now()->format('Y-m-d 23:59:59');
        return $this->hasMany(Token::class, 'createdBy')
            ->where('tokens.created_at', '>', $today_start)
            ->where('tokens.created_at', '<', $today_end);
    }

    static function onlinePaymentUser($name)
    {
        $user = User::where('name', $name)->first();
        if ($user) {
            return $user;
        } else {
            $user = User::create([
                'name'      => $name,
                'email'     => $name . '@demo.com',
                'password'  => bcrypt('YetFix@2022AutoPayment'),
                'user_accounting_status' => 'yes',
                'isActive' => 'yes'
            ]);

            User_details::create([
                'user_id' => $user->id,
                'company' => $name,
                'user_status' => 'active'
            ]);
            return $user;
        }
    }


    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }
}
