<?php
/**
 * KML Sitemap generator for locations.
 *
 * @package SEOvaultSEO\LocalSEO
 */

namespace SEOvaultSEO\LocalSEO;

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

class KmlSitemap {

	public static function init() {
		add_action( 'init', array( __CLASS__, 'register_rewrites' ) );
		add_action( 'template_redirect', array( __CLASS__, 'output_kml' ), 0 );
	}

	public static function register_rewrites() {
		add_rewrite_rule( '^locations\.kml$', 'index.php?seovault_kml=1', 'top' );
		add_rewrite_tag( '%seovault_kml%', '([0-9]+)' );
	}

	public static function output_kml() {
		$kml = get_query_var( 'seovault_kml' );
		if ( ! $kml ) {
			return;
		}

		$pt    = PostType::get_post_type();
		$query = new \WP_Query(
			array(
				'post_type'      => $pt,
				'post_status'    => 'publish',
				'posts_per_page' => -1,
				// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key -- KML export needs locations with coordinates meta.
				'meta_key'       => LocationMeta::META_PREFIX . 'coordinates_lat',
				'meta_compare'   => 'EXISTS',
			)
		);

		header( 'Content-Type: application/vnd.google-earth.kml+xml; charset=utf-8' );

		$xml  = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
		$xml .= '<kml xmlns="http://www.opengis.net/kml/2.2">' . "\n";
		$xml .= '<Document>' . "\n";
		$xml .= '<name>' . esc_html( get_bloginfo( 'name' ) . ' - Locations' ) . '</name>' . "\n";

		if ( $query->have_posts() ) {
			while ( $query->have_posts() ) {
				$query->the_post();
				$post_id = get_the_ID();
				$lat     = LocationMeta::get( $post_id, 'coordinates_lat' );
				$lng     = LocationMeta::get( $post_id, 'coordinates_long' );
				$address = LocationMeta::get( $post_id, 'business_address' );
				$city    = LocationMeta::get( $post_id, 'business_city' );
				$phone   = LocationMeta::get( $post_id, 'business_phone' );

				if ( '' === $lat || '' === $lng ) {
					continue;
				}

				$xml .= '<Placemark>' . "\n";
				$xml .= '<name>' . esc_html( get_the_title( $post_id ) ) . '</name>' . "\n";
				$xml .= '<description><![CDATA[';
				if ( $address ) {
					$xml .= esc_html( $address );
				}
				if ( $city ) {
					$xml .= ', ' . esc_html( $city );
				}
				if ( $phone ) {
					$xml .= ' | ' . esc_html( $phone );
				}
				$xml .= ']]></description>' . "\n";
				$xml .= '<Point><coordinates>' . esc_html( $lng ) . ',' . esc_html( $lat ) . ',0</coordinates></Point>' . "\n";
				$xml .= '</Placemark>' . "\n";
			}
			wp_reset_postdata();
		}

		$xml .= '</Document>' . "\n";
		$xml .= '</kml>';

		// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- KML document built with escaped fragments.
		echo $xml;
		exit;
	}

	public static function get_kml_url() {
		return home_url( '/locations.kml' );
	}
}
