<?php
/**
 * Maps file.
 *
 * @package wpjm-jobs-geolocation.
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

/**
 * Deprecated function.
 *
 * @param  array $atts shortcode attibutes.
 *
 * @return [type]       [description]
 */
function gjm_get_results_map( $atts ) {

	_deprecated_function( 'gjm_get_results_map', '1.9', 'gjm_get_map_element' );

	return GJM_Maps::get_map_element( $atts );
}

/**
 * Map functions class
 */
class GJM_Maps {

	/**
	 * Array of maps that need to be generated on the page
	 *
	 * @var array
	 */
	public static $map_elements = array();

	/**
	 * Map enabler
	 *
	 * @var boolean
	 */
	private static $map_enabled = false;

	/**
	 * Generate map element
	 *
	 * @param  array $atts shortcode attibutes.
	 *
	 * @return map element
	 */
	public static function get_map_element( $atts ) {

		// default map settings.
		$args = shortcode_atts(
			array(
				'map_id'                 => 'job_map_listing',
				'prefix'                 => 'gjm',
				'map_width'              => '100%',
				'map_height'             => '300px',
				'init_map_show'          => true,
				'show_without_locations' => false,
				'user_marker'            => 'https://maps.google.com/mapfiles/ms/icons/blue-dot.png',
				'zoom_level'             => 'auto',
				'max_zoom_level'         => '',
				'map_type'               => 'ROADMAP',
				'scrollwheel'            => '',
				'group_markers'          => 'normal',
				'clusters_path'          => 'https://raw.githubusercontent.com/googlemaps/js-marker-clusterer/gh-pages/images/m',
				'map_name'               => 'results-map',
			),
			$atts
		);

		$display  = empty( $args['init_map_show'] ) ? 'display:none;' : '';
		$args     = apply_filters( $args['prefix'] . '_map_output_args', $args );
		$prefix   = esc_attr( $args['prefix'] );
		$map_id   = esc_attr( $args['map_id'] );
		$map_name = ! empty( $args['map_name'] ) ? esc_attr( $args['map_name'] ) : 'results-map';

		$args = array_map( 'esc_attr', $args );

		$output['open']          = '<div id="' . $prefix . '-map-wrapper-' . $map_id . '" class="' . $prefix . '-map-wrapper map-wrapper ' . $map_name . '" data-map_id="' . $map_id . '" style="' . $display . ' width:' . esc_attr( $args['map_width'] ) . ';height:' . esc_attr( $args['map_height'] ) . '">';
		$output['resize_toggle'] = '<span id="' . $prefix . '-resize-map-toggle-' . $map_id . '" class="' . $prefix . '-resize-map-toggle gjm-icon-resize-full" style="display:none;" title="' . __( 'Resize map', 'pointify' ) . '"></span>';
		$output['map']           = '<div id="' . $prefix . '-map-' . $map_id . '" data-map-id="' . $map_id . '" class="' . $prefix . '-map" style="width:100%; height:100%" data-user_marker="' . esc_url( $args['user_marker'] ) . '" data-zoom_level="' . esc_attr( $args['zoom_level'] ) . '" data-max_zoom_level="' . esc_attr( $args['max_zoom_level'] ) . '" data-map_type="' . esc_attr( $args['map_type'] ) . '" data-scrollwheel="" data-group_markers="' . esc_attr( $args['group_markers'] ) . '" data-clusters_path="' . esc_url( $args['clusters_path'] ) . '" data-show_without_locations="' . esc_attr( $args['show_without_locations'] ) . '"></div>';
		$output['loader']        = '<i id="' . $prefix . '-map-loader-' . $map_id . '" class="' . $prefix . '-map-loader gjm-icon-spin-thin animate-spin"></i>';
		$output['close']         = '</div>';

		// modify the map element.
		$output = apply_filters( $args['prefix'] . '_map_output', $output, $args );

		// enqueue grouping scripts.
		self::enqueue_scripts( $args );

		return implode(' ', $output);
	}

	/**
	 * Generate the map aruments.
	 *
	 * @param  array $map_args      map arguments.
	 *
	 * @param  array $map_options   map options.
	 *
	 * @param  array $locations     locations.
	 *
	 * @param  array $user_position user location.
	 *
	 * @return [type]                [description]
	 */
	public static function get_map_object( $map_args = array(), $map_options = array(), $locations = array(), $user_position = array() ) {

		// randomize map ID if not exists.
		$map_id = ! empty( $map_args['map_id'] ) ? $map_args['map_id'] : 'job_map_listing';

		// default map args.
		$default_map_args = array(
			'map_id'        => $map_id,
			'prefix'        => 'gjm',
			'zoom_position' => false,
		);

		// merge default with incoming map args.
		$map_args = array_merge( $default_map_args, is_array($map_args) ? $map_args:[]);

		// default map options.
		$default_map_options = array(
			'backgroundColor'        => '#f1f1f1',
			'disableDefaultUI'       => false,
			'disableDoubleClickZoom' => false,
			'draggable'              => true,
			'draggableCursor'        => '',
			'draggingCursor'         => '',
			'fullscreenControl'      => false,
			'keyboardShortcuts'      => true,
			'mapMaker'               => false,
			'mapTypeControl'         => true,
			'mapTypeControlOptions'  => true,
			'mapTypeId'              => 'ROADMAP',
			'maxZoom'                => null,
			'minZoom'                => null,
			'zoomLevel'              => 13,
			'noClear'                => false,
			'rotateControl'          => true,
			'scaleControl'           => true,
			'scrollwheel'            => true,
			'streetViewControl'      => true,
			'styles'                 => null,
			'tilt'                   => null,
			'zoomControl'            => true,
			'resizeMapControl'       => true,
			'panControl'             => true,
		);

		$map_options = array_merge( $default_map_options, $map_options );

		// default user position.
		$default_user_position = array(
			'lat'        => false,
			'lng'        => false,
			'address'    => false,
			'iw_content' => null,
			'iw_open'    => false,
		);

		// if user position exists, merge it with default.
		if ( ! empty( $user_position['lat'] ) ) {

			$user_position = array_merge( $default_user_position, $user_position );

		} else {

			$user_position = $default_user_position;
		}

		// push the map args into the global array of maps.
		$map_element = array(
			'args'          => $map_args,
			'map_options'   => $map_options,
			'locations'     => $locations,
			'user_position' => $user_position,
		);
		
		// allow plugins modify the map args.
		$map_element = apply_filters( 'gjm_map_element', $map_element, $map_id );

		// enable maps.
		self::$map_enabled = true;

		GJM_Init::enqueue_google_maps_api();

		self::$map_elements[ $map_id ] = $map_element;
	
		// pass the mapObjects to JS.
		wp_localize_script( 'gjm-map', 'gjmMapObjects', self::$map_elements );

		return $map_element;
	}

	/**
	 * Info-window content.
	 *
	 * @param object $post the post object.
	 */
	public static function get_info_window_content( $post ) {

		// get the address.
		if ( ! empty( $post->formatted_address ) ) {

			$address = $post->formatted_address;

		} elseif ( ! empty( $post->address ) ) {

			$address = $post->address;

		} else {

			$address = get_post_meta( $post->ID, 'geolocation_formatted_address', true );
		}

		if ( empty( $address ) ) {
			$address = __( 'N/A', 'pointify' );
		}

		$output['title'] = '<a class="title" href="' . get_permalink( $post->ID ) . '" title="' . esc_attr( $post->post_title ) . '">' . esc_attr( $post->post_title ) . '</a>';

		$output['address'] = '<span class="location gjm-icon-location">' . esc_attr( $address ) . '</span>';

		$additional_info = apply_filters( 'gjm_info_window_additional_info', false, $post );

		// additional data disabled by default to keep the info window minimal and clean.
		if ( false !== $additional_info && is_array( $additional_info ) ) {

			$output = array_merge( $output, $additional_info );
		}

		if ( isset( $post->distance ) ) {
			$output['distance'] = '<span class="distance">' . esc_attr( $post->distance . ' ' . $post->units ) . '</span>';
		}

		$output = apply_filters( 'gjm_info_window_content', $output, $post );

		return implode( '', $output );
	}

	/**
	 * Enqueue map scripts
	 *
	 * @param  array $args arguments.
	 */
	public static function enqueue_scripts( $args ) {

		// Load marker clusterer library when needed. It might already loaded by GEO my WP, Jobify or WorkScout themes.
		// When that is the case we will use the Jobify clusters.
		if ( 'markers_clusterer' === $args['group_markers'] && ! wp_script_is( 'gjm-marker-clusterer', 'enqueued' ) && ! wp_script_is( 'gmw-marker-clusterer', 'enqueued' ) && ! wp_script_is( 'jobify-app-map', 'enqueued' ) && ! wp_script_is( 'workscout-clusters', 'enqueued' ) ) {
			wp_enqueue_script( 'gjm-marker-clusterer', GJM_URL . '/inc/includes/assets/js/lib/marker-clusterer/marker.clusterer.min.js', array( 'jquery' ), GJM_VERSION, true );
		}

		// load marker spiderfire library.
		if ( 'markers_spiderfier' === $args['group_markers'] && ! wp_script_is( 'gjm-marker-spiderfier', 'enqueued' ) && ! wp_script_is( 'gmw-marker-spiderfier', 'enqueued' ) ) {
			wp_enqueue_script( 'gjm-marker-spiderfier', GJM_URL . '/inc/includes/assets/js/lib/marker-spiderfier/marker.spiderfier.min.js', array( 'jquery' ), GJM_VERSION, true );
		}
	}
}
