<?php

namespace App\Models;

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, Notifiable;

    protected $fillable = [
        'name',
        'email',
        'password',
        'role',
        'components',
        'is_active',
        'last_login_at',
    ];

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

    protected $casts = [
        'email_verified_at' => 'datetime',
        'last_login_at'     => 'datetime',
        'components'        => 'array', // JSON → array
        'is_active'         => 'boolean',
    ];

    // === Roles ===
    public const ROLE_SUPER_ADMIN = 'super_admin';
    public const ROLE_COMPONENT_USER = 'component_user';

    // === Scopes ===
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    public function scopeSuperAdmin($query)
    {
        return $query->where('role', self::ROLE_SUPER_ADMIN);
    }

    // === Helpers ===
    public function isSuperAdmin(): bool
    {
        return $this->role === self::ROLE_SUPER_ADMIN;
    }

    public function hasComponent(int $componentId): bool
    {
        return in_array((string)$componentId, $this->components ?? []);
    }

    public function hasAnyComponent(array $componentIds): bool
    {
        return !empty(array_intersect($componentIds, $this->components ?? []));
    }

    // === Update last login ===
    public function updateLastLogin(): void
    {
        $this->update(['last_login_at' => now()]);
    }
}