<?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;

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

    /**
     * The attributes that are mass assignable.
     *
     * @var list<string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'role',
        'permissions',
    ];


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

public function isAdmin(): bool
    {
        return ($this->role ?? 'admin') === 'admin';
    }

    public function isAgent(): bool
    {
        return ($this->role ?? '') === 'agent';
    }

    public function hasPermission(string $permission): bool
    {
        // Admin always has access
        if ($this->isAdmin()) {
            return true;
        }

        // Agents can always use tracking (existing behavior)
        if ($this->isAgent() && $permission === 'track') {
            return true;
        }

        $perms = $this->permissions ?? [];

        // If permissions stored as JSON string, decode safely
        if (is_string($perms)) {
            $decoded = json_decode($perms, true);
            $perms = is_array($decoded) ? $decoded : [];
        }

        if (!is_array($perms)) {
            $perms = [];
        }

        return in_array($permission, $perms, true);
    }

    public function anyPermissions(): bool
    {
        $perms = $this->permissions ?? [];
        return is_array($perms) && count($perms) > 0;
    }

    /**
     * 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',
            'permissions' => 'array',
        ];
    }
}
