<?php

namespace App\Models;

use App\Enums\RecordStatus;
use App\Models\Concerns\Auditable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class SubAccount extends Model
{
    use Auditable, HasFactory, SoftDeletes;

    protected $fillable = [
        'main_account_id', 'name', 'code', 'phone', 'email', 'status', 'notes',
    ];

    protected $casts = [
        'status' => RecordStatus::class,
    ];

    public function mainAccount(): BelongsTo
    {
        return $this->belongsTo(MainAccount::class);
    }

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

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

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

    public function scopeSearch($query, ?string $term)
    {
        if (! $term) {
            return $query;
        }

        return $query->where(function ($q) use ($term) {
            $q->where('name', 'like', "%{$term}%")
                ->orWhere('code', 'like', "%{$term}%");
        });
    }
}
