<?php
/**
 * Condition taxonomy (New, Used, CPO).
 *
 * @package ThemeREX\AutoDealer
 */

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Taxonomies;

use ThemeREX\AutoDealer\PostTypes\VehiclePostType;

class ConditionTaxonomy {

	public const TAXONOMY = 'trx_ad_condition';

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

		$args = array(
			'labels'            => $labels,
			'hierarchical'      => false,
			'public'            => true,
			'show_ui'           => true,
			// false: list-table Condition column already renders this with fallback.
			'show_admin_column' => false,
			'show_in_nav_menus' => true,
			'show_tagcloud'     => false,
			'show_in_rest'      => false,
			'rewrite'           => array(
				'slug'       => 'condition',
				'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(
			'new'  => 'New',
			'used' => 'Used',
			'cpo'  => 'Certified Pre-Owned',
		);
	}

	/**
	 * 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 ) );
		}
	}
}
