<?php
namespace Medienreaktor\Products\ViewHelpers\Map;

class PinViewHelper extends \TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper {

	/**
	* Arguments Initialization
	*/
	public function initializeArguments(): void {
		$this->registerArgument('latitude', 'String', 'The latitude for the map center', TRUE);
		$this->registerArgument('longitude', 'String', 'The longitude for the map center', TRUE);
		$this->registerArgument('title', 'String', 'The title for the info window', TRUE);
		$this->registerArgument('content', 'String', 'The content of the info window', FALSE);
        $this->registerArgument('sorting', 'int', 'The sorting of the marker', TRUE);
	}

     /**
     * Render method
     * @return string
     */
    public function render() {
		$latitude	= number_format(trim($this->arguments['latitude']), 6, ".", "");
		$longitude	= number_format(trim($this->arguments['longitude']), 6, ".", "");
		$title = $this->arguments['title'];
		$title		= str_replace(' ', '&nbsp;', $title);
		$title 		= str_replace(" ", "", $title);
		$title 		= addslashes($title);
		$content 	= $this->arguments['content'];

        $sorting    = $this->arguments['sorting'] ? 1000 : 100;

		$icon		= 'typo3conf/ext/products/Resources/Public/Images/MapMarker.png';

		$content = str_replace("\n", "", $content);
		$content = str_replace("\r", "", $content);
		$content = str_replace('&nbsp;', '', $content);
		$content = str_replace(" ", "", $content);
		$content = addslashes($content);

		$output = '
			var newMarker = new google.maps.Marker({
				position: new google.maps.LatLng('.$latitude.', '.$longitude.'),
				map: map,
				title: "'.html_entity_decode($title).'",
				icon: "'.$icon.'",
                optimized: false,
                zIndex: '.$sorting.'
			});
		';

		$output .= '
			markers.push(newMarker);
			var length = markers.length - 1;

			google.maps.event.addListener(markers[length], \'click\', function() {
				infowindow.close();
				infowindow.setContent("'.$content.'");
				infowindow.open(map, this);
			});
		';

		return $output;
    }

}
?>
