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

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Taxonomies;

use ThemeREX\AutoDealer\PostTypes\VehiclePostType;

class MakeTaxonomy {

	public const TAXONOMY = 'trx_ad_make';

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

		$args = array(
			'labels'            => $labels,
			'hierarchical'      => false,
			'public'            => true,
			'show_ui'           => true,
			// false: the list-table already renders a Make column from the
			// specs row (with fallback to taxonomy terms). Two columns showing
			// the same data was the duplicate operators were complaining about.
			'show_admin_column' => false,
			'show_in_nav_menus' => true,
			'show_tagcloud'     => false,
			'show_in_rest'      => false,
			'rewrite'           => array(
				'slug'         => 'make',
				'with_front'   => false,
				'hierarchical' => false,
			),
		);

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

	/**
	 * Return the default terms for this taxonomy.
	 *
	 * @return string[]
	 */
	public function getDefaultTerms(): array {
		return array(
			'Toyota',
			'Ford',
			'BMW',
			'Mercedes-Benz',
			'Volkswagen',
			'Honda',
			'Chevrolet',
			'Audi',
			'Hyundai',
			'Kia',
			'Nissan',
			'Mazda',
			'Subaru',
			'Lexus',
			'Porsche',
			'Tesla',
			'Volvo',
			'Jeep',
			'Land Rover',
			'Jaguar',
		);
	}

	/**
	 * 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 $term ) {
			wp_insert_term( $term, self::TAXONOMY );
		}
	}
}
