<?php
declare(strict_types=1);

namespace App\Modules\Sales\Services;

use App\Core\App;

final class InvoiceNumberGenerator
{
    /**
     * Generate invoice number: INV-YYYY-NNNNNN
     */
    public static function nextInvoiceNumber(): string
    {
        return self::generate('INV', 'sales', 'invoice_number');
    }

    /**
     * Generate refund number: REF-YYYY-NNNNNN
     */
    public static function nextRefundNumber(): string
    {
        return self::generate('REF', 'sale_refunds', 'refund_number');
    }

    private static function generate(string $prefix, string $table, string $column): string
    {
        $db = App::getInstance()->db();
        $year = date('Y');
        $pattern = $prefix . '-' . $year . '-';

        $last = $db->selectOne(
            "SELECT `{$column}` FROM `{$table}` WHERE `{$column}` LIKE ? ORDER BY `id` DESC LIMIT 1",
            [$pattern . '%']
        );

        if ($last) {
            $parts = explode('-', $last[$column]);
            $seq = (int) end($parts) + 1;
        } else {
            $seq = 1;
        }

        return $pattern . str_pad((string) $seq, 6, '0', STR_PAD_LEFT);
    }
}
