<?php
/**
 * @package DhlPolska\ShippingMethod
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use DhlPolska\Shipment\DhlServices;
use DhlPolska\ShippingMethod\DhlInstanceSettings;
use DhlPolska\ShippingMethod\DhlShippingMethod;

$service_field_id    = 'woocommerce_' . DhlShippingMethod::SHIPPING_METHOD_ID . '_' . DhlInstanceSettings::OPTION_SERVICE;
$point_type_field_id = 'woocommerce_' . DhlShippingMethod::SHIPPING_METHOD_ID . '_' . DhlInstanceSettings::OPTION_POINT_TYPE;
?>
<script type="text/javascript">
	jQuery( function ( $ ) {
		function dhl_polska_toggle_point_type( context ) {
			var container = context || document;
			var service_field = $( container ).find( '#<?php echo esc_attr( $service_field_id ); ?>' );
			var point_type_field = $( container ).find( '#<?php echo esc_attr( $point_type_field_id ); ?>' );

			if ( ! service_field.length || ! point_type_field.length ) {
				return;
			}

			var should_show = service_field.val() === '<?php echo esc_attr( DhlServices::SERVICE_POINT ); ?>';
			point_type_field.closest( 'tr' ).toggle( should_show );
		}

		$( document.body ).on( 'change', '#<?php echo esc_attr( $service_field_id ); ?>', function () {
			dhl_polska_toggle_point_type( $( this ).closest( 'form' ) );
		} );

		$( document.body ).on( 'wc_backbone_modal_loaded', function ( event, target ) {
			if ( target === 'wc-modal-shipping-method-settings' ) {
				dhl_polska_toggle_point_type( $( '.wc-backbone-modal-content' ) );
			}
		} );

		dhl_polska_toggle_point_type( document );
	} );
</script>
