<?php
/**
 * Admin asset enqueuing for vehicle and dealer edit screens.
 *
 * @package ThemeREX\AutoDealer
 */

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Admin;

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

class AdminAssets {

	/**
	 * CSS handle. Public so other admin classes can wp_add_inline_style()
	 * against it instead of printing raw <style> tags (wp.org 2026-07 review).
	 *
	 * @var string
	 */
	public const CSS_HANDLE = 'trx-ad-admin-css';

	/**
	 * JS handle. Public so other admin classes can wp_add_inline_script()
	 * against it instead of printing raw <script> tags (wp.org 2026-07 review).
	 *
	 * @var string
	 */
	public const JS_HANDLE = 'trx-ad-admin-js';

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

	/**
	 * Enqueue admin CSS and JS on relevant screens only.
	 *
	 * @param string $hook The current admin page hook suffix.
	 * @return void
	 */
	public function enqueue( string $hook ): void {
		if ( ! $this->isRelevantScreen( $hook ) ) {
			return;
		}

		$this->enqueueStyles();
		$this->enqueueScripts();
	}

	/**
	 * Check whether the current admin screen is a vehicle or dealer edit screen.
	 *
	 * @param string $hook The admin page hook suffix.
	 * @return bool
	 */
	private function isRelevantScreen( string $hook ): bool {
		$screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;

		if ( $screen === null ) {
			return false;
		}

		// Load on every plugin submenu page (settings, leads teaser, upgrade —
		// all live under the Listings menu, so their screen ids share this prefix).
		if ( 0 === strpos( $screen->id, 'trx_ad_listing_page_' ) ) {
			return true;
		}

		// Load on post.php (edit) and post-new.php (add new).
		if ( ! in_array( $hook, array( 'post.php', 'post-new.php', 'edit.php' ), true ) ) {
			return false;
		}

		$allowed_post_types = array(
			VehiclePostType::POST_TYPE,
			DealerPostType::POST_TYPE,
		);

		return in_array( $screen->post_type, $allowed_post_types, true );
	}

	/**
	 * Enqueue admin stylesheet.
	 *
	 * @return void
	 */
	private function enqueueStyles(): void {
		wp_enqueue_style(
			self::CSS_HANDLE,
			TRX_AD_URL . 'assets/css/admin.css',
			array(),
			TRX_AD_VERSION
		);
	}

	/**
	 * Enqueue admin script and localize data.
	 *
	 * @return void
	 */
	private function enqueueScripts(): void {
		$screen = get_current_screen();

		// Settings page: load WP color picker so Appearance tab pickers work.
		if ( $screen !== null && $screen->id === 'trx_ad_listing_page_trx-auto-dealer-settings' ) {
			wp_enqueue_style( 'wp-color-picker' );
			wp_enqueue_script( 'wp-color-picker' );
			wp_add_inline_script(
				'wp-color-picker',
				'jQuery(function($){ if ($.fn && $.fn.wpColorPicker) { $(".trx-ad-color-field").wpColorPicker(); } });'
			);
		}

		// Enqueue WP media uploader + Vehicle Data meta box assets. The
		// taxonomy pickers are native multi-selects (no bundled dropdown
		// library — wp.org 2026-08 review round 5).
		$isVehicleEdit = $screen !== null
			&& $screen->post_type === VehiclePostType::POST_TYPE
			&& in_array( $screen->base, array( 'post', 'post-new' ), true );

		if ( $isVehicleEdit ) {
			wp_enqueue_media();
			wp_enqueue_script( 'jquery-ui-sortable' );

			// Vehicle Data meta box CSS.
			wp_enqueue_style(
				'trx-ad-vehicle-data-css',
				TRX_AD_URL . 'assets/css/vehicle-data-metabox.css',
				array(),
				TRX_AD_VERSION
			);

			// Vehicle Data meta box JS.
			wp_enqueue_script(
				'trx-ad-vehicle-data-js',
				TRX_AD_URL . 'assets/js/vehicle-data-metabox.js',
				array( 'jquery', 'jquery-ui-sortable' ),
				TRX_AD_VERSION,
				array( 'in_footer' => true )
			);

			wp_localize_script(
				'trx-ad-vehicle-data-js',
				'trxAdVehicleData',
				array(
					'i18n' => array(
						'confirmRemoveAll' => __( 'Remove all gallery images?', 'trx-auto-dealer' ),
						'selectImages'     => __( 'Select Vehicle Images', 'trx-auto-dealer' ),
						'addToGallery'     => __( 'Add to Gallery', 'trx-auto-dealer' ),
						'remove'           => __( 'Remove', 'trx-auto-dealer' ),
						'main'             => __( 'Main', 'trx-auto-dealer' ),
						'selectVideo'      => __( 'Select Video', 'trx-auto-dealer' ),
						'addVideo'         => __( 'Add Video', 'trx-auto-dealer' ),
						'videoPlaceholder' => __( 'https://www.youtube.com/watch?v=... or https://vimeo.com/...', 'trx-auto-dealer' ),
					),
				)
			);
		}

		wp_enqueue_script(
			self::JS_HANDLE,
			TRX_AD_URL . 'assets/js/admin.js',
			array(),
			TRX_AD_VERSION,
			array(
				'in_footer' => true,
				'strategy'  => 'defer',
			)
		);

		wp_localize_script( self::JS_HANDLE, 'trxAdAdmin', $this->getLocalizedData() );
	}

	/**
	 * Build the localized data array for the admin script.
	 *
	 * Includes taxonomy terms for dropdowns and i18n strings.
	 *
	 * @return array<string, mixed>
	 */
	private function getLocalizedData(): array {
		$data = array(
			'postType' => get_current_screen() ? get_current_screen()->post_type : '',
			'i18n'     => array(
				'vinError'     => esc_html__( 'VIN must be exactly 17 alphanumeric characters (no I, O, or Q).', 'trx-auto-dealer' ),
				'priceWarning' => esc_html__( 'Price should not be negative.', 'trx-auto-dealer' ),
				'priceError'   => esc_html__( 'Price must be a valid number.', 'trx-auto-dealer' ),
			),
			'terms'    => array(),
		);

		// Only fetch taxonomy terms for vehicle screens.
		$screen = get_current_screen();
		if ( $screen !== null && $screen->post_type === VehiclePostType::POST_TYPE ) {
			$data['terms'] = $this->getTaxonomyTerms();
		}

		return $data;
	}

	/**
	 * Fetch terms for all vehicle taxonomies.
	 *
	 * Returns an associative array keyed by taxonomy slug,
	 * each containing an array of [ id, name, slug, parent ] objects.
	 *
	 * @return array<string, array<int, array{id: int, name: string, slug: string, parent: int}>>
	 */
	private function getTaxonomyTerms(): array {
		$taxonomies = VehiclePostType::TAXONOMIES;
		$result     = array();

		foreach ( $taxonomies as $taxonomy ) {
			$terms = get_terms(
				array(
					'taxonomy'   => $taxonomy,
					'hide_empty' => false,
					'orderby'    => 'name',
					'order'      => 'ASC',
				)
			);

			if ( is_wp_error( $terms ) ) {
				$result[ $taxonomy ] = array();
				continue;
			}

			$result[ $taxonomy ] = array_map(
				static function ( \WP_Term $term ): array {
					return array(
						'id'     => $term->term_id,
						'name'   => $term->name,
						'slug'   => $term->slug,
						'parent' => $term->parent,
					);
				},
				$terms
			);
		}

		return $result;
	}
}
