<?php

namespace App\Models;

use Filament\Models\Contracts\FilamentUser;
use Filament\Panel;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Spatie\Permission\Traits\HasRoles;

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

    protected $fillable = [
        'name',
        'email',
        'phone',
        'password',
        'role',
        'is_active',
        'created_by',
    ];

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

    protected $casts = [
        'email_verified_at' => 'datetime',
        'password'          => 'hashed',
        'is_active'         => 'boolean',
    ];

    // ── Filament gate ─────────────────────────────────────────────
    //
    // This is the ONLY check Filament runs before showing /admin.
    // Previously this was tied to isStaff() which was correct,
    // but the issue was the LOGIN used email+password while some
    // accounts were created with only phone. Fixed: allow login
    // by phone OR email in AuthController.
    //
    public function canAccessPanel(Panel $panel): bool
    {
        return $this->isStaff() && $this->is_active;
    }

    // ── Role helpers ──────────────────────────────────────────────

    /**
     * Returns true for any account that should use /admin.
     * Deliberately broad — super_admin, admin, AND staff.
     */
    public function isStaff(): bool
    {
        return in_array($this->role, [
            'super_admin', 'admin', 'accountant',
            'cashier', 'warehouse', 'staff', 'director',
        ]);
    }

    public function isSuperAdmin(): bool
    {
        return $this->role === 'super_admin';
    }

    // ── Relationships ─────────────────────────────────────────────

    public function createdBy()
    {
        return $this->belongsTo(User::class, 'created_by');
    }
}