<?php
global $globKurier;

$point_id           = WC()->session->get( 'globkurier_ruch_selected_point_id' ) ?? '';
$point_val          = WC()->session->get( 'globkurier_ruch_selected_point_value' ) ?? '';
$point_lat          = WC()->session->get( 'globkurier_ruch_selected_point_latitude' ) ?? '';
$point_long         = WC()->session->get( 'globkurier_ruch_selected_point_longitude' ) ?? '';
$point_city         = WC()->session->get( 'globkurier_ruch_selected_point_city' ) ?? '';
$point_address      = WC()->session->get( 'globkurier_ruch_selected_point_address' ) ?? '';
$point_openingHours = WC()->session->get( 'globkurier_ruch_selected_point_openingHours' ) ?? '';

$isInitDisabled                 = WC()->session->get( 'globkurier_disable_ruch_init' ) ?? 0;
$globkurier_old_ruch_params     = WC()->session->get( 'globkurier_old_ruch_params' ) ?? '';

if( $isInitDisabled == 'off' ) {
	$isInitDisabled = 0;
}

$sessionCity = WC()->session->customer[ 'city' ];

$allPoints = $globKurier->ruch()->getAllPoints( );

?>

<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( 'ruch_method' ) ?? '' ?>">
		<input type="hidden" name="globkurier_ruch_input" id="globkurier_ruch_input" value="<?php echo $point_val ?>" required>
		<input type="hidden" name="globkurier_ruch_input_hidden_value" id="globkurier_ruch_input_hidden_value" value="<?php echo $point_id ?>" required>
		
		<div id="globkurier_map"></div>
		
		<select style="width: 100%; display: none" class="udi-select2" id="udi-select-ruch" name="globkurier_ruch_input_value">
			<option></option>
			<?php
				foreach( $allPoints as $point ){
					echo "<option
					value='".$point['id']."'
					data-latitude='".$point['latitude']."'
					data-longitude='".$point['longitude']."'
					data-city='".$point['city']."'
					data-address='".$point['address']."'
					data-openinghours='".$point['openingHours']."'
					>".$point['value']."</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 () {
			const log = false;
			
			const ajaxurl = data[ 'ajaxUrl' ];
			
			const globkurierInput = '#globkurier_ruch_input';
			const udiSelect = '.udi-select2#udi-select-ruch';
			const globkurierInputHiddenValue = '#globkurier_ruch_input_hidden_value';
			const select2SelectContainer = '#select2-udi-select-ruch-container'
			
			const saveSessionAction = 'globkurierSaveRuchPointsSession';
			
			const clusterIcon = 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m';
			
			const map_container = 'globkurier_map';
			const poland = { lat: 52.476329, lng: 18.995734 };
			
			var customOpen = false;
			
			let markerCluster;
			let globkurier_map;
			
			var currentQuery;
			let markers = [];
			
			var isInitDisabled = <?php echo $isInitDisabled ?>;

			globkurierMapInit();
			
			function globkurierMapInit() {
				logger( 'globkurierMapInit' );
				
				globkurier_map = new google.maps.Map( document.getElementById( map_container ), {
					center: poland,
					zoom: 6,
					disableDefaultUI: true
				} );
				
				/*
				if( isInitDisabled == 1){
					console.log('old params set up');
					let oldParms = '<?php echo $globkurier_old_ruch_params ?? '' ?>';
					
					if( oldParms !== '' && true ){
						let data = JSON.parse( oldParms );

						data.forEach( ( d ) => {
							let contentString =
								`<div class="gkInfowindow-inside">` +
								`<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();
							
							contentString += `<button class="globkurier_marker_select_point"`;
							
							let eventData = JSON.stringify( {
								id: d.id,
								value: d.text,
								latitude: d.latitude,
								longitude: d.longitude,
								city: d.city,
								address: d.address,
								openingHours: d.openinghours,
							} )
							
							let lat = d.latitude;
							let lng = d.longitude;
							
							let pos = { lat, lng }
							
							contentString += " data-eventdata='" + eventData + "'";
							contentString += ` type="button">WYBIERZ</button>`;
							
							contentString += `</div>`;
							
							tooltip.setContent( contentString ) ;
							
							let marker = new google.maps.Marker( {
								position: pos,
								map: globkurier_map,
								maxWidth: 300,
							} );
							
							marker.addListener( 'click', () => {
								tooltip.open( globkurier_map, marker );
								globkurier_map.setCenter( new google.maps.LatLng( d.lat, d.lng ) );
								globkurier_map.setZoom( 15 );
							} );
							
							markers.push( marker );
						} );

						markerCluster = new MarkerClusterer( globkurier_map, markers, { imagePath: clusterIcon } );
						markerCluster.fitMapToMarkers();
					}
				}
				*/
			}
			
			function gkDisableInit( type, status, params ) {
				logger('gkDisableInit', type, status);
				let action;
				
				switch ( type ) {
					case 'ruch':
						action = 'globkurierSaveRuchPointsDisableInitSession';
						break;
					case 'inpsot':
						action = 'globkurierSaveInpostPointsDisableInitSession';
						break;
					default:
						return;
				}
				
				$.post( {
					url: ajaxurl,
					data: {
						action: action,
						status: status,
						params: params || [],
					},
				} );
			}
			
			function gkSaveSession( d ) {
				logger( 'gkSaveSession' );
				
				$( document ).find( globkurierInput ).val( d.value || d.text );
				$( document ).find( globkurierInputHiddenValue ).val( d.id );

				$( document ).find( '#udi-map-td .select2-selection__rendered' ).text( d.value || d.text );
				
				$.post( {
					url: ajaxurl,
					dataType: 'json',
					minLength: 3,
					data: {
						action: saveSessionAction,
						id: d.id,
						value: d.value || d.text,
						latitude: d.latitude,
						longitude: d.longitude,
						city: d.city,
						address: d.address,
						openingHours: d.openingHours,
					},
				} );
				
				// gkDisableInit( 'ruch', 'off', '' );
			}
			
			$( document ).on( 'click', '.globkurier_marker_select_point', function ( e ) {
				logger( 'globkurier_marker_select_point' );
				
				let eventData = $( e.target ).data( 'eventdata' );
				gkSaveSession( eventData );
				
				// tooltip.close();
				$( e.target ).parent().parent().parent().parent().find('button.gm-ui-hover-effect').click()
			} );
			
			<?php
			
			if ( $point_val && $point_id && $point_lat && $point_long && $point_city && $point_address  ) {  ?>
			let lat = <?php echo $point_lat?>;
			let lng = <?php echo $point_long?>;
			let pos = { lat, lng };
			
			let contentString = `<div class='gkInfowindow-inside'><p> Miasto: <?php echo $point_city ?> </p>` + `<p> Adres: <?php echo $point_address ?> </p>`;
			
			<?php if ($point_openingHours != ''){?>
			contentString += `<p> Godziny otwarcia: <?php echo $point_openingHours ?> </p></div>`;
			<?php }?>
			
			let tooltip = new google.maps.InfoWindow( {
				content: contentString
			} );
			
			let marker = new google.maps.Marker( {
				position: pos,
			} );
			
			marker.addListener( 'click', () => {
				tooltip.open( globkurier_map, marker );
				$( globkurierInput ).val( '<?php echo $point_val ?>' );
				$( globkurierInputHiddenValue ).val( '<?php echo $point_val ?>' );
			} );
			
			globkurier_map.setZoom( 15 );
			globkurier_map.setCenter( marker.getPosition() );
			
			marker.setMap( globkurier_map );
			
			<?php } ?>
			
			function matchStart( params, data ) {
				params.term = params.term || '';
				if ( data.text.toUpperCase().indexOf(params.term.toUpperCase()) == 0 ) {
					return data;
				}
				return null;
			}
			
			$( document ).find( udiSelect ).select2( {
				placeholder: 'Znajdź punkt dostawy',
				
				language: {
					searching: function () {
						return 'Szukaj Paczka w RUCHu';
					},
					inputTooShort: function () {
						return 'Wpisz miasto';
					},
					noResults: function () {
						return 'Brak wyników';
					},
					errorLoading: function () {
						return 'Szukanie...';
					},
					loadingMore: function () {
						return 'Szukanie...';
					},
				},
				minimumInputLength: 3,
			})
			.on('select2:open', function(e) {
				logger( 'select2:open' );
				//
				// konflikt z wyszukiwaniem po miejscowosci - pozycja srony
				// let input = $( 'input[aria-owns="select2-udi-select-ruch-results"]' );
				//
				// if( currentQuery != '' ) {
				// 	input.val( currentQuery );
				//
				// 	setTimeout( function () {
				// 		input.trigger( 'input' );
				// 	}, 10 );
				// }

			})
			.on('select2:closing', function() {
				logger( 'select2:closing' );
				currentQuery = $( '.select2-search input' ).prop( 'value' );
			});
			
			<?php if( isset( $point_id ) && $point_id != '' ){?>
				logger( 'init set current point name' );
				$( document ).find( '#udi-map-td .select2-selection__rendered' ).text( '<?php echo $point_val ?>');
			<?php } ?>
			
			//dodanie markera z wybranym punktem
			$( document ).find( udiSelect ).on( 'select2:select', function ( e ) {
				logger( 'select2:select' );
				
				let option = $(e.params.data.element);

				$( globkurierInput ).val( option[0].text );
				$( globkurierInputHiddenValue ).val( option[0].value );
				
				let lat = option.data('latitude');
				let lng = option.data('longitude');
				let pos = { lat, lng };
				let markers = [];
				
				let contentString =`<div class='gkInfowindow-inside'`+
					`<p> Miasto: ${ option.data('city') } </p>` +
					`<p> Adres: ${ option.data('address') } </p>`;
				
				contentString += `<p> Godziny otwarcia: ${ option.data('openinghours')} </p></div>`;
				
				let tooltip = new google.maps.InfoWindow( {
					content: contentString
				} );
				
				let marker = new google.maps.Marker( {
					position: pos,
				} );
				
				marker.addListener( 'click', () => {
					tooltip.open( globkurier_map, marker );
				} );
		
				markers.push( marker );
				
				// if( isInitDisabled !== 1){
				// 	globkurierMapInit();
				// }
				
				markerCluster = new MarkerClusterer( globkurier_map, markers, { imagePath: clusterIcon } );
				
				globkurier_map.setCenter( marker.getPosition() );
				globkurier_map.setZoom( 15 );
				
				gkSaveSession( {
					id: option[0].value,
					value: option[0].text,
					latitude: option.data('latitude'),
					longitude: option.data('longitude'),
					city: option.data('city'),
					address: option.data('address'),
					openingHours: option.data('openinghours'),
				} );
			} );
			
			$( document ).find( udiSelect ).data( 'select2' ).on( 'results:message', function ( params ) {
				logger( 'results:message', params );

				this.dropdown._resizeDropdown();
				this.dropdown._positionDropdown();
			} );
			
			function addPointToMap( d ){
				if ( d ) {
					if( d.loading == true){
						return;
					}
					
					let option = $(d.element);
					
					//dodanie cluster z lista wszystkich wynikow wyszukiwania
					let lat = option.data( 'latitude' );
					let lng = option.data( 'longitude' );
					let pos = { lat, lng };
					let city = option.data( 'city' );
					let address = option.data( 'address' );
					let openinghours = option.data( 'openinghours' );
					
					let contentString =
						`<div class="gkInfowindow-inside">` +
						`<p> Miasto: ${ city } </p>` +
						`<p> Adres: ${ address } </p>`;
					
					if ( d.openingHours !== '' ) {
						contentString += `<p> Godziny otwarcia: ${ openinghours } </p>`;
					}
					
					let tooltip = new google.maps.InfoWindow();
					
					contentString += `<button class="globkurier_marker_select_point"`;
					
					let eventData = JSON.stringify( {
						id: d.id,
						value: d.text,
						latitude: lat,
						longitude: lng,
						city: city,
						address: address,
						openingHours: openinghours,
					} )
					
					contentString += " data-eventdata='" + eventData + "'";
					contentString += ` type="button">WYBIERZ</button>`;
					
					contentString += `</div>`;
					
					tooltip.setContent( contentString ) ;
					
					let marker = new google.maps.Marker( {
						position: pos,
						map: globkurier_map,
						maxWidth: 300,
					} );
					
					tooltip.setPosition( marker.getPosition() ) ;
					
					
					marker.addListener( 'click', () => {
						tooltip.open( globkurier_map, marker );
						globkurier_map.setCenter( new google.maps.LatLng( lat, lng ) );
						// globkurier_map.setZoom( 15 );
					} );
					
					// globkurier_map.setCenter( new google.maps.LatLng( lat, lng ) );
					// globkurier_map.setZoom( 15 );
					//
					return marker;
				}
			}
			
			$( document ).find( udiSelect ).data( 'select2' ).on( 'results:all', function ( params ) {
			
				logger( 'results', params );
				
				globkurierMapInit();
				
				markers = [];
				
				let data = params.data.results;
				
				if( data.length == 0 ){
					return;
				}
				
				let markersData = []
				data.forEach( ( d ) => {
					let marker = addPointToMap( d );
					markers.push( marker );
					
					let option = $(d.element);
					
					markersData.push({
						id: d.id,
						value: d.text,
						latitude:  option.data( 'latitude' ),
						longitude: option.data( 'longitude' ),
						city: option.data( 'city' ),
						address: option.data( 'address' ),
						openingHours: option.data( 'openinghours' ),
					});
					
				} );
				
				markerCluster = new MarkerClusterer( globkurier_map, markers, { imagePath: clusterIcon } );
				
				if( markers.length == 1){
					globkurier_map.setZoom( 15 );
					globkurier_map.setCenter( markers[0].getPosition() );
				}else{
					markerCluster.fitMapToMarkers();
				}
				
			} );
			
			function select2_search ( $el, term, closeAfter = true ) {
				
				let currentPosition = window.pageYOffset || document.documentElement.scrollTop;
				
				currentQuery = '';
				
				$el.select2( 'open' );
				
				let $search = $el.data( 'select2' ).dropdown.$search || $el.data( 'select2' ).selection.$search;
				$search.val( term );
				$search.trigger( 'input' );
				
				if( closeAfter === true ){
					$el.select2( 'close' );
				}
				
				setTimeout(function () {
					$(window).scrollTop( currentPosition );
				},10);
				
			}
			
			$( document ).on( 'change', '#billing_city', function ( e ) {
				if( $('#ship-to-different-address-checkbox').is( ':checked' ) ){
					return
				}
				
				if( $( globkurierInputHiddenValue ).val() !== '' ){
					return;
				}
				
				select2_search(	$( document ).find( udiSelect ), $( this ).val() + ',', true);
				
				currentQuery = $(this).val();
				
				logger( 'billing_city change' );
			} );
			
			$( document ).on( 'change', '#shipping_city', function ( e ) {
				if( ! $( '#ship-to-different-address-checkbox' ).is( ':checked' ) ){
					return
				}
				
				if( $( globkurierInputHiddenValue ).val() !== '' ){
					return;
				}
				
				select2_search(	$( document ).find( udiSelect ), $( this ).val() + ',', true);
				
				logger( 'shipping_city change' );
			} );
			
			$( select2SelectContainer ).removeAttr( 'title' );
			
			function logger( ...msg ) {
				if( !log || false ){
					return;
				}
				console.table( msg );
			}
			
			
		} );
	} )( jQuery );
</script>