<?php
/**
 * Geo meta tags output for Local SEO.
 *
 * Outputs geo.position, geo.placename, geo.region meta tags.
 *
 * @package SEOvaultSEO\LocalSEO
 */

namespace SEOvaultSEO\LocalSEO;

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

class GeoTags {

	public static function init() {
		add_action( 'wp_head', array( __CLASS__, 'output' ), 15 );
	}

	public static function output() {
		if ( is_admin() && ! wp_doing_ajax() ) {
			return;
		}

		$location = self::get_current_location();
		if ( ! $location ) {
			return;
		}

		$tags = self::build_tags( $location );
		foreach ( $tags as $name => $content ) {
			if ( '' !== $content ) {
				echo '<meta name="' . esc_attr( $name ) . '" content="' . esc_attr( $content ) . '" />' . "\n";
			}
		}
	}

	public static function get_current_location() {
		$pt = PostType::get_post_type();

		if ( is_singular( $pt ) ) {
			$post_id = get_queried_object_id();
			return LocationMeta::get_location_data_object( $post_id );
		}

		$primary_id = LocationMeta::get_primary_location();
		if ( $primary_id ) {
			return LocationMeta::get_location_data_object( $primary_id );
		}

		$options = get_option( 'seovaultseo_local_settings', array() );
		if ( ! is_array( $options ) || empty( $options ) ) {
			return null;
		}

		if ( empty( $options['business_address'] ) ) {
			return null;
		}

		$data                   = new \stdClass();
		$data->business_city    = $options['business_city'] ?? '';
		$data->business_country = $options['business_country'] ?? '';
		$data->business_state   = $options['business_state'] ?? '';
		$data->coords           = array(
			'lat'  => $options['coordinates_lat'] ?? '',
			'long' => $options['coordinates_long'] ?? '',
		);

		return $data;
	}

	public static function build_tags( $location ) {
		$tags = array(
			'geo.position'  => '',
			'geo.placename' => '',
			'geo.region'    => '',
		);

		if ( ! $location ) {
			return $tags;
		}

		if ( isset( $location->coords['lat'] ) && isset( $location->coords['long'] ) ) {
			if ( '' !== $location->coords['lat'] && '' !== $location->coords['long'] ) {
				$tags['geo.position'] = $location->coords['lat'] . ';' . $location->coords['long'];
			}
		}

		if ( isset( $location->business_city ) && '' !== $location->business_city ) {
			$tags['geo.placename'] = $location->business_city;
		}

		if ( isset( $location->business_country ) && '' !== $location->business_country ) {
			$region = $location->business_country;
			if ( isset( $location->business_state ) && '' !== $location->business_state ) {
				$region .= '-' . $location->business_state;
			}
			$tags['geo.region'] = $region;
		}

		return $tags;
	}
}
