<?php

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

class AIEO_Order_Document_Invoice extends AIEO_Order_Document_Base {

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

    public function default_attached_to_emails() {
        return array('customer_completed_order');
    }

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

    public function resolve_number($order) {
        $cfg      = (array) AIEO_Fulfillment_Settings::get('documents.invoice', array());
        $strategy = isset($cfg['number_strategy']) ? (string) $cfg['number_strategy'] : 'order_number';

        if ($strategy === 'separate_sequence') {
            $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('invoice', $year, $start);
            $prefix = isset($cfg['prefix'])  ? (string) $cfg['prefix']  : '';
            $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;
        }
        return (string) $order->get_order_number();
    }
}

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