<?php

namespace App\Models;

use App\Enums\Role;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use HasFactory;
    use Notifiable;

    protected $fillable = [
        'name',
        'email',
        'password',
        'phone',
        'job_title',
        'role',
        'status',
        'approved_at',
    ];

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

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

    public function consultantProfile()
    {
        return $this->hasOne(ConsultantProfile::class);
    }

    public function affiliateProfile()
    {
        return $this->hasOne(AffiliateProfile::class);
    }

    public function isApproved(): bool
    {
        return $this->status === 'approved';
    }

    public function isExecutive(): bool
    {
        return $this->role === Role::Executive->value;
    }

    public function isAffiliate(): bool
    {
        return $this->role === Role::AffiliateConsultant->value;
    }

    public function isResident(): bool
    {
        return $this->role === Role::ResidentConsultant->value;
    }

    public function canAccessAffiliateScopedModel(object $model): bool
    {
        if ($this->isExecutive()) {
            return true;
        }

        $affiliateId = $model->affiliate_user_id ?? null;
        $ownerId = $model->owner_user_id ?? null;
        $assignedUserId = $model->assigned_user_id ?? null;

        if ($this->isAffiliate()) {
            return $affiliateId === $this->id || $ownerId === $this->id;
        }

        if ($this->isResident()) {
            return in_array($this->id, [$ownerId, $assignedUserId], true);
        }

        return false;
    }
}
