<?php

namespace App\Models\CRM;

use App\Enums\AddressType;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Relations\MorphOne;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Company extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'business_name',
        'short_name',
        'mb',
        'pib',
        'email',
        'phone',
        'mobile',
        'status',
    ];


    protected static function booted()
    {
        parent::booted();

        static::created(function ($company) {
            // Check if an Entity already exists for this Company
            if (!$company->entity()->exists()) {
                $company->entity()->create();
            }
        });

        static::deleting(function ($company) {
            // Soft delete the related Entity
            if ($company->entity) {
                $company->entity->delete();
            }
        });
    }

    public function entity(): MorphOne
    {
        return $this->morphOne(Entity::class, 'entityable');
    }


    public function addresses()
    {
        return $this->morphMany(Address::class, 'addressable');
    }

    public function lastActiveResidence()
    {
        return $this->morphOne(Address::class, 'addressable')
            ->where('type', AddressType::Residence->value)
            ->active()
            ->latest();
    }

    public function lastActiveMailing()
    {
        return $this->morphOne(Address::class, 'addressable')
            ->where('type', AddressType::Mailing->value)
            ->active()
            ->latest();
    }
}
