<?php

namespace App\Services;

use App\Models\Billing;
use Illuminate\Support\Carbon;

/**
 * Penomoran invoice billing (RPD BR-02).
 *
 * Format: DDMMYYYY + 4 digit urut harian (mis. 2001210001), direset setiap hari.
 */
class InvoiceService
{
    /**
     * Hasilkan nomor invoice unik untuk hari ini.
     */
    public function generate(?Carbon $date = null): string
    {
        $date = $date ?? now();

        $prefix = $date->format('dmY');

        $last = Billing::whereDate('created_at', $date->toDateString())
            ->where('no_invoice', 'like', $prefix.'%')
            ->max('no_invoice');

        $sequence = $last ? ((int) substr($last, -4)) + 1 : 1;

        return $prefix.str_pad((string) $sequence, 4, '0', STR_PAD_LEFT);
    }
}
