<?php
/**
 * Taxonomy icon settings — one icon per taxonomy.
 *
 * Each taxonomy gets a single icon (from the built-in SVG sprite) or a custom
 * uploaded image. This represents the taxonomy itself (e.g. a fuel pump for
 * "Fuel Type"), not individual terms. Configured in the Taxonomies tab.
 *
 * @package ThemeREX\AutoDealer
 */

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Admin;

defined( 'ABSPATH' ) || exit;
use ThemeREX\AutoDealer\PostTypes\VehiclePostType;

class TaxonomyIconFields {

	/**
	 * Option key for taxonomy icon settings.
	 */
	public const OPTION_KEY = 'trx_ad_taxonomy_icons';

	/**
	 * Available icons in the SVG sprite.
	 *
	 * @var array<string, string> Icon ID (without trx-ad-icon- prefix) => Label.
	 */
	private const ICONS = array(
		'fuel-pump'      => 'Fuel Pump',
		'electric'       => 'Electric',
		'battery'        => 'Battery',
		'hybrid'         => 'Hybrid',
		'transmission'   => 'Transmission',
		'automatic'      => 'Automatic',
		'drivetrain'     => 'Drivetrain',
		'awd'            => 'AWD',
		'car'            => 'Car',
		'sedan'          => 'Sedan',
		'suv'            => 'SUV',
		'truck'          => 'Truck',
		'van'            => 'Van',
		'motorcycle'     => 'Motorcycle',
		'convertible'    => 'Convertible',
		'coupe'          => 'Coupe',
		'engine'         => 'Engine',
		'horsepower'     => 'Horsepower',
		'speedometer'    => 'Speedometer',
		'steering-wheel' => 'Steering Wheel',
		'ac'             => 'A/C',
		'seat'           => 'Seat',
		'sunroof'        => 'Sunroof',
		'camera'         => 'Camera',
		'bluetooth'      => 'Bluetooth',
		'navigation'     => 'Navigation',
		'wifi'           => 'Wi-Fi',
		'shield'         => 'Shield',
		'airbag'         => 'Airbag',
		'new'            => 'New',
		'used'           => 'Used',
		'certified'      => 'Certified',
		'color-palette'  => 'Color Palette',
		'mileage'        => 'Mileage',
		'price'          => 'Price',
		'calendar'       => 'Calendar',
		'door'           => 'Door',
		'weight'         => 'Weight',
		'vin'            => 'VIN',
		'tag'            => 'Tag',
		'check'          => 'Check',
		'info'           => 'Info',
		'settings'       => 'Settings',
	);

	/**
	 * Register hooks.
	 *
	 * @return void
	 */
	public function register(): void {
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueueAssets' ) );
	}

	/**
	 * Enqueue assets on the plugin settings page (taxonomies tab).
	 *
	 * @param string $hook Admin page hook.
	 * @return void
	 */
	public function enqueueAssets( string $hook ): void {
		$screen = get_current_screen();
		if ( ! $screen || $screen->id !== 'trx_ad_listing_page_trx-auto-dealer-settings' ) {
			return;
		}

		$tab = isset( $_GET['tab'] ) ? sanitize_key( $_GET['tab'] ) : 'general'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		if ( 'taxonomies' !== $tab ) {
			return;
		}

		$version = defined( 'TRX_AD_VERSION' ) ? TRX_AD_VERSION : '1.0.0';

		wp_enqueue_media();

		wp_enqueue_style(
			'trx-ad-taxonomy-icon-picker',
			TRX_AD_URL . 'assets/css/taxonomy-icon-picker.css',
			array(),
			$version
		);

		wp_enqueue_script(
			'trx-ad-taxonomy-icon-picker',
			TRX_AD_URL . 'assets/js/taxonomy-icon-picker.js',
			array( 'jquery', 'media-upload' ),
			$version,
			true
		);

		wp_localize_script(
			'trx-ad-taxonomy-icon-picker',
			'trxAdIconPicker',
			array(
				'title'        => __( 'Choose Icon', 'trx-auto-dealer' ),
				'uploadTitle'  => __( 'Select Icon Image', 'trx-auto-dealer' ),
				'uploadButton' => __( 'Use as Icon', 'trx-auto-dealer' ),
				'uploadLabel'  => __( 'Upload Custom Image', 'trx-auto-dealer' ),
				'done'         => __( 'Done', 'trx-auto-dealer' ),
			)
		);
	}

	// ------------------------------------------------------------------
	// Admin rendering helper
	// ------------------------------------------------------------------

	/**
	 * Render the compact icon picker cell (trigger button + hidden picker + hidden upload).
	 *
	 * @param string $taxonomy    Taxonomy slug (used for input names).
	 * @param string $currentIcon Current icon slug.
	 * @param int    $imageId     Current custom image attachment ID.
	 */
	public static function renderIconCell( string $taxonomy, string $currentIcon = '', int $imageId = 0 ): void {
		$spriteUrl = TRX_AD_URL . 'assets/icons/auto-dealer-icons.svg';
		$imageUrl  = $imageId > 0 ? wp_get_attachment_image_url( $imageId, 'thumbnail' ) : '';

		// Build trigger preview.
		$preview = '<span style="color:#999;">—</span>';
		if ( $imageId > 0 && $imageUrl ) {
			$preview = '<img src="' . esc_url( $imageUrl ) . '" alt="">';
		} elseif ( '' !== $currentIcon && isset( self::ICONS[ $currentIcon ] ) ) {
			$preview = '<svg width="20" height="20"><use href="' . esc_url( $spriteUrl ) . '#trx-ad-icon-' . esc_attr( $currentIcon ) . '"></use></svg>';
		}
		?>
		<div class="trx-ad-icon-wrapper">
			<input type="hidden"
				name="trx_ad_tax_icon[<?php echo esc_attr( $taxonomy ); ?>]"
				class="trx-ad-icon-picker__input"
				value="<?php echo esc_attr( $currentIcon ); ?>">
			<input type="hidden"
				name="trx_ad_tax_image[<?php echo esc_attr( $taxonomy ); ?>]"
				class="trx-ad-icon-upload__input"
				value="<?php echo $imageId > 0 ? esc_attr( (string) $imageId ) : ''; ?>">

			<span class="trx-ad-icon-trigger">
				<span class="trx-ad-icon-trigger__preview"><?php echo wp_kses( $preview, \ThemeREX\AutoDealer\allowedHtml() ); ?></span>
				<span class="trx-ad-icon-trigger__label"><?php esc_html_e( 'Choose', 'trx-auto-dealer' ); ?></span>
			</span>

			<!-- Hidden picker grid (cloned into modal on open) -->
			<div class="trx-ad-icon-picker" style="display:none;">
				<span class="trx-ad-icon-picker__item<?php echo '' === $currentIcon ? ' trx-ad-icon-picker__item--selected' : ''; ?>"
						data-icon="" title="<?php esc_attr_e( 'No icon', 'trx-auto-dealer' ); ?>">
					<span class="trx-ad-icon-picker__none">—</span>
				</span>
				<?php foreach ( self::ICONS as $slug => $label ) : ?>
					<span class="trx-ad-icon-picker__item<?php echo $currentIcon === $slug ? ' trx-ad-icon-picker__item--selected' : ''; ?>"
							data-icon="<?php echo esc_attr( $slug ); ?>"
							title="<?php echo esc_attr( $label ); ?>">
						<svg><use href="<?php echo esc_url( $spriteUrl ); ?>#trx-ad-icon-<?php echo esc_attr( $slug ); ?>"></use></svg>
					</span>
				<?php endforeach; ?>
			</div>

			<!-- Hidden upload preview (synced with modal) -->
			<div class="trx-ad-icon-upload__preview" style="display:none;">
				<?php if ( $imageUrl ) : ?>
					<img src="<?php echo esc_url( $imageUrl ); ?>" alt="">
					<span class="trx-ad-icon-upload__remove">&times;</span>
				<?php endif; ?>
			</div>
		</div>
		<?php
	}

	// ------------------------------------------------------------------
	// Public static helpers (for frontend use)
	// ------------------------------------------------------------------

	/**
	 * Get the icon/image HTML for a taxonomy.
	 *
	 * Returns custom image if set, otherwise SVG icon, or empty string.
	 *
	 * @param string $taxonomy Taxonomy slug.
	 * @param string $size     Image size for custom uploads (default: 'thumbnail').
	 * @return string HTML string.
	 */
	public static function getTaxonomyIconHtml( string $taxonomy, string $size = 'thumbnail' ): string {
		$saved = get_option( self::OPTION_KEY, array() );
		$data  = $saved[ $taxonomy ] ?? array();

		$image_id = (int) ( $data['image_id'] ?? 0 );
		if ( $image_id > 0 ) {
			$url = wp_get_attachment_image_url( $image_id, $size );
			if ( $url ) {
				return '<img src="' . esc_url( $url ) . '" alt="" class="trx-ad-taxonomy-icon-img">';
			}
		}

		$icon = $data['icon'] ?? '';
		if ( '' !== $icon ) {
			return self::getSvgIcon( $icon );
		}

		// Fallback: if the admin hasn't configured an icon for this taxonomy
		// or spec field, pick a sensible default from the built-in sprite so
		// "Show Icons" actually shows something out of the box.
		$default = self::getDefaultIconForKey( $taxonomy );
		if ( '' !== $default ) {
			return self::getSvgIcon( $default );
		}

		return '';
	}

	/**
	 * Map spec keys / taxonomy slugs to built-in icon slugs.
	 *
	 * @param string $key
	 * @return string
	 */
	private static function getDefaultIconForKey( string $key ): string {
		$map = array(
			'_year'               => 'calendar',
			'_mileage'            => 'mileage',
			'_price'              => 'price',
			'_engine'             => 'engine',
			'_horsepower'         => 'horsepower',
			'_doors'              => 'door',
			'_seats'              => 'seat',
			'_vin'                => 'vin',
			'trx_ad_make'         => 'tag',
			'trx_ad_model'        => 'car',
			'trx_ad_body_style'   => 'sedan',
			'trx_ad_fuel_type'    => 'fuel-pump',
			'trx_ad_transmission' => 'transmission',
			'trx_ad_drivetrain'   => 'drivetrain',
			'trx_ad_color'        => 'color-palette',
			'trx_ad_vehicle_type' => 'car',
			'trx_ad_condition'    => 'check',
			'trx_ad_feature'      => 'settings',
		);
		return $map[ $key ] ?? '';
	}

	/**
	 * Render an SVG use reference to the sprite.
	 *
	 * @param string $slug Icon slug (without prefix).
	 * @return string SVG HTML.
	 */
	public static function getSvgIcon( string $slug ): string {
		if ( '' === $slug || ! isset( self::ICONS[ $slug ] ) ) {
			return '';
		}

		$sprite_url = TRX_AD_URL . 'assets/icons/auto-dealer-icons.svg';

		return sprintf(
			'<svg class="trx-ad-icon" width="24" height="24"><use href="%s#trx-ad-icon-%s"></use></svg>',
			esc_url( $sprite_url ),
			esc_attr( $slug )
		);
	}

	/**
	 * Get the list of available built-in icons.
	 *
	 * @return array<string, string> Slug => Label.
	 */
	public static function getAvailableIcons(): array {
		return self::ICONS;
	}
}
