<?php

/**
 * Customizations for the online solution.
 *
 * @package northmill-online-shared
 */
declare (strict_types=1);
namespace Northmill_Online_Shared_Checkout\Northmill_Online_Shared\Modules\Admin\Pages\Page\Admin_Sync_Settings;

use Northmill_Online_Shared_Checkout\Northmill_Online_Shared\Modules\Sync\Orders\Models\Order_Base_Model;
use WC_Email;
use WC_Order;
defined('ABSPATH') || exit;
/**
 * Class Online_Solution_Customizations
 */
readonly class Online_Solution_Customizations
{
    /**
     * Constructor.
     *
     * @param Abstract_Online_Solution_Settings_Sync $syncer The syncer.
     */
    public function __construct(private Abstract_Online_Solution_Settings_Sync $syncer)
    {
        add_filter('woocommerce_order_number', array($this, 'filter_woocommerce_order_number'));
        add_filter('moreflo_sync_order_to_moreflo_order', array($this, 'filter_moreflo_order'), 10, 2);
        add_filter('nmf_sync_income_account_codes_api_payment_source_arg_1', array($this->syncer, 'get_income_account_code_sync_api_payment_source_arg_1'), 10, 0);
        add_filter('woocommerce_email_format_string', array($this, 'custom_email_placeholders'), 10, 2);
    }
    /**
     * Filter the WooCommerce order number.
     *
     * @param int|string $order_id The order ID.
     *
     * @return string
     */
    public function filter_woocommerce_order_number(int|string $order_id): string
    {
        $prefix = $this->syncer->get_order_number_prefix();
        if (!empty($prefix)) {
            $order_id = $prefix . '-' . $order_id;
        }
        return $order_id;
    }
    /**
     * Adds order info when transforming wc order to mf order
     *
     * @param array $mf_order Current order data to be sent to Hub.
     * @param int   $wc_order_id The WooCommerce order ID.
     *
     * @return array
     */
    public function filter_moreflo_order(array $mf_order, int $wc_order_id): array
    {
        $wc_order = wc_get_order($wc_order_id);
        if (isset($mf_order['State']) && 'Delivered' === $mf_order['State']) {
            if ('processing' === $wc_order->get_status()) {
                $mf_order['State'] = 'ReadyForHandOut';
            }
        }
        return $mf_order;
    }
    /**
     * Custom email placeholders.
     *
     * @param string   $email_string The email format string.
     * @param WC_Email $email        The email object.
     *
     * @return string
     */
    public function custom_email_placeholders(string $email_string, WC_Email $email): string
    {
        /**
         * Order for email.
         *
         * @var WC_Order $order
         */
        $placeholder = '{hub_order_id}';
        $order = $email->object;
        $order_model = new Order_Base_Model($order);
        $value = $order_model->get_hub_order_number();
        return is_null($value) ? $email_string : str_replace($placeholder, $value, $email_string);
    }
}
