<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use App\Models\Branch\Branch;
use App\Models\Order\Loan\LoanOrder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Nova\Actions\Actionable;
use Laravel\Sanctum\HasApiTokens;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable
{
    use Actionable;
    use HasApiTokens;
    use HasFactory;
    use HasRoles;
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'username',
        'name',
        'email',
        'phone',
        'email_verified_at',
        'phone_verified_at',
        'password',
        'locale',
        'active',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
        'password' => 'hashed',
    ];

    /**
     * Branches associated with user
     */
    public function branches(): BelongsToMany
    {
        return $this->belongsToMany(Branch::class);
    }

    /**
     * Loan orders user created
     */
    public function loanOrders(): HasMany
    {
        return $this->hasMany(LoanOrder::class);
    }

    /**
     * Check if user is me.
     */
    public function isMe(): bool
    {
        return $this->email === 'nurmuhammet@mail.com';
    }

    /**
     * Check if user is super admin.
     */
    public function isSuperAdmin(): bool
    {
        if ($this->isMe()) {
            return true;
        }

        return $this->hasRole('superadmin');
    }

    /**
     * Check if user is admin.
     */
    public function isAdmin(): bool
    {
        if ($this->isMe()) {
            return true;
        }

        return $this->hasRole(['king', 'superadmin', 'admin']);
    }

    /**
     * Check if user is operator.
     */
    public function isOperator(): bool
    {
        return $this->hasRole('operator');
    }

    /**
     * Is System User
     */
    public function isSystemUser(): bool
    {
        return $this->isAdmin() || $this->isOperator();
    }

    /**
     * Check if user owns loan order.
     */
    public function ownsLoanOrder(LoanOrder $loanOrder): bool
    {
        return $this->id === $loanOrder->user_id;
    }

    /**
     * Check if phone is verified
     */
    public function phoneIsVerified(): bool
    {
        return ! is_null($this->phone_verified_at);
    }
}
