<?php

namespace App\Models;

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

class User extends Authenticatable implements FilamentUser
{
    /** @use HasFactory<UserFactory> */
    use HasFactory, HasRoles, Notifiable;

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

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

    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
            'is_active' => 'boolean',
        ];
    }

    public function canAccessPanel(Panel $panel): bool
    {
        if (! $this->is_active) {
            return false;
        }

        return match ($panel->getId()) {
            'admin' => $this->hasAnyRole(['super_admin', 'admin']),
            'real-estate' => $this->hasAnyRole(['super_admin', 're_admin', 're_sales_agent', 're_accountant']),
            'construction' => $this->hasAnyRole(['super_admin', 'construction_admin', 'construction_engineer', 'construction_accountant']),
            default => false,
        };
    }

    public function homePanelPath(): string
    {
        if ($this->hasAnyRole(['super_admin', 'admin'])) {
            return '/admin';
        }

        if ($this->hasAnyRole(['re_admin', 're_sales_agent', 're_accountant'])) {
            return '/real-estate';
        }

        if ($this->hasAnyRole(['construction_admin', 'construction_engineer', 'construction_accountant'])) {
            return '/construction';
        }

        return '/login';
    }

    public function homePanelLoginPath(): string
    {
        return rtrim($this->homePanelPath(), '/') . '/login';
    }

    public function assignedLeads(): HasMany
    {
        return $this->hasMany(Lead::class, 'assigned_to');
    }

    public function assignedClients(): HasMany
    {
        return $this->hasMany(Client::class, 'assigned_to');
    }

    public function dailyProgressReports(): HasMany
    {
        return $this->hasMany(DailyProgressReport::class);
    }
}
