<?php
namespace ComptaFlowUK\Services;

defined('ABSPATH') || exit;

class NumberingService {

    public static function nextInvoiceNumber(): string {
        return self::next('invoice', 'INV');
    }

    public static function nextCreditNoteNumber(): string {
        return self::next('credit_note', 'CN');
    }

    private static function next(string $type, string $prefix): string {
        global $wpdb;
        $p = $wpdb->prefix . 'cfuk_';
        $year = gmdate('Y');
        $pattern = $prefix . '-' . $year . '-%';

        $last = $wpdb->get_var($wpdb->prepare(
            "SELECT invoice_number FROM {$p}invoices
             WHERE invoice_number LIKE %s
             ORDER BY invoice_number DESC LIMIT 1",
            $pattern
        ));

        $seq = 1;
        if ($last) {
            $parts = explode('-', $last);
            $seq = intval(end($parts)) + 1;
        }

        return $prefix . '-' . $year . '-' . str_pad($seq, 4, '0', STR_PAD_LEFT);
    }
}
