<?php
global $globKurier;


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



$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' ) ?? '';

$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%;" class="udi-select2" id="udi-select-ruch" name="globkurier_ruch_input_value">-->
<!--			--><?php
//				if( isset( $point_id ) ){
//					echo "<option value='{$point_id}' selected>{$point_val}</option>";
//				}
//			?>
<!--		</select>	-->
		
		<select style="width: 100%;" class="udi-select2" id="udi-select-ruch" name="globkurier_ruch_input_value">
			<?php
				foreach( $allPoints as $point ){
					echo "<option value='".$point['id']."' latitude='".$point['latitude']."' selected>".$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 ajaxurl = data[ 'ajaxUrl' ];
			
			const globkurierInput = '#globkurier_ruch_input';
			const udiSelect = '.udi-select2#udi-select-ruch';
			const globkurierInputHiddenValue = '#globkurier_ruch_input_hidden_value';
			const saveSessionAction = 'globkurierSaveRuchPointsSession';
			const getPointsAction = 'globkurierGetRuchPointsSelect2';
			
			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 };
			
			let markerCluster;
			let globkurier_map;
			
			var prevData = [];
			
			globkurierMapInit();
			
			function globkurierMapInit() {
				globkurier_map = new google.maps.Map( document.getElementById( map_container ), {
					center: poland,
					zoom: 6,
					disableDefaultUI: true
				} );
			}
			
			function gkSaveSession( d ) {
				$( 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,
					},
				} );
			}
			
			$( document ).on( 'click', '.globkurier_marker_select_point', function ( e ) {
				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 = `<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>`;
			<?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 } ?>
			
			
			$( document ).find( udiSelect ).on('change', function (e) {
				console.log('change');
			});
			$( document ).find( udiSelect ).on('change.select2', function (e) {
				console.log('change.select2');
			});
			
			$( document ).find( udiSelect ).on('select2:select', function (e) {
				console.log('select2:select');
			});
			
			$( document ).find( udiSelect ).on('select2:select', function (e) {
				console.log('select2:select');
			});
			
			$( document ).find( udiSelect ).on('select2:select', function (e) {
				console.log('select2:selecting');
			});
			
			$( document ).find( udiSelect ).select2( {
				placeholder: 'Znajdź punkt dostawy',
				language: {
					searching: function () {
						return 'Szukaj ORLEN Paczka';
					},
					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: getPointsAction,
						};
					},
					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 = [];
							
							prevData = parsedData;
							
							//dodanie cluster z lista wszystkich wynikow wyszukiwania
							parsedData.forEach( ( d ) => {
								let lat = d.latitude;
								let lng = d.longitude;
								let pos = { lat, lng };
								
								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( d )
								let tooltipData = JSON.stringify( d )
								
								contentString += " data-eventdata='" + eventData + "'";
								contentString += " data-tooltip='" + tooltipData + "'";
								contentString += ` type="button">WYBIERZ</button>`;
								
								contentString += `</div>`;
								
								tooltip.setContent( contentString ) ;
								
								let marker = new google.maps.Marker( {
									position: pos,
									maxWidth: 300,
								} );
								
								marker.addListener( 'click', () => {
									tooltip.open( globkurier_map, marker );
									globkurier_map.setCenter( new google.maps.LatLng( d.latitude, d.longitude ) );
									globkurier_map.setZoom( 15 );
								} );
								
								markers.push( marker );
							} );
							
							markerCluster = new MarkerClusterer( globkurier_map, markers, { imagePath: clusterIcon } );
							
							markerCluster.fitMapToMarkers();
						}
						
						return {
							results: options
						};
					},
					cache: true
				},
				minimumInputLength: 3,
			} );
			
			//dodanie markera z wybranym punktem
			$( document ).find( udiSelect ).on( 'select2:select', function ( e ) {
				
				console.log(e, e.params.data);
				
				$( globkurierInput ).val( e.params.data.text );
				$( globkurierInputHiddenValue ).val( e.params.data.id );
				
				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,
				} );
				
				marker.addListener( 'click', () => {
					tooltip.open( globkurier_map, marker );
				} );
		
				markers.push( marker );
				
				globkurierMapInit();
				
				markerCluster = new MarkerClusterer( globkurier_map, markers, { imagePath: clusterIcon } );
				
				globkurier_map.setCenter( marker.getPosition() );
				globkurier_map.setZoom( 15 );
				
				gkSaveSession( e.params.data )
			} );
			
			$( document ).find( udiSelect ).data( 'select2' ).on( 'results:message', function ( params ) {
				this.dropdown._resizeDropdown();
				this.dropdown._positionDropdown();
			} );
			
		} );
	} )( jQuery );
</script>