<?php
declare(strict_types=1);

namespace App\Modules\Inventory\Services;

use App\Core\App;

final class InventoryNumberGenerator
{
    /**
     * Generate a transfer number: TRF-YYYY-NNNNNN
     */
    public static function nextTransferNumber(): string
    {
        return self::generate('TRF', 'stock_transfers', 'transfer_number');
    }

    /**
     * Generate a purchase order number: PO-YYYY-NNNNNN
     */
    public static function nextPONumber(): string
    {
        return self::generate('PO', 'purchase_orders', 'po_number');
    }

    /**
     * Generate an audit number: AUD-YYYY-NNNNNN
     */
    public static function nextAuditNumber(): string
    {
        return self::generate('AUD', 'stock_audits', 'audit_number');
    }

    /**
     * Generate an asset tag: AST-YYYY-NNNNNN
     */
    public static function nextAssetTag(): string
    {
        return self::generate('AST', 'asset_register', 'asset_tag');
    }

    /**
     * Core sequence generator: PREFIX-YYYY-NNNNNN
     */
    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);
    }
}
