<?php
/**
 * Class PointAssetsCheckout
 *
 * @package DhlPolska\Point
 */

namespace DhlPolska\Point;

use DhlPolskaVendor\WPDesk\PluginBuilder\Plugin\Hookable;

/**
 * Adds assets for DHL point map on checkout.
 */
class PointAssetsCheckout implements Hookable {
	public const ASSET_HANDLE = 'dhl-polska-point';

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

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

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

	/**
	 * PointAssetsCheckout constructor.
	 *
	 * @param string $assets_url      .
	 * @param string $scripts_version .
	 * @param string $map_url         .
	 */
	public function __construct( $assets_url, $scripts_version, $map_url ) {
		$this->assets_url      = $assets_url;
		$this->scripts_version = $scripts_version;
		$this->map_url         = $map_url;
	}

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

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

		$suffix = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';

		wp_enqueue_script( self::ASSET_HANDLE, $this->assets_url . 'js/choosing-point' . $suffix . '.js', [], $this->scripts_version, true );
		wp_localize_script( self::ASSET_HANDLE, '__jsDHLPolskaCheckoutVars', $this->get_localize_script() );

		wp_enqueue_style( self::ASSET_HANDLE, $this->assets_url . 'css/choosing-point' . $suffix . '.css', [], $this->scripts_version );
	}

	/**
	 * @return bool
	 */
	private function should_add_checkout_assets(): bool {
		return is_checkout();
	}

	/**
	 * @return array<string, string|array>
	 */
	private function get_localize_script(): array {
		return [
			'map_url'    => $this->map_url,
			'locale'     => get_user_locale(),
			'point_type' => $this->get_point_type_from_session(),
			'l10n'       => [
				'api_error'   => __( 'Błąd komunikacji z mapą DHL. Wybierz punkt odbioru ponownie lub skontaktuj się z obsługą sklepu.', 'dhl-polska' ),
				'close_popup' => __( 'Zamknij mapę', 'dhl-polska' ),
			],
		];
	}

	/**
	 * @return string
	 */
	private function get_point_type_from_session(): string {
		$wc      = WC();
		$session = $wc->session;

		$point_types = $session->get( CheckoutChoosePointField::SESSION_SERVICE_POINT_TYPES, [] );
		if ( ! is_array( $point_types ) ) {
			return '';
		}

		$chosen_methods = wp_parse_list( $session->get( 'chosen_shipping_methods' ) );
		foreach ( $chosen_methods as $method ) {
			if ( isset( $point_types[ $method ] ) ) {
				return (string) $point_types[ $method ];
			}
		}

		return '';
	}
}
