<?php
/**
 * Shipping zones functions.
 *
 * @package northmill-online-shared
 */

declare(strict_types=1);

namespace Northmill_Online_Shared\Abstracts\Hub_API\Hub_Accounts\Shipping;

use WC_Shipping_Zone;
use WC_Shipping_Zones;

defined( 'ABSPATH' ) || exit;

/**
 * Shipping zones class.
 */
class Shipping_Zones {

	/**
	 * Get all shipping zones, including the default zone.
	 *
	 * @return array
	 */
	public static function get_all_zones(): array {
		static $shipping_zones;

		if ( isset( $shipping_zones ) ) {
			return $shipping_zones;
		}

		$zones = WC_Shipping_Zones::get_zones();

		$default_zone                        = new WC_Shipping_Zone( 0 );
		$zones[0]                            = $default_zone->get_data();
		$zones[0]['zone_id']                 = $default_zone->get_id();
		$zones[0]['formatted_zone_location'] = $default_zone->get_formatted_location();
		$zones[0]['shipping_methods']        = $default_zone->get_shipping_methods();

		ksort( $zones );

		$shipping_zones = $zones;

		return $zones;
	}

	/**
	 * Get multi select for all zone shipping methods.
	 *
	 * @param string $select_name Select name.
	 * @param string $select_class Select class.
	 * @param array  $current_values Current values.
	 * @param bool   $is_required Whether the select should be made required.
	 *
	 * @return string HTML.
	 */
	public static function get_shipping_methods_multi_select(
		string $select_name,
		string $select_class,
		array $current_values = array(),
		bool $is_required = false
	): string {
		$shipping_zones = self::get_all_zones();

		$is_multiple_zones = count( $shipping_zones ) > 1;

		ob_start();

		echo '<select multiple="multiple" name="' . esc_attr( $select_name ) . '" id="' . esc_attr( $select_name ) . '" class="' . esc_attr( $select_class ) . '" ' . ( $is_required ? 'required' : '' ) . '>';
		foreach ( $shipping_zones as $zone ) {
			$zone_shipping_methods = $zone['shipping_methods'] ?? array();
			if ( isset( $zone['id'] ) && ! empty( $zone_shipping_methods ) ) {
				echo $is_multiple_zones ? '<optgroup label="' . esc_attr( $zone['zone_name'] ) . '">' : '';
				foreach ( $zone_shipping_methods as $shipping_method ) {
					if (
						! isset( $shipping_method->id ) ||
						! isset( $shipping_method->instance_id )
					) {
						continue;
					}
					$shipping_method_id    = $zone['id'] . ':' . $shipping_method->id . ':' . $shipping_method->instance_id;
					$shipping_method_title = $shipping_method->title ?? '';
					$selected              = false;
					if ( in_array( $shipping_method_id, $current_values, true ) ) {
						$selected = true;
					}
					echo '<option value="' . esc_attr( $shipping_method_id ) . '" ' . selected( $selected ) . '>' . esc_html( $shipping_method_title ) . '</option>';
				}
				echo $is_multiple_zones ? '</optgroup>' : '';
			}
		}
		echo '</select>';

		return ob_get_clean();
	}
}
