<?php

// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedNamespaceFound -- APD is the established namespace shared with the Pro add-on and retained for backward compatibility.
namespace APD\WooCommerce;

use APD\Admin\AdminSettings;
use APD\Container;
use APD\Contracts\ServiceProviderInterface;

defined('ABSPATH') || exit;

class WooServiceProvider implements ServiceProviderInterface
{
    public function __construct(protected Container $container)
    {
    }

    public function register() : void
    {
    }

    public function boot() : void
    {
        add_action('plugins_loaded', [$this, 'bootWhenWooReady'], 20);
    }

    public function bootWhenWooReady() : void
    {
        $settings = $this->container->get(AdminSettings::class)->all();
        if (($settings['enable_woocommerce_binding'] ?? '1') !== '1') {
            return;
        }

        if (! WooDetector::isAvailable()) {
            return;
        }

        (new ProductIntegration())->boot();
        $cartIntegration = new CartIntegration();
        $cartIntegration->boot();
        (new StoreApiIntegration())->boot();
        (new AdminOrderMetaBox())->register();
        $orderIntegration = new OrderIntegration();
        add_action('woocommerce_before_calculate_totals', [new PriceIntegration(), 'boot']);
        add_action('woocommerce_checkout_create_order_line_item', [$orderIntegration, 'boot'], 10, 4);
        add_action('woocommerce_checkout_order_created', [$orderIntegration, 'finalizeOrderLinks'], 20, 1);
        add_action('woocommerce_store_api_checkout_order_processed', [$orderIntegration, 'finalizeOrderLinks'], 20, 1);
        add_action('woocommerce_order_item_meta_end', [$orderIntegration, 'renderResumeLink'], 10, 4);
        add_filter('woocommerce_order_item_permalink', [$orderIntegration, 'filterOrderItemPermalink'], 10, 3);
        add_filter('woocommerce_order_item_name', [$orderIntegration, 'filterOrderItemName'], 10, 3);
        add_action('wp_enqueue_scripts', [$orderIntegration, 'enqueueCustomerOrderAssets'], 30);
        add_action('woocommerce_view_order', [$orderIntegration, 'renderCustomerOrderExperience'], 20);
        add_action('woocommerce_thankyou', [$orderIntegration, 'renderCustomerOrderExperience'], 20);
        add_filter('woocommerce_my_account_my_orders_actions', [$orderIntegration, 'filterMyAccountOrderActions'], 20, 2);
    }
}
