<?php

namespace CarDealerPress\Templates\Sitemap;

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

$plugin_url = CARDEALERPRESS_URL;

use CarDealerPress\Includes\Database\Requests;
use CarDealerPress\includes\functions\Fn_Inventory;
use CarDealerPress\includes\helpers\helpers as helpers;
use DateTime;
use DateTimeZone;

global $wp_query;
$safe = helpers::sanitize_get( $wp_query->query_vars );

$yoast_sitemap = ( isset( $safe['sitemap'] ) ) ? $safe['sitemap'] : '';
$taxonomy      = ( isset( $safe['taxonomy'] ) ) ? $safe['taxonomy'] : $yoast_sitemap;
$db_requests   = new Requests();
$fn_inventory  = new Fn_Inventory();
$type          = '';

switch ( true ) {
	case str_contains( $taxonomy, 'new' ):
		$type = 'new';
		break;
	case str_contains( $taxonomy, 'used' ):
		$type = 'used';
		break;
	case str_contains( $taxonomy, 'video' ):
		$type = 'video';
		break;
}

$site_map_array = array();
$sitemap_output = '';
$date_raw       = wp_date( 'Y-m-d H:i P', strtotime( '-1 day', strtotime( wp_date( 'Y-m-d H:i P', time() ) ) ) );
$utc_timezone   = new DateTimeZone( 'UTC' );
$datetime       = new DateTime( $date_raw, $utc_timezone );
$last_mod       = $datetime->format( 'c' );

if ( 'video' !== $type ) {
	$site_map_array[] = array( esc_url( home_url( '/inventory/' . ucfirst( $type ) . '/' ) ), '0.9' );
	// VehicleClass.
	$site_map_db_data = $db_requests->cdp_inventory_special_request( 'saleclass,vehicleclass', ' saleclass="' . $type . '"' );
	if ( $site_map_db_data ) {
		foreach ( $site_map_db_data as $key => $data ) {
			$site_map_array[] = array(
				esc_url( home_url( '/inventory/' . ucfirst( $type ) . '/?vehicleclass=' . rawurlencode( $data['vehicleclass'] ) ) ),
				'0.8',
			);
		}
	}
	// Make.
	$site_map_db_data = $db_requests->cdp_inventory_special_request( 'saleclass,make', ' saleclass="' . $type . '"' );
	if ( $site_map_db_data ) {
		foreach ( $site_map_db_data as $key => $data ) {
			$site_map_array[] = array(
				esc_url( home_url( '/inventory/' . ucfirst( $type ) . '/' . rawurlencode( $data['make'] ) . '/' ) ),
				'0.8',
			);
		}
	}
	// Certified if Available.

	// Model.
	$site_map_db_data = $db_requests->cdp_inventory_special_request( 'saleclass,make,model', ' saleclass="' . $type . '"' );
	if ( $site_map_db_data ) {
		foreach ( $site_map_db_data as $key => $data ) {
			$site_map_array[] = array(
				esc_url( home_url( '/inventory/' . ucfirst( $type ) . '/' . rawurlencode( $data['make'] ) . '/' . rawurlencode( $data['model'] ) . '/' ) ),
				'0.7',
			);
		}
	}
	// Trim.
	$site_map_db_data = $db_requests->cdp_inventory_special_request( 'saleclass,make,model,trim', ' saleclass="' . $type . '"' );
	if ( $site_map_db_data ) {
		foreach ( $site_map_db_data as $key => $data ) {
			$site_map_array[] = array(
				esc_url( home_url( '/inventory/' . ucfirst( $type ) . '/' . rawurlencode( $data['make'] ) . '/' . rawurlencode( $data['model'] ) . '/?trim=' . rawurlencode( $data['trim'] ) ) ),
				'0.7',
			);
		}
	}
	// Vehicle Detail.
	$site_map_db_data = $db_requests->cdp_inventory_special_request( '', ' saleclass="' . $type . '"' );
	if ( $site_map_db_data ) {
		foreach ( $site_map_db_data as $key => $data ) {
			$link_params      = array(
				'year'   => $data['year'],
				'make'   => $data['make'],
				'model'  => $data['model'],
				'state'  => $data['geo_state'],
				'city'   => $data['geo_city'],
				'vin'    => $data['vin'] ?? '',
				'vms_id' => $data['vms_id'] ?? '',
			);
			$home_url         = ( new Fn_Inventory() )->generate_inventory_link( array(
				'params' => $link_params,
				'type'   => 1
			) );
			$site_map_array[] = array(
				esc_url( site_url() . $home_url ),
				'0.7',
				$data['updated'],
			);
		}
	}

	if ( $site_map_array ) {
		foreach ( $site_map_array as $data ) {
			if ( isset( $data[2] ) ) {
				$vehicle_updated = new DateTime( $data[2], $utc_timezone );
				$vehicle_mod     = $vehicle_updated->format( 'c' );
			} else {
				$vehicle_mod = $last_mod;
			}
			$value = '<url>' . "\n";
			$value .= '<loc>' . $data[0] . '</loc>' . "\n";
			$value .= '<lastmod>' . esc_html( htmlspecialchars( $vehicle_mod ) ) . '</lastmod>' . "\n";
			$value .= '<changefreq>daily</changefreq>' . "\n";
			$value .= '<priority>' . $data[1] . '</priority>' . "\n";
			$value .= '</url>' . "\n";

			$sitemap_output .= $value;
		}
		display_output( $sitemap_output, $plugin_url );
	}
} else {
	$site_map_db_data = $db_requests->cdp_inventory_special_request( '', 'video<>""' );
	if ( $site_map_db_data ) {
		foreach ( $site_map_db_data as $key => $data ) {
			$link_params = array(
				'year'   => $data['year'],
				'make'   => $data['make'],
				'model'  => $data['model'],
				'state'  => $data['geo_state'],
				'city'   => $data['geo_city'],
				'vin'    => $data['vin'] ?? '',
				'vms_id' => $data['vms_id'] ?? '',
			);
			$vdp_link    = ( new Fn_Inventory() )->generate_inventory_link( array(
				'params' => $link_params,
				'type'   => 1
			) );
			$value       = '<url>' . "\n";

			$value .= '<loc>' . urldecode( site_url() . $vdp_link ) . '</loc>' . "\n";

			$value .= '<video:video>' . "\n";
			$title = ucfirst( $data['saleclass'] ) . ' ' . $data['year'] . ' ' . $data['make'] . ' ' . $data['model'];
			$value .= '<video:thumbnail_loc>' . $data['thumbnail'] . '</video:thumbnail_loc>' . "\n";
			$value .= '<video:title><![CDATA[' . $title . ']]></video:title>' . "\n";
			$value .= '<video:description>' . ( $data['description'] ? '<![CDATA[' . $fn_inventory->cdp_limit_word_count( html_entity_decode( $data['description'] ), 50 ) . ']]>' : $title . ' ' . $data['trim'] ) . '</video:description>' . "\n";
			$value .= '<video:player_loc allow_embed="no"><![CDATA[' . $data['video'] . ']]></video:player_loc>' . "\n";
			$value .= '</video:video>' . "\n";

			$value .= '</url>' . "\n";

			$sitemap_output .= $value;
		}

		display_video( $sitemap_output, $plugin_url );
	}
}


function display_output( $output_escaped, $plugin_url ) {
	status_header( 200 );
	// Prevent the search engines from indexing the XML Sitemap.
	header( 'X-Robots-Tag: noindex, follow', true );
	header( 'Content-Type: text/xml' );
	header( 'Access-Control-Allow-Origin: *' );
	echo ent2ncr( '<?xml version="1.0" encoding="' . esc_attr( get_bloginfo( 'charset' ) ) . '"?>' );
	echo ent2ncr( '<?xml-stylesheet type="text/xsl" href="' . esc_url( $plugin_url ) . 'templates/sitemap/inc/xml-sitemap.xsl' . '"?>' );
	echo ent2ncr( '<urlset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' );
	echo ent2ncr( 'xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 https://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd" ' );
	echo ent2ncr( 'xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n" );
	// @codingStandardsIgnoreStart
	echo ent2ncr( $output_escaped );
	// @codingStandardsIgnoreEnd
	echo ent2ncr( '</urlset>' );
}

function display_video( $output_escaped, $plugin_url ) {
	status_header( 200 );
	header( 'X-Robots-Tag: noindex, follow', true );
	header( 'Content-Type: text/xml' );
	header( 'Access-Control-Allow-Origin: *' );
	echo ent2ncr( '<?xml version="1.0" encoding="' . esc_attr( get_bloginfo( 'charset' ) ) . '"?>' );
	echo ent2ncr( '<?xml-stylesheet type="text/xsl" href="' . esc_url( $plugin_url ) . 'templates/sitemap/inc/xml-sitemap-video.xsl"?>' );
	echo ent2ncr( '<urlset  xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" ' );
	echo ent2ncr( 'xmlns:video="http://www.google.com/schemas/sitemap-video/1.1">' );
	// @codingStandardsIgnoreStart
	echo ent2ncr( $output_escaped );
	// @codingStandardsIgnoreEnd
	echo ent2ncr( '</urlset>' );
}
