<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    /** @use HasFactory<\Database\Factories\UserFactory> */
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var list<string>
     */
    protected $fillable = [
        'name',
        'email',
        'username',
        'password',
        'last_seen_at',
        'is_admin',
        'two_factor_enabled',
        'two_factor_secret',
        'two_factor_pending_secret',
    ];

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

    /**
     * Get the attributes that should be cast.
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
            'is_admin' => 'boolean',
            'two_factor_enabled' => 'boolean',
        ];
    }

    public function roles()
    {
        return $this->belongsToMany(Role::class, 'user_role');
    }

    public function employee()
    {
        return $this->hasOne(Employee::class);
    }

    public function createdPenalties()
    {
        return $this->hasMany(EmployeePenalty::class, 'created_by');
    }

    public function createdBonuses()
    {
        return $this->hasMany(EmployeeBonus::class, 'created_by');
    }

    public function createdWithdrawals()
    {
        return $this->hasMany(EmployeeWithdrawal::class, 'created_by');
    }

    public function hasPermission(string $permissionKey): bool
    {
        $username = strtolower((string) $this->username);

        if ($this->is_admin || $username === 'admin') {
            return true;
        }

        $this->loadMissing('roles.permissions');

        if ($this->roles->contains(fn ($role) => in_array($role->key, ['super_admin', 'admin'], true))) {
            return true;
        }

        foreach ($this->roles as $role) {
            foreach ($role->permissions as $permission) {
                if ($permission->key === $permissionKey) {
                    return true;
                }
            }
        }

        return false;
    }

    public function hasAnyPermission(array $permissionKeys): bool
    {
        foreach ($permissionKeys as $permissionKey) {
            if ($this->hasPermission($permissionKey)) {
                return true;
            }
        }

        return false;
    }
}
