<?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_API_Settings' ) ) {

	/**
	 * WPSEO_Local_Admin_API_Settings class.
	 *
	 * Build the WPSEO Local admin form.
	 *
	 * @since   11.8
	 */
	class WPSEO_Local_Admin_API_Settings {

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

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

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

		/**
		 * @var WPSEO_Local_Timezone_Repository $wpseo_local_timezone_repository Holds the Timezone repository object;
		 */
		private $wpseo_local_timezone_repository;

		/**
		 * WPSEO_Local_Admin_API_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, 'tab_content' ), 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() {
			$this->wpseo_local_timezone_repository = new 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 ] = __( 'API 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;
		}

		/**
		 * Create tab content for API Settings.
		 */
		public function tab_content() {
			echo '<h3>API key for Google Maps</h3>';
			/* translators: %1$s extends to the anchor opening tag '<a href="https://yoa.st/gm-api-browser-key" target="_blank">', %2$s closes that tag. */
			echo '<p>' . sprintf( __( 'A Google Maps browser key is required to show Google Maps and make use of the Store Locator. For more information on how to create and set your Google Maps browser key, open the help center or %1$scheck our knowledge base%2$s.', 'yoast-local-seo' ), '<a href="https://yoa.st/gm-api-browser-key" target="_blank">', '</a>' ) . '</p>';
			WPSEO_Local_Admin_Wrappers::textinput( 'api_key_browser', __( 'Google Maps API browser key (required)', 'yoast-local-seo' ) );
			if ( defined( 'WPSEO_LOCAL_API_KEY_BROWSER' ) ) {
				/* translators: %s extends to the API Key constant name */
				echo '<p class="help">' . sprintf( __( 'You defined your API key using the %s PHP constant.', 'yoast-local-seo' ), '<code>WPSEO_LOCAL_API_KEY_BROWSER</code>' ) . '</p>';
			}

			echo '<h3>API key for geocoding</h3>';
			/* translators: %1$s extends to a number; %2$s opens a link tag to the Yoast knowledge base; %3$s closes that link. */
			echo '<p>' . sprintf( __( 'A Google Maps Geocoding server key will calculate the latitude and longitude of an address. With this key, you can retrieve the geographical location of up to %1$s addresses per 24 hours. For more information on how to create and set your Google Maps Geocoding server key, open the help center or %2$scheck our knowledge base%3$s. Note, that it is not required to output a Google Map.', 'yoast-local-seo' ), number_format_i18n( 2500, 0 ),
					'<a href="https://yoa.st/gm-geocoding-api-server-key" target="_blank">', '</a>' ) . '</p>';
			WPSEO_Local_Admin_Wrappers::textinput( 'api_key', __( 'Google Maps API server key<br>(not required)', 'yoast-local-seo' ) );
			if ( defined( 'WPSEO_LOCAL_API_KEY_SERVER' ) ) {
				/* translators: %s extends to the API Key constant name */
				echo '<p class="help">' . sprintf( __( 'You defined your API key using the %s PHP constant.', 'yoast-local-seo' ), '<code>WPSEO_LOCAL_API_KEY_SERVER</code>' ) . '</p>';
			}
		}

		/**
		 * @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;
		}
	}
}
