<?php

if (!defined('ABSPATH')) { exit; }

class AIEO_Order_Document_Proforma extends AIEO_Order_Document_Base {

    public function type()  { return 'proforma'; }
    public function label() { return __('Proforma invoice', 'ai-eshop-optimizer'); }

    public function is_enabled_for($order) {
        $cfg = AIEO_Fulfillment_Settings::get('documents.proforma', array());
        return is_array($cfg) ? !empty($cfg['enabled']) : false; 
    }

    public function resolve_number($order) {
        $cfg      = (array) AIEO_Fulfillment_Settings::get('documents.proforma', array());
        $strategy = isset($cfg['number_strategy']) ? (string) $cfg['number_strategy'] : 'separate_sequence';
        if ($strategy === 'order_number') {
            return 'PRO-' . (string) $order->get_order_number();
        }
        $year   = !empty($cfg['reset_yearly']) ? (int) gmdate('Y') : 0;
        $start  = isset($cfg['start_at']) ? (int) $cfg['start_at'] : 1;
        $seq    = AIEO_Fulfillment_Documents::next_sequence_value('proforma', $year, $start);
        $prefix = isset($cfg['prefix'])  ? (string) $cfg['prefix']  : 'PRO-';
        $suffix = isset($cfg['suffix'])  ? (string) $cfg['suffix']  : '';
        $padding = isset($cfg['padding']) ? max(0, (int) $cfg['padding']) : 0;
        $body    = $padding > 0 ? str_pad((string) $seq, $padding, '0', STR_PAD_LEFT) : (string) $seq;
        return $prefix . $body . $suffix;
    }
}

add_filter('aieo_fulfillment_documents', static function (array $docs) {
    if (!isset($docs['proforma']) && class_exists('AIEO_Order_Document_Proforma')) {
        $docs['proforma'] = new AIEO_Order_Document_Proforma();
    }
    return $docs;
});
