<?php

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Frontend;

use ThemeREX\AutoDealer\Admin\TaxonomyIconFields;
use ThemeREX\AutoDealer\PostTypes\VehiclePostType;
use ThemeREX\AutoDealer\Taxonomies\UserTaxonomyManager;
use function ThemeREX\AutoDealer\getVehicleSpecs;
use function ThemeREX\AutoDealer\getSettings;

/**
 * Builds the specs highlights data for a listing post.
 *
 * @package ThemeREX\AutoDealer
 */
class SpecsHighlightsRenderer {

	/**
	 * Build the specs highlight items for a post.
	 *
	 * Dynamically includes all taxonomies that have terms assigned,
	 * plus key meta fields (mileage, year).
	 *
	 * @param int $postId Post ID.
	 * @return array<int, array{icon: string, label: string, value: string}>
	 */
	/**
	 * Get all available source options for the widget control.
	 *
	 * @return array<string, string> Key => Label.
	 */
	public static function getSourceOptions(): array {
		$options  = array();
		$disabled = UserTaxonomyManager::getDisabled();

		$options['_year']    = __( 'Year', 'trx-auto-dealer' );
		$options['_mileage'] = __( 'Mileage', 'trx-auto-dealer' );

		foreach ( VehiclePostType::TAXONOMIES as $taxonomy ) {
			if ( in_array( $taxonomy, $disabled, true ) ) {
				continue;
			}
			$taxObj               = get_taxonomy( $taxonomy );
			$label                = $taxObj ? $taxObj->labels->name : $taxonomy;
			$options[ $taxonomy ] = $label;
		}

		$customTaxonomies = UserTaxonomyManager::getAll();
		foreach ( $customTaxonomies as $tax ) {
			$slug = $tax['slug'] ?? '';
			if ( '' !== $slug && taxonomy_exists( $slug ) ) {
				$options[ $slug ] = $tax['label'] ?? $slug;
			}
		}

		return $options;
	}

	public static function buildItems( int $postId, array $selectedSources = array() ): array {
		$specs = getVehicleSpecs( $postId );
		if ( ! is_array( $specs ) ) {
			$specs = array();
		}

		$unit = getSettings( 'distance_unit', 'km' );

		// If no sources specified, use all available.
		if ( empty( $selectedSources ) ) {
			$selectedSources = array_keys( self::getSourceOptions() );
		}

		$items = array();

		foreach ( $selectedSources as $source ) {
			$item = self::buildSingleItem( $source, $postId, $specs, $unit );
			if ( null !== $item ) {
				$items[] = $item;
			}
		}

		return $items;
	}

	/**
	 * Build a single spec item by source key.
	 *
	 * @param string $source Source key (taxonomy slug or _year, _mileage).
	 * @param int    $postId Post ID.
	 * @param array  $specs  Specs data.
	 * @param string $unit   Distance unit.
	 * @return array{icon: string, label: string, value: string}|null
	 */
	private static function buildSingleItem( string $source, int $postId, array $specs, string $unit ): ?array {
		// Spec pseudo-keys resolve through getTaxonomyIconHtml() like taxonomy
		// sources, so admin-chosen icons apply here too instead of hardcoded
		// glyphs (tester feedback #8); the built-in defaults map keeps the
		// calendar/mileage icons when nothing is configured.
		if ( '_year' === $source ) {
			$year = isset( $specs['year'] ) ? (int) $specs['year'] : 0;
			if ( $year > 0 ) {
				return array(
					'icon'  => TaxonomyIconFields::getTaxonomyIconHtml( '_year' ),
					'label' => __( 'Year', 'trx-auto-dealer' ),
					'value' => (string) $year,
				);
			}
			return null;
		}

		if ( '_mileage' === $source ) {
			$mileage = isset( $specs['mileage'] ) ? (int) $specs['mileage'] : 0;
			if ( $mileage > 0 ) {
				return array(
					'icon'  => TaxonomyIconFields::getTaxonomyIconHtml( '_mileage' ),
					'label' => __( 'Mileage', 'trx-auto-dealer' ),
					'value' => number_format( $mileage ) . ' ' . $unit,
				);
			}
			return null;
		}

		// Taxonomy source.
		if ( ! taxonomy_exists( $source ) ) {
			return null;
		}

		$termName = self::getFirstTermName( $postId, $source );
		if ( '' === $termName ) {
			return null;
		}

		$taxObj = get_taxonomy( $source );
		$label  = $taxObj ? $taxObj->labels->singular_name : $source;

		return array(
			'icon'  => TaxonomyIconFields::getTaxonomyIconHtml( $source ),
			'label' => $label,
			'value' => $termName,
		);
	}

	/**
	 * Get the first term name for a taxonomy on a post.
	 *
	 * @param int    $postId   Post ID.
	 * @param string $taxonomy Taxonomy slug.
	 * @return string Term name or empty string.
	 */
	private static function getFirstTermName( int $postId, string $taxonomy ): string {
		$terms = wp_get_post_terms( $postId, $taxonomy, array( 'fields' => 'names' ) );

		if ( is_wp_error( $terms ) || empty( $terms ) ) {
			return '';
		}

		return (string) $terms[0];
	}
}
