<?php
/**
 * Shipping method logo assets for checkout blocks.
 *
 * @package DhlPolska\CheckoutBlocks
 */

namespace DhlPolska\CheckoutBlocks;

use DhlPolska\Integration\FlexibleShipping\FlexibleShippingIntegration;
use DhlPolska\ShippingMethod\DhlShippingMethod;
use DhlPolskaVendor\WPDesk\PluginBuilder\Plugin\Hookable;

/**
 * Enqueue block checkout logo assets.
 */
class ShippingMethodLogoAssets implements Hookable {
	public const SCRIPT_HANDLE = 'dhl-polska-shipping-method-logo';

	/**
	 * @var string
	 */
	private $plugin_url;

	/**
	 * @var string
	 */
	private $scripts_version;

	/**
	 * @param string $plugin_url      .
	 * @param string $scripts_version .
	 */
	public function __construct( $plugin_url, $scripts_version ) {
		$this->plugin_url      = rtrim( (string) $plugin_url, '/' ) . '/';
		$this->scripts_version = $scripts_version;
	}

	/**
	 * Hooks.
	 */
	public function hooks() {
		add_action( 'wp_enqueue_scripts', [ $this, 'add_assets' ] );
	}

	/**
	 * @return void
	 */
	public function add_assets(): void {
		if ( ! $this->should_add_assets() ) {
			return;
		}

		$asset_data   = $this->get_asset_file();
		$dependencies = $asset_data['dependencies'] ?? [];
		$version      = $this->scripts_version;
		if ( ! empty( $asset_data['version'] ) ) {
			$version = $asset_data['version'] . '.' . $this->scripts_version;
		}

		wp_enqueue_script(
			self::SCRIPT_HANDLE,
			$this->plugin_url . 'build/shipping-method-logo.js',
			$dependencies,
			$version,
			true
		);

		wp_localize_script( self::SCRIPT_HANDLE, '__jsDHLPolskaShippingLogo', $this->get_localize_script() );
	}

	/**
	 * @return bool
	 */
	private function should_add_assets(): bool {
		if ( ! is_checkout() ) {
			return false;
		}

		if ( function_exists( 'has_block' ) ) {
			return has_block( 'woocommerce/checkout' );
		}

		return true;
	}

	/**
	 * @return array<string, array|string>
	 */
	private function get_asset_file(): array {
		$asset_path = dirname( __DIR__, 2 ) . '/build/shipping-method-logo.asset.php';
		if ( file_exists( $asset_path ) ) {
			$asset_data = require $asset_path;
			if ( is_array( $asset_data ) ) {
				return $asset_data;
			}
		}

		return [
			'dependencies' => [],
			'version'      => $this->scripts_version,
		];
	}

	/**
	 * @return array<string, string|array>
	 */
	private function get_localize_script(): array {
		return [
			'logo_url'       => $this->plugin_url . 'assets/images/DHL_Logo.svg',
			'logo_alt'       => __( 'DHL Polska', 'dhl-polska' ),
			'method_ids'     => [ DhlShippingMethod::SHIPPING_METHOD_ID ],
			'integration_id' => FlexibleShippingIntegration::INTEGRATION_ID,
		];
	}
}
