<?php

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class GMDS_Admin {
	/**
	 * Register hooks.
	 *
	 * @return void
	 */
	public static function init() {
		add_action( 'admin_menu', array( __CLASS__, 'register_settings_page' ) );
		add_action( 'admin_init', array( __CLASS__, 'register_settings' ) );
		add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_admin_assets' ) );
		add_action( 'wp_enqueue_scripts', array( __CLASS__, 'enqueue_front_builder_assets' ) );
		add_action( 'admin_head', array( __CLASS__, 'print_builder_config' ) );
		add_action( 'wp_head', array( __CLASS__, 'print_builder_config' ) );
	}

	/**
	 * Add the settings page under Settings.
	 *
	 * @return void
	 */
	public static function register_settings_page() {
		add_options_page(
			__( 'Google Maps Divi Simplified', 'google-maps-divi-simplified' ),
			__( 'Google Maps Divi Simplified', 'google-maps-divi-simplified' ),
			'manage_options',
			'gmds-settings',
			array( __CLASS__, 'render_settings_page' )
		);
	}

	/**
	 * Register the API key setting.
	 *
	 * @return void
	 */
	public static function register_settings() {
		register_setting(
			'gmds_settings_group',
			GMDS_OPTION_API_KEY,
			array(
				'type'              => 'string',
				'sanitize_callback' => array( __CLASS__, 'sanitize_api_key' ),
				'default'           => '',
			)
		);

		register_setting(
			'gmds_settings_group',
			GMDS_OPTION_DIRECTIONS_ORIGIN,
			array(
				'type'              => 'string',
				'sanitize_callback' => array( __CLASS__, 'sanitize_api_key' ),
				'default'           => '',
			)
		);

		add_settings_section(
			'gmds_api_section',
			__( 'Google Maps API', 'google-maps-divi-simplified' ),
			array( __CLASS__, 'render_settings_section' ),
			'gmds-settings'
		);

		add_settings_field(
			GMDS_OPTION_API_KEY,
			__( 'Google Maps API Key', 'google-maps-divi-simplified' ),
			array( __CLASS__, 'render_api_key_field' ),
			'gmds-settings',
			'gmds_api_section'
		);

		add_settings_field(
			GMDS_OPTION_DIRECTIONS_ORIGIN,
			__( 'Directions Destination Address', 'google-maps-divi-simplified' ),
			array( __CLASS__, 'render_directions_origin_field' ),
			'gmds-settings',
			'gmds_api_section'
		);
	}

	/**
	 * Sanitize the key before saving.
	 *
	 * @param string $value API key.
	 * @return string
	 */
	public static function sanitize_api_key( $value ) {
		return sanitize_text_field( wp_unslash( $value ) );
	}

	/**
	 * Output the settings section text.
	 *
	 * @return void
	 */
	public static function render_settings_section() {
		echo '<p>' . esc_html__( 'Add the Google Maps API key used for geocoding and the static map image.', 'google-maps-divi-simplified' ) . '</p>';
	}

	/**
	 * Output the API key field.
	 *
	 * @return void
	 */
	public static function render_api_key_field() {
		$value = get_option( GMDS_OPTION_API_KEY, '' );
		?>
		<input
			type="text"
			name="<?php echo esc_attr( GMDS_OPTION_API_KEY ); ?>"
			id="<?php echo esc_attr( GMDS_OPTION_API_KEY ); ?>"
			value="<?php echo esc_attr( $value ); ?>"
			class="regular-text"
			autocomplete="off"
		/>
		<p class="description">
			<?php esc_html_e( 'Enable the Geocoding API and Static Maps API for this key in Google Cloud.', 'google-maps-divi-simplified' ); ?>
		</p>
		<?php
	}

	/**
	 * Output the directions origin field.
	 *
	 * @return void
	 */
	public static function render_directions_origin_field() {
		$value = get_option( GMDS_OPTION_DIRECTIONS_ORIGIN, '' );
		?>
		<input
			type="text"
			name="<?php echo esc_attr( GMDS_OPTION_DIRECTIONS_ORIGIN ); ?>"
			id="<?php echo esc_attr( GMDS_OPTION_DIRECTIONS_ORIGIN ); ?>"
			value="<?php echo esc_attr( $value ); ?>"
			class="regular-text"
			autocomplete="off"
		/>
		<p class="description">
			<?php esc_html_e( 'This address is used as the destination when visitors click Get Directions on the front-end map.', 'google-maps-divi-simplified' ); ?>
		</p>
		<?php
	}

	/**
	 * Render the plugin settings page.
	 *
	 * @return void
	 */
	public static function render_settings_page() {
		?>
		<div class="wrap">
			<h1><?php esc_html_e( 'Google Maps Divi Simplified', 'google-maps-divi-simplified' ); ?></h1>
			<form action="options.php" method="post">
				<?php
				settings_fields( 'gmds_settings_group' );
				do_settings_sections( 'gmds-settings' );
				submit_button();
				?>
			</form>
			<p>
				<?php esc_html_e( 'Created by Bartosz Klemensowski at skylandnj.com.', 'google-maps-divi-simplified' ); ?>
			</p>
		</div>
		<?php
	}

	/**
	 * Print builder globals used by the JS module preview.
	 *
	 * @return void
	 */
	public static function print_builder_config() {
		if ( is_admin() ) {
			$screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;

			if ( ! $screen || ! in_array( $screen->base, array( 'post', 'page' ), true ) ) {
				return;
			}
		} elseif ( empty( $_GET['et_fb'] ) ) {
			return;
		}

		$config = array(
			'apiKey'   => get_option( GMDS_OPTION_API_KEY, '' ),
			'noApiKey' => __( 'Set a Google Maps API key in Settings > Google Maps Divi Simplified.', 'google-maps-divi-simplified' ),
		);

		printf(
			'<script>window.gmdsDiviModule=%s;</script>',
			wp_json_encode( $config )
		);
	}

	/**
	 * Load builder helper assets in wp-admin.
	 *
	 * @param string $hook_suffix Current page suffix.
	 * @return void
	 */
	public static function enqueue_admin_assets( $hook_suffix ) {
		$allowed_hooks = array(
			'post.php',
			'post-new.php',
		);

		if ( ! in_array( $hook_suffix, $allowed_hooks, true ) ) {
			return;
		}

		self::enqueue_builder_helper();
	}

	/**
	 * Load builder helper assets in the visual builder iframe.
	 *
	 * @return void
	 */
	public static function enqueue_front_builder_assets() {
		if ( empty( $_GET['et_fb'] ) ) {
			return;
		}

		self::enqueue_builder_helper();
	}

	/**
	 * Enqueue the builder helper script that keeps the preview in sync while typing.
	 *
	 * @return void
	 */
	private static function enqueue_builder_helper() {
		wp_enqueue_script(
			'gmds-admin',
			GMDS_PLUGIN_URL . 'assets/js/gmds-admin.js',
			array( 'jquery' ),
			'0.5.1',
			true
		);

		wp_localize_script(
			'gmds-admin',
			'gmdsAdmin',
			array(
				'apiKey'  => get_option( GMDS_OPTION_API_KEY, '' ),
				'strings' => array(
					'preview'    => __( 'Geocode Address', 'google-maps-divi-simplified' ),
					'previewing' => __( 'Geocoding...', 'google-maps-divi-simplified' ),
					'success'    => __( 'Address found. Preview updated.', 'google-maps-divi-simplified' ),
					'noAddress'  => __( 'Enter an address first.', 'google-maps-divi-simplified' ),
					'noApiKey'   => __( 'Add your Google Maps API key in Settings first.', 'google-maps-divi-simplified' ),
					'loadError'  => __( 'Unable to load the Google Maps JavaScript API.', 'google-maps-divi-simplified' ),
					'authError'  => __( 'Google Maps rejected this API key for the current site.', 'google-maps-divi-simplified' ),
					'error'      => __( 'Unable to geocode this address.', 'google-maps-divi-simplified' ),
				),
			)
		);
	}

}
