<?php
global $globKurier;

$inpost_id           = WC()->session->get( 'globkurier_inpost_selected_point_id' ) ?? '';
$inpost_val          = WC()->session->get( 'globkurier_inpost_selected_point_value' ) ?? '';
$inpost_lat          = WC()->session->get( 'globkurier_inpost_selected_point_latitude' ) ?? '';
$inpost_long         = WC()->session->get( 'globkurier_inpost_selected_point_longitude' ) ?? '';
$inpost_city         = WC()->session->get( 'globkurier_inpost_selected_point_city' ) ?? '';
$inpost_address      = WC()->session->get( 'globkurier_inpost_selected_point_address' ) ?? '';
$inpost_openingHours = WC()->session->get( 'globkurier_inpost_selected_point_openingHours' ) ?? '';
?>

<tr class="order-total">
	<th colspan="2" id="udi-map-td">
		<input type="hidden" name="globkurier_method_id" id="globkurier_method_id" value="<?php echo $globKurier->settings( 'inpost_method' ) ?? '' ?>">
		<input type="hidden" name="globkurier_inpost_input" id="globkurier_inpost_input" value="<?php echo $inpost_val ?>" required>
		
		<div id="globkurier_map" style="width: 100%; height: 300px"></div>
		<select type="text" style="width: 100%;" class="udi-select2" id="udi-select-inpost" name="globkurier_inpost_input_value">
			<?php
			if( isset( $inpost_id ) ){
				echo "<option value='{$inpost_id}' selected>{$inpost_val}</option>";
			}
			?>
		</select>
	</th>
</tr>


<script src="https://cdnjs.cloudflare.com/ajax/libs/js-marker-clusterer/1.0.0/markerclusterer_compiled.js"></script>
<script>
	( function ( $ ) {
		$( function () {
			let ajaxurl = data[ 'ajaxUrl' ];
			
			let map_container = 'globkurier_map';
			let poland = { lat: 52.476329, lng: 18.995734 };
			let markerCluster;
			let globkurier_map;
			
			globkurierMapInit();
			
			function globkurierMapInit(){
				globkurier_map = new google.maps.Map( document.getElementById( map_container ), {
					center: poland,
					zoom: 6,
					disableDefaultUI: true
				} );
			}
			
			<?php
			if ( $inpost_id && $inpost_val && $inpost_lat && $inpost_long && $inpost_city && $inpost_address ) {  ?>
			let lat = <?php echo $inpost_lat?>;
			let lng = <?php echo $inpost_long?>;
			let pos = { lat, lng };
			
			let contentString = `<p> Miasto: <?php echo $inpost_city ?> </p>` + `<p> Adres: <?php echo $inpost_address ?> </p>`;
			
			<?php if ($inpost_openingHours != ''){?>
			contentString += `<p> Godziny otwarcia: <?php echo $inpost_openingHours ?> </p>`;
			<?php }?>
			
			let tooltip = new google.maps.InfoWindow( {
				content: contentString
			} );
			
			let marker = new google.maps.Marker( {
				position: pos,
			} );
			
			marker.addListener( 'mouseover', () => {
				tooltip.open( globkurier_map, marker );
			} );
			
			marker.addListener( 'mouseout', () => {
				tooltip.close();
			} );
			
			marker.addListener( 'click', () => {
				$( '#globkurier_inpost_input' ).val( '<?php echo $inpost_val ?>' );
				$( '#globkurier_inpost_input_value' ).val( '<?php echo $inpost_val ?>' );
			} );
			
			globkurier_map.setZoom( 15 );
			globkurier_map.setCenter( marker.getPosition() );
			
			marker.setMap( globkurier_map );
			
			<?php } ?>
			
			$( document ).find( '.udi-select2#udi-select-inpost' ).select2( {
				placeholder: 'Znajdź punkt dostawy',
				language: {
					searching: function () {
						return 'Szukaj Paczkomat InPost';
					},
					inputTooShort: function () {
						return 'Wpisz miasto';
					},
					noResults: function () {
						return 'Brak wyników';
					},
					errorLoading: function () {
						return 'Szukanie...';
					},
					loadingMore: function () {
						return 'Szukanie...';
					},
				},
				
				ajax: {
					url: data[ 'ajaxUrl' ],
					dataType: 'json',
					data: function ( params ) {
						return {
							city: params.term,
							action: 'globkurierGetInpostPointsSelect2',
						};
					},
					processResults: function ( data ) {
						let parsedData = JSON.parse( data );
						
						let options = [];
						if ( parsedData ) {
							$.each( parsedData, function ( index, data ) {
								options.push( {
									id: data.id,
									text: data.label,
									latitude: data.latitude,
									longitude: data.longitude,
									city: data.city,
									address: data.address,
									openingHours: data.openingHours,
								} );
							} );
							
							globkurierMapInit();
							
							let markers = [];
							
							//dodanie cluster z lista wszystkich wyników wyszukiwania
							parsedData.forEach( ( d ) => {
								let lat = d.latitude;
								let lng = d.longitude;
								let pos = { lat, lng };
								
								let contentString =
									`<p> Miasto: ${ d.city } </p>` +
									`<p> Adres: ${ d.address } </p>`;
								
								if ( d.openingHours !== '' ) {
									contentString += `<p> Godziny otwarcia: ${ d.openingHours } </p>`;
								}
								
								let tooltip = new google.maps.InfoWindow( {
									content: contentString
								} );
								
								let marker = new google.maps.Marker( {
									position: pos,
								} );
								
								marker.addListener( 'mouseover', () => {
									tooltip.open( globkurier_map, marker );
								} );
								
								marker.addListener( 'mouseout', () => {
									tooltip.close();
								} );
								
								marker.addListener( 'click', () => {
									
									$( document ).find( '#globkurier_inpost_input' ).val( d.value );
									$( document ).find( '#udi-map-td .select2-selection__rendered' ).text( d.value );
									
									$.post( {
										url: ajaxurl,
										dataType: 'json',
										minLength: 3,
										data: {
											action: 'globkurierSaveInpostPointsSession',
											id: d.id,
											value: d.value,
											latitude: d.latitude,
											longitude: d.longitude,
											city: d.city,
											address: d.address,
											openingHours: d.openingHours,
										},
									} );
									
									globkurier_map.setCenter( new google.maps.LatLng( d.latitude, d.longitude ) );
									globkurier_map.setZoom( 15 );
								} );
								
								markers.push( marker );
							} );
							
							let markerCluster = new MarkerClusterer( globkurier_map, markers, { imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m' } );
							
							markerCluster.fitMapToMarkers();
						}
						return {
							results: options
						};
					},
					cache: true
				},
				minimumInputLength: 3,
			} );
			
			//dodanie markera z wybranym punktem
			$( document ).find( '.udi-select2#udi-select-inpost' ).on( 'select2:select', function ( e ) {
				$( '#globkurier_inpost_input' ).val( e.params.data.text );
				
				let lat = e.params.data.latitude;
				let lng = e.params.data.longitude;
				let pos = { lat, lng };
				let markers = [];
				
				let contentString =
					`<p> Miasto: ${ e.params.data.city } </p>` +
					`<p> Adres: ${ e.params.data.address } </p>`;
				
				contentString += `<p> Godziny otwarcia: ${ e.params.data.openingHours } </p>`;
				
				let tooltip = new google.maps.InfoWindow( {
					content: contentString
				} );
				
				let marker = new google.maps.Marker( {
					position: pos,
					map: globkurier_map,
					// icon: '',
				} );
				
				marker.addListener( 'mouseover', () => {
					tooltip.open( globkurier_map, marker );
				} );
				
				marker.addListener( 'mouseout', () => {
					tooltip.close();
				} );
				
				markers.push( marker );
				
				globkurierMapInit();
				
				markerCluster = new MarkerClusterer( globkurier_map, markers, { imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m' } );
				
				globkurier_map.setCenter(marker.getPosition());
				globkurier_map.setZoom( 15 );
				
				$.post( {
					url: data[ 'ajaxUrl' ],
					dataType: 'json',
					minLength: 3,
					data: {
						action: 'globkurierSaveInpostPointsSession',
						id: e.params.data.id,
						value: e.params.data.text,
						latitude: e.params.data.latitude,
						longitude: e.params.data.longitude,
						city: e.params.data.city,
						address: e.params.data.address,
						openingHours: e.params.data.openingHours,
					},
				} );
			} );
			
			$( document ).find( '.udi-select2#udi-select-inpost' ).on( 'results:message', function(params){
				alert(1);
				this.dropdown._resizeDropdown();
				this.dropdown._positionDropdown();
			});
			
			$( document ).find( '.udi-select2#udi-select-inpost' ).data( 'select2' ).on( 'results:message', function(params){
				this.dropdown._resizeDropdown();
				this.dropdown._positionDropdown();
			});
			
		} );
	} )( jQuery );
</script>