<?php
/**
 * Class FlexibleShippingIntegration
 *
 * @package DhlPolska\Integration\FlexibleShipping
 */

namespace DhlPolska\Integration\FlexibleShipping;

use DhlPolska\Shipment\DhlServices;
use DhlPolska\Shipment\ShipmentData;
use DhlPolska\ShippingMethod;
use DhlPolska\ShippingMethod\DhlInstanceSettings;
use DhlPolska\Shipment\ShipmentTypes;
use DhlPolska\WooCommerceSettings\Templates\TemplatesRepository;
use DhlPolska\WooCommerceSettings\WooCommerceDHLPolskaSettings;
use DhlPolska\WooCommerceSettings\WooCommerceDHLPolskaSettingsFields;
use DhlPolskaVendor\WPDesk\PluginBuilder\Plugin\Hookable;

/**
 * Integration with Flexible Shipping.
 */
class FlexibleShippingIntegration implements Hookable {

	public const INTEGRATION_ID = 'dhl_polska';

	private const FIELD_SERVICE    = self::INTEGRATION_ID . '_' . ShipmentData::OPTION_SERVICE;
	private const FIELD_POINT_TYPE = self::INTEGRATION_ID . '_' . ShipmentData::OPTION_POINT_TYPE;
	private const FIELD_TEMPLATE   = self::INTEGRATION_ID . '_' . ShipmentData::OPTION_TEMPLATE;
	private const FIELD_SHOW_LOGO  = self::INTEGRATION_ID . '_show_logo';

	/**
	 * @return void
	 */
	public function hooks() {
		add_filter( 'flexible_shipping_integration_options', [ $this, 'add_integration' ] );
		add_filter( 'flexible_shipping_method_settings', [ $this, 'add_integration_fields' ], 10, 2 );
		add_action( 'flexible_shipping_method_script', [ $this, 'add_integration_scripts' ] );
	}

	/**
	 * @return void
	 */
	public function add_integration_scripts() {
		include __DIR__ . '/views/html-fs-scripts.php';
	}

	/**
	 * @param array<string, string> $options .
	 *
	 * @return array<string, string>
	 */
	public function add_integration( array $options ): array {
		$options[ self::INTEGRATION_ID ] = __( 'DHL Polska', 'dhl-polska' );

		return $options;
	}

	/**
	 * @param array<string, array<string, mixed>> $fields                   .
	 * @param array<string, string>               $shipping_method_settings .
	 *
	 * @return array<string, array<string, mixed>>
	 */
	public function add_integration_fields( array $fields, array $shipping_method_settings ): array {
		$shipment_types = new ShipmentTypes();
		$template_field = ( new DhlInstanceSettings(
			new TemplatesRepository( new WooCommerceDHLPolskaSettings(), $shipment_types ),
			$shipment_types
		) )->get_settings_fields()[ DhlInstanceSettings::OPTION_TEMPLATE ];

		$integration_fields = [
			self::FIELD_SHOW_LOGO => [
				'title'   => __( 'Logo DHL', 'dhl-polska' ),
				'type'    => 'checkbox',
				'label'   => __( 'Wyświetl logo DHL pod nazwą metody wysyłki.', 'dhl-polska' ),
				'default' => 'no',
				'class'   => 'js--field-dhl_polska',
			],
			self::FIELD_SERVICE => [
				'title'   => __( 'Usługa', 'dhl-polska' ),
				'type'    => 'select',
				'options' => ( new DhlServices() )->get_all_services(),
				'class'   => 'js--field-dhl_polska',
			],
		];

		if ( $this->should_show_point_type_field() ) {
			$integration_fields[ self::FIELD_POINT_TYPE ] = [
				'title'   => __( 'Typ punktu odbioru', 'dhl-polska' ),
				'type'    => 'select',
				'options' => [
					ShipmentData::POINT_TYPE_PARCELSHOP  => __( 'Punkt partnerski', 'dhl-polska' ),
					ShipmentData::POINT_TYPE_PACKSTATION => __( 'Automat paczkowy', 'dhl-polska' ),
				],
				'default' => ShipmentData::POINT_TYPE_PARCELSHOP,
				'class'   => 'js--field-dhl_polska js--field-dhl_polska-point-type',
			];
		}

		$integration_fields[ self::FIELD_TEMPLATE ] = [
			'title'    => $template_field['title'],
			'type'     => $template_field['type'],
			'options'  => $template_field['options'],
			'desc_tip' => $template_field['desc_tip'],
			'class'    => 'js--field-dhl_polska',
		];

		return array_merge( $fields, $integration_fields );
	}

	private function should_show_point_type_field(): bool {
		$instance_id = $this->get_instance_id_from_request();
		if ( null === $instance_id || 0 === $instance_id ) {
			return true;
		}

		return $this->zone_has_non_pl_countries( $instance_id );
	}

	private function get_instance_id_from_request(): ?int {
		$instance_id = filter_input( INPUT_GET, 'instance_id', FILTER_VALIDATE_INT );
		if ( false === $instance_id || null === $instance_id ) {
			$raw_instance_id = isset( $_GET['instance_id'] ) // phpcs:ignore WordPress.Security.NonceVerification.Recommended
				? sanitize_text_field( wp_unslash( $_GET['instance_id'] ) ) // phpcs:ignore WordPress.Security.NonceVerification.Recommended
				: '';
			if ( '' === $raw_instance_id ) {
				return null;
			}

			$instance_id = absint( $raw_instance_id );
		}

		return (int) $instance_id;
	}

	private function zone_has_non_pl_countries( int $instance_id ): bool {
		$zone = $this->get_zone_by_instance_id( $instance_id );
		if ( null === $zone ) {
			return true;
		}

		if ( 0 === (int) $zone->get_id() ) {
			return true;
		}

		$locations = $zone->get_zone_locations();
		if ( empty( $locations ) ) {
			return true;
		}

		if ( $this->locations_include_continent( $locations ) ) {
			return true;
		}

		$countries = $this->get_countries_from_locations( $locations );
		if ( empty( $countries ) ) {
			return true;
		}

		return $this->countries_include_non_pl( $countries );
	}

	private function get_zone_by_instance_id( int $instance_id ): ?\WC_Shipping_Zone {
		if ( ! class_exists( 'WC_Shipping_Zones' ) ) {
			return null;
		}

		$zone = \WC_Shipping_Zones::get_zone_by( 'instance_id', $instance_id );
		if ( ! $zone instanceof \WC_Shipping_Zone ) {
			return null;
		}

		return $zone;
	}

	/**
	 * @param array<int, object> $locations .
	 */
	private function locations_include_continent( array $locations ): bool {
		foreach ( $locations as $location ) {
			if ( isset( $location->type ) && 'continent' === $location->type ) {
				return true;
			}
		}

		return false;
	}

	/**
	 * @param array<int, object> $locations .
	 *
	 * @return string[]
	 */
	private function get_countries_from_locations( array $locations ): array {
		$countries = [];
		foreach ( $locations as $location ) {
			if ( ! isset( $location->type, $location->code ) ) {
				continue;
			}

			if ( 'country' === $location->type ) {
				$countries[] = (string) $location->code;
				continue;
			}

			if ( 'state' === $location->type ) {
				$parts       = explode( ':', (string) $location->code, 2 );
				$countries[] = (string) $parts[0];
			}
		}

		return array_filter( $countries, static fn ( $country ) => '' !== $country );
	}

	/**
	 * @param string[] $countries .
	 */
	private function countries_include_non_pl( array $countries ): bool {
		foreach ( $countries as $country ) {
			if ( 'PL' !== strtoupper( $country ) ) {
				return true;
			}
		}

		return false;
	}
}
