<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Business extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'logo',
        'email',
        'phone',
        'address',
        'city',
        'country',
        'tin',
        'vat_number',
        'currency',
        'payment_details',
        'created_by',
    ];

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

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

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

    public function nextInvoiceNumber(): string
{
    $lastInvoice = $this->invoices()
        ->withoutGlobalScopes()
        ->orderByDesc('id')
        ->first();

    $nextNumber = $lastInvoice
        ? ((int) substr($lastInvoice->invoice_number, 4)) + 1
        : 1;

    return 'INV-' . str_pad($nextNumber, 4, '0', STR_PAD_LEFT);
}
}