<?php
declare(strict_types=1);

namespace App\Modules\Procurement\Services;

use App\Core\App;

final class ProcurementNumberGenerator
{
    public static function nextPRNumber(): string
    {
        return self::generate('PR', 'purchase_requisitions', 'pr_number');
    }

    public static function nextGRNNumber(): string
    {
        return self::generate('GRN', 'goods_received_notes', 'grn_number');
    }

    public static function nextInvoiceNumber(): string
    {
        return self::generate('VINV', 'vendor_invoices', 'internal_number');
    }

    public static function nextPaymentNumber(): string
    {
        return self::generate('VPAY', 'vendor_payments', 'payment_number');
    }

    public static function nextRTVNumber(): string
    {
        return self::generate('RTV', 'return_to_vendor', 'rtv_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);
    }
}
