<?php
/**
 * ComptaFlow - Service de numerotation automatique
 * Format : PREFIXE-ANNEE-NUMERO (ex: FAC-2026-001)
 */

namespace ComptaFlowPro\Services;

defined('ABSPATH') || exit;

class NumberingService {

    /**
     * Generer le prochain numero de facture
     */
    public static function getNextInvoiceNumber(): string {
        $settings = get_option('comptaflow_company_settings', []);
        $prefix = $settings['invoice_prefix'] ?? 'FAC';

        return self::generateNumber($prefix, 'invoices', 'invoice_number');
    }

    /**
     * Generer un numero unique
     */
    private static function generateNumber(string $prefix, string $table, string $column): string {
        global $wpdb;

        $year = gmdate('Y');
        $table_name = $wpdb->prefix . 'cfp_' . $table;
        $pattern = $prefix . '-' . $year . '-%';

        $last_number = $wpdb->get_var($wpdb->prepare(
            "SELECT {$column} FROM {$table_name}
             WHERE {$column} LIKE %s
             ORDER BY id DESC
             LIMIT 1",
            $pattern
        ));

        if ($last_number) {
            $parts = explode('-', $last_number);
            $sequence = isset($parts[2]) ? intval($parts[2]) : 0;
            $next_sequence = $sequence + 1;
        } else {
            $next_sequence = 1;
        }

        $formatted_sequence = str_pad($next_sequence, 3, '0', STR_PAD_LEFT);

        return $prefix . '-' . $year . '-' . $formatted_sequence;
    }

    /**
     * Verifier si un numero de facture existe deja
     */
    public static function invoiceNumberExists(string $number): bool {
        global $wpdb;
        $table = $wpdb->prefix . 'cfp_invoices';

        $exists = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM {$table} WHERE invoice_number = %s",
            $number
        ));

        return (int) $exists > 0;
    }
}
