<?php
/**
 * @fs_premium_only
 *
 * Pro — JSON-LD Vehicle schema for single vehicle pages.
 *
 * Emits a Schema.org Car/Vehicle object (name, brand, model, VIN, mileage,
 * colour, offers.price/priceCurrency, images, …) in the page head so search
 * engines can show rich vehicle results. Reads the importer's canonical meta
 * directly; output is built with wp_json_encode so it is always valid JSON.
 *
 * @since 2.6.0
 * @package AutomotiveFeedImport
 */

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

class AFI_Vehicle_Schema {

	/** @var AutomotiveFeedImport */
	private $afi;

	/** Currency symbol → ISO 4217 code (best-effort; defaults to USD). */
	private static $currency_codes = array(
		'$'  => 'USD',
		'€'  => 'EUR',
		'£'  => 'GBP',
		'¥'  => 'JPY',
		'C$' => 'CAD',
		'A$' => 'AUD',
		'R'  => 'ZAR',
		'₹'  => 'INR',
	);

	/**
	 * @param AutomotiveFeedImport $afi Main plugin instance.
	 */
	public function __construct($afi) {
		$this->afi = $afi;
		add_action('wp_head', array($this, 'output'), 20);
	}

	/**
	 * Output the JSON-LD script on single vehicle pages.
	 *
	 * @return void
	 */
	public function output() {
		if (! is_singular('vehicles')) {
			return;
		}

		$post_id = get_queried_object_id();
		if (! $post_id) {
			return;
		}

		$data = $this->build($post_id);
		if (empty($data)) {
			return;
		}

		echo "\n<script type=\"application/ld+json\">"
			. wp_json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)
			. "</script>\n";
	}

	/**
	 * Build the schema array for a vehicle.
	 *
	 * @param int $post_id Vehicle post ID.
	 * @return array
	 */
	private function build($post_id) {
		$get = static function ($key) use ($post_id) {
			return trim((string) get_post_meta($post_id, $key, true));
		};

		$title = $this->afi->normalize_title_display(get_the_title($post_id));
		$make  = '' !== $get('manufacturer') ? $get('manufacturer') : $get('brand');

		$schema = array(
			'@context' => 'https://schema.org',
			'@type'    => 'Car',
			'name'     => $title,
			'url'      => get_permalink($post_id),
		);

		if ('' !== $make) {
			$schema['brand'] = array(
				'@type' => 'Brand',
				'name'  => $this->afi->normalize_title_display($make),
			);
			$schema['manufacturer'] = $this->afi->normalize_title_display($make);
		}

		// Model name from the dedicated model field.
		$model = $get('model');
		if ('' !== $model) {
			$schema['model'] = $this->afi->normalize_title_display($model);
		}
		if ('' !== $get('model_year')) {
			$schema['vehicleModelDate'] = $get('model_year');
			$schema['productionDate']   = $get('model_year');
		}
		if ('' !== $get('vin')) {
			$schema['vehicleIdentificationNumber'] = $get('vin');
		}
		if ('' !== $get('stock_number')) {
			$schema['sku'] = $get('stock_number');
		}
		if ('' !== $get('mileage') && is_numeric($get('mileage'))) {
			$schema['mileageFromOdometer'] = array(
				'@type'    => 'QuantitativeValue',
				'value'    => (float) $get('mileage'),
				'unitCode' => 'SMI', // statute miles
			);
		}
		if ('' !== $get('exterior_color')) {
			$schema['color'] = $this->afi->normalize_title_display($get('exterior_color'));
		}
		if ('' !== $get('interior_color')) {
			$schema['vehicleInteriorColor'] = $this->afi->normalize_title_display($get('interior_color'));
		}
		$body = '' !== $get('body_type') ? $get('body_type') : $get('type');
		if ('' !== $body) {
			$schema['bodyType'] = $this->afi->normalize_title_display($body);
		}
		$cond = strtolower($get('designation'));
		if ('' !== $cond) {
			$schema['itemCondition'] = (false !== strpos($cond, 'new'))
				? 'https://schema.org/NewCondition'
				: 'https://schema.org/UsedCondition';
		}

		// Offer.
		$price = $get('special_web_price');
		if ('' !== $price && is_numeric($price)) {
			$schema['offers'] = array(
				'@type'         => 'Offer',
				'price'         => (float) $price,
				'priceCurrency' => $this->currency_code(),
				'availability'  => 'https://schema.org/InStock',
				'url'           => get_permalink($post_id),
			);
		}

		// Images (full-size, excluding the placeholder).
		$images = $this->images($post_id);
		if ($images) {
			$schema['image'] = $images;
		}

		return $schema;
	}

	/**
	 * Full-size image URLs for the vehicle (placeholder excluded).
	 *
	 * @param int $post_id Vehicle post ID.
	 * @return string[]
	 */
	private function images($post_id) {
		$placeholder_id = (int) get_option('automotive-feed-import_placeholder_attachment_id');
		$ids = get_children(array(
			'post_parent'    => $post_id,
			'post_type'      => 'attachment',
			'post_mime_type' => 'image',
			'numberposts'    => 10,
			'orderby'        => 'menu_order',
			'order'          => 'ASC',
			'fields'         => 'ids',
		));
		$urls = array();
		foreach ($ids as $id) {
			if ($placeholder_id && (int) $id === $placeholder_id) {
				continue;
			}
			$url = wp_get_attachment_image_url($id, 'full');
			if ($url) {
				$urls[] = $url;
			}
		}
		if (empty($urls)) {
			$thumb = get_the_post_thumbnail_url($post_id, 'full');
			if ($thumb) {
				$urls[] = $thumb;
			}
		}
		return $urls;
	}

	/**
	 * Best-effort ISO currency code from the configured symbol.
	 *
	 * @return string
	 */
	private function currency_code() {
		$symbol = (string) get_option('automotive-feed-import_currency_symbol', '$');
		$symbol = trim($symbol);
		return isset(self::$currency_codes[$symbol]) ? self::$currency_codes[$symbol] : 'USD';
	}
}
