<?php
/**
 * Transmission taxonomy.
 *
 * @package ThemeREX\AutoDealer
 */

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Taxonomies;

use ThemeREX\AutoDealer\PostTypes\VehiclePostType;

class TransmissionTaxonomy {

	public const TAXONOMY = 'trx_ad_transmission';

	/**
	 * Register the taxonomy.
	 *
	 * @return void
	 */
	public function register(): void {
		$labels = array(
			'name'                  => _x( 'Transmissions', 'Taxonomy general name', 'trx-auto-dealer' ),
			'singular_name'         => _x( 'Transmission', 'Taxonomy singular name', 'trx-auto-dealer' ),
			'search_items'          => __( 'Search Transmissions', 'trx-auto-dealer' ),
			'all_items'             => __( 'All Transmissions', 'trx-auto-dealer' ),
			'edit_item'             => __( 'Edit Transmission', 'trx-auto-dealer' ),
			'update_item'           => __( 'Update Transmission', 'trx-auto-dealer' ),
			'add_new_item'          => __( 'Add New Transmission', 'trx-auto-dealer' ),
			'new_item_name'         => __( 'New Transmission Name', 'trx-auto-dealer' ),
			'menu_name'             => __( 'Transmissions', 'trx-auto-dealer' ),
			'not_found'             => __( 'No transmissions found.', 'trx-auto-dealer' ),
			'no_terms'              => __( 'No transmissions', 'trx-auto-dealer' ),
			'items_list_navigation' => __( 'Transmissions list navigation', 'trx-auto-dealer' ),
			'items_list'            => __( 'Transmissions list', 'trx-auto-dealer' ),
			'back_to_items'         => __( '&larr; Back to Transmissions', 'trx-auto-dealer' ),
		);

		$args = array(
			'labels'            => $labels,
			'hierarchical'      => false,
			'public'            => true,
			'show_ui'           => true,
			'show_admin_column' => false,
			'show_in_nav_menus' => true,
			'show_tagcloud'     => false,
			'show_in_rest'      => false,
			'rewrite'           => array(
				'slug'       => 'transmission',
				'with_front' => false,
			),
		);

		register_taxonomy( self::TAXONOMY, VehiclePostType::POST_TYPE, $args );
	}

	/**
	 * Return the default terms for this taxonomy.
	 *
	 * @return array<string, string> Slug => Name.
	 */
	public function getDefaultTerms(): array {
		return array(
			'manual'      => 'Manual',
			'automatic'   => 'Automatic',
			'cvt'         => 'CVT',
			'semi-auto'   => 'Semi-Automatic',
			'dual-clutch' => 'Dual Clutch',
		);
	}

	/**
	 * Insert default terms if the taxonomy is empty.
	 *
	 * @return void
	 */
	public function insertDefaultTerms(): void {
		$existing = wp_count_terms(
			array(
				'taxonomy'   => self::TAXONOMY,
				'hide_empty' => false,
			)
		);
		if ( is_wp_error( $existing ) || (int) $existing > 0 ) {
			return;
		}

		foreach ( $this->getDefaultTerms() as $slug => $name ) {
			wp_insert_term( $name, self::TAXONOMY, array( 'slug' => $slug ) );
		}
	}
}
