<?php
/**
 * Yoast SEO: Local plugin file.
 *
 * @package WPSEO_Local\Admin\
 * @since   4.1
 * @ToDo    CHECK THE @SINCE VERSION NUMBER!!!!!!!!
 */

if ( ! defined( 'WPSEO_LOCAL_VERSION' ) ) {
	header( 'Status: 403 Forbidden' );
	header( 'HTTP/1.1 403 Forbidden' );
	exit();
}

if ( ! class_exists( 'WPSEO_Local_Admin_Map_Settings' ) ) {

	/**
	 * WPSEO_Local_Admin_Map_Settings class.
	 *
	 * Build the WPSEO Local admin form.
	 *
	 * @since   4.0
	 */
	class WPSEO_Local_Admin_Map_Settings {

		/**
		 * Holds the slug for this settings tab.
		 *
		 * @var string
		 */
		private $slug = 'maps_settings';

		/**
		 * Holds WPSEO Local Core instance.
		 *
		 * @var mixed
		 */
		private $wpseo_local_core;

		/**
		 * Stores the options for this plugin.
		 *
		 * @var mixed
		 */
		private $options;

		/**
		 * WPSEO_Local_Admin_Map_Settings constructor.
		 */
		public function __construct() {
			$this->get_core();
			$this->get_timezone_repository();
			$this->get_options();

			add_filter( 'wpseo_local_admin_tabs', array( $this, 'create_tab' ) );
			add_filter( 'wpseo_local_admin_help_center_video', array( $this, 'set_video' ) );

			add_action( 'wpseo_local_admin_' . $this->slug . '_content', array( $this, 'maps_settings' ), 10 );
			add_action( 'wpseo_local_admin_' . $this->slug . '_content', array( $this, 'store_locator' ), 10 );

			add_action( 'pre_update_option_wpseo_local', array( $this, 'update_lat_long' ), 10, 2 );
			add_action( 'pre_update_option_wpseo_local', array( $this, 'update_timezone' ), 10, 2 );
		}

		/**
		 * Set WPSEO Local Core instance in local property
		 */
		private function get_core() {
			global $wpseo_local_core;
			$this->wpseo_local_core = $wpseo_local_core;
		}

		/**
		 * Set WPSEO Local Core Timezone Repository in local property
		 */
		private function get_timezone_repository() {
			$wpseo_local_timezone_repository       = new WPSEO_Local_Timezone_Repository();
			$this->wpseo_local_timezone_repository = $wpseo_local_timezone_repository;
		}

		/**
		 * Get wpseo_local options.
		 */
		private function get_options() {
			$this->options = get_option( 'wpseo_local' );
		}

		/**
		 * @param array $tabs Array holding the tabs.
		 *
		 * @return mixed
		 */
		public function create_tab( $tabs ) {
			$tabs[ $this->slug ] = __( 'Maps settings', 'yoast-local-seo' );

			return $tabs;
		}

		/**
		 * @param array $videos Array holding the videos for the help center.
		 *
		 * @return mixed
		 */
		public function set_video( $videos ) {
			$videos[ $this->slug ] = 'https://yoa.st/screencast-local-settings-api-keys';

			return $videos;
		}

		/**
		 * Advanced settings section.
		 */
		public function maps_settings() {
			$api_key_browser = $this->options['api_key_browser'];
			$api_key         = $this->options['api_key'];

			if ( ! empty( $api_key_browser ) || ! empty( $api_key ) ) {
				$select_options = array(
					'METRIC'   => __( 'Metric', 'yoast-local-seo' ),
					'IMPERIAL' => __( 'Imperial', 'yoast-local-seo' ),
				);
				WPSEO_Local_Admin_Wrappers::select(
					'unit_system',
					__( 'Unit System', 'yoast-local-seo' ),
					$select_options
				);

				$select_options = array(
					'HYBRID'    => __( 'Hybrid', 'yoast-local-seo' ),
					'SATELLITE' => __( 'Satellite', 'yoast-local-seo' ),
					'ROADMAP'   => __( 'Roadmap', 'yoast-local-seo' ),
					'TERRAIN'   => __( 'Terrain', 'yoast-local-seo' ),
				);
				WPSEO_Local_Admin_Wrappers::select(
					'map_view_style',
					__( 'Default map style', 'yoast-local-seo' ),
					$select_options
				);

				WPSEO_Local_Admin_Page::section_before( 'wpseo-local-custom-marker', null, 'wpseo-local-custom_marker-wrapper' );
				echo '<label class="textinput" for="custom_marker">' . esc_html__( 'Custom marker', 'yoast-local-seo' ) . ':</label>';
				WPSEO_Local_Admin_Wrappers::hidden( 'custom_marker' );

				$show_marker = ! empty( $this->options['custom_marker'] );
				echo '<img src="' . ( isset( $this->options['custom_marker'] ) ? wp_get_attachment_url( $this->options['custom_marker'] ) : '' ) . '" id="custom_marker_image_container" class="wpseo-local-hide-button' . ( ( false === $show_marker ) ? ' hidden' : '' ) . '">';
				echo '<br class="wpseo-local-hide-button' . ( ( false === $show_marker ) ? ' hidden' : '' ) . '">';
				echo '<p style="border: none;">';
				echo '<a href="javascript:" class="set_custom_images button" data-id="custom_marker">' . esc_html__( 'Set custom marker image', 'yoast-local-seo' ) . '</a>';
				echo ' <a href="javascript:" class="remove_custom_image wpseo-local-hide-button' . ( ( false === $show_marker ) ? ' hidden' : '' ) . '" style="color: #a00 !important;" data-id="custom_marker">' . esc_html__( 'Remove marker', 'yoast-local-seo' ) . '</a>';
				echo '</p>';
				if ( true == $show_marker ) {
					$this->wpseo_local_core->check_custom_marker_size( $this->options['custom_marker'] );
				}
				else {
					echo '<p style="border:none;">' . esc_html__( 'The custom marker should be 100x100 px. If the image exceeds those dimensions it could (partially) cover the info popup.', 'yoast-local-seo' ) . '</p>';
				}

				WPSEO_Local_Admin_Page::section_after(); // End wpseo-local-custom-marker section.
			}
		}


		/**
		 * Store locator settings section.
		 */
		public function store_locator() {
			$api_key_browser = $this->options['api_key_browser'];
			$api_key         = $this->options['api_key'];

			if ( ! empty( $api_key_browser ) || ! empty( $api_key ) ) {
				WPSEO_Local_Admin_Page::section_before( 'sl-settings', 'clear: both; ' . ( wpseo_has_multiple_locations() ? '' : 'display: none;' ) );
				echo '<h3>' . esc_html__( 'Store locator settings', 'yoast-local-seo' ) . '</h3>';
				WPSEO_Local_Admin_Wrappers::textinput( 'sl_num_results', __( 'Number of results', 'yoast-local-seo' ) );

				// Chosen allows us to clear a set option (to pass no value), but to do that it requires an empty option.
				$countries = ( array( '' => '' ) + WPSEO_Local_Frontend::get_country_array() );

				WPSEO_Local_Admin_Wrappers::select( 'default_country', __( 'Primary country', 'yoast-local-seo' ), $countries );

				echo '<p style="border:none;" class="label desc">' . esc_html__( 'From which country does your business mainly operate? This will improve the accuracy of the store locator.', 'yoast-local-seo' ) . '</p>';
				WPSEO_Local_Admin_Wrappers::textinput( 'show_route_label', __( '"Show route" label', 'yoast-local-seo' ), '', array( 'placeholder' => __( 'Show route', 'yoast-local-seo' ) ) );

				if ( true === is_ssl() ) {
					Yoast_Form::get_instance()->toggle_switch(
						'detect_location',
						array(
							'on'  => __( 'On', 'yoast-local-seo' ),
							'off' => __( 'Off', 'yoast-local-seo' ),
						),
						__( 'Location detection', 'yoast-local-seo' )
					);

					echo '<p>' . __( 'Automatically detect the users location as starting point.', 'yoast-local-seo' ) . '</p>';
				}
				else {
					echo '<label class="checkbox" for="detect_location">Location detection: (disabled)</label>';
					echo '<p style="border:none; margin-bottom: 0;"><em>';
					printf(
					/* translators: 1: link open tag; 2: link close tag. */
						esc_html__( 'This option only works on HTTPS websites. Using HTTPS is important, read more about it in the %1$sYoast KB%2$s', 'yoast-local-seo' ),
						'<a href="https://yoa.st/local-seo-https">',
						'</a>'
					);
					echo '</em></p>';
				}
				WPSEO_Local_Admin_Page::section_after(); // End Stor Locator settings
			}
		}

		/**
		 * @param array $new_value New value for wpseo_local options.
		 * @param array $old_value Old value for wpseo_local options.
		 *
		 * @return mixed
		 */
		public function update_lat_long( $new_value, $old_value ) {
			// Don't geocode when no address details are known.
			if ( ( empty( $new_value['location_coords_lat'] ) || empty( $new_value['location_coords_lat'] ) ) && empty( $new_value['location_address'] ) ) {
				return $new_value;
			}

			// Calculate lat/long coordinates when address is entered.
			if ( empty( $old_value['location_coords_lat'] ) || empty( $old_value['location_coords_long'] ) ) {
				$location_info        = array(
					'_wpseo_business_address' => isset( $new_value['location_address'] ) ? esc_attr( $new_value['location_address'] ) : '',
					'_wpseo_business_city'    => isset( $new_value['location_city'] ) ? esc_attr( $new_value['location_city'] ) : '',
					'_wpseo_business_state'   => isset( $new_value['location_state'] ) ? esc_attr( $new_value['location_state'] ) : '',
					'_wpseo_business_zipcode' => isset( $new_value['location_zipcode'] ) ? esc_attr( $new_value['location_zipcode'] ) : '',
					'_wpseo_business_country' => isset( $new_value['location_country'] ) ? esc_attr( $new_value['location_country'] ) : '',
				);
				$location_coordinates = $this->wpseo_local_core->get_geo_data( $location_info, true );

				if ( ! empty( $location_coordinates['coords'] ) ) {
					$new_value['location_coords_lat']  = str_replace( ',', '.', $location_coordinates['coords']['lat'] );
					$new_value['location_coords_long'] = str_replace( ',', '.', $location_coordinates['coords']['long'] );
				}
			}

			return $new_value;
		}

		/**
		 * @param array $new_value New value for wpseo_local options.
		 * @param array $old_value Old value for wpseo_local options.
		 *
		 * @return mixed
		 */
		public function update_timezone( $new_value, $old_value ) {
			// Multiple locations are set, there is no need for this update.
			if ( wpseo_has_multiple_locations() ) {
				return $new_value;
			}

			if ( empty( $old_value['location_coords_lat'] ) || empty( $old_value['location_coords_long'] ) ) {
				$timezone = $this->wpseo_local_timezone_repository->get_coords_timezone();

				if ( ! empty( $timezone ) ) {
					$new_value['location_timezone'] = $timezone;
				}
			}

			return $new_value;
		}
	}
}
