<?php

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

class AIEO_Order_Document_Credit_Note extends AIEO_Order_Document_Base {

    public function type()  { return 'credit-note'; }
    public function label() { return __('Credit note', 'ai-eshop-optimizer'); }

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

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

    public function resolve_number($order) {
        $cfg      = (array) AIEO_Fulfillment_Settings::get('documents.credit-note', array());
        $strategy = isset($cfg['number_strategy']) ? (string) $cfg['number_strategy'] : 'separate_sequence';
        if ($strategy === 'order_number') {
            return 'CN-' . (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('credit-note', $year, $start);
        $prefix = isset($cfg['prefix'])  ? (string) $cfg['prefix']  : 'CN-';
        $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;
    }

    
    public static function register() {
        add_action('woocommerce_order_refunded', array(__CLASS__, 'on_refund'), 20, 2);
    }

    public static function on_refund($order_id, $refund_id) {
        
        
        
        
        $cfg = (array) AIEO_Fulfillment_Settings::get('documents.credit-note', array());
        if (empty($cfg['auto_on_refund'])) { return; }

        $order = function_exists('wc_get_order') ? wc_get_order((int) $order_id) : null;
        if (!$order) { return; }

        $doc = new self();
        if (!$doc->is_enabled_for($order)) { return; }
        $doc->generate($order, array('force_regenerate' => true));
    }
}

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

if (class_exists('AIEO_Order_Document_Credit_Note')) {
    AIEO_Order_Document_Credit_Note::register();
}
