<?php
/**
 * Vehicle custom post type registration.
 *
 * @package ThemeREX\AutoDealer
 */

declare(strict_types=1);

namespace ThemeREX\AutoDealer\PostTypes;

defined( 'ABSPATH' ) || exit;

class VehiclePostType {

	public const POST_TYPE = 'trx_ad_listing';

	/**
	 * All taxonomy slugs that belong to this post type.
	 *
	 * @var string[]
	 */
	public const TAXONOMIES = array(
		'trx_ad_make',
		'trx_ad_model',
		'trx_ad_body_style',
		'trx_ad_fuel_type',
		'trx_ad_transmission',
		'trx_ad_drivetrain',
		'trx_ad_color',
		'trx_ad_feature',
		'trx_ad_vehicle_type',
		'trx_ad_condition',
	);

	/**
	 * Register the post type.
	 *
	 * Hooked to `init`.
	 *
	 * @return void
	 */
	/**
	 * Force the classic editor for listings.
	 *
	 * The Vehicle Data meta box owns description (via wp_editor in the
	 * Details tab) and every spec/taxonomy/media field. Gutenberg's
	 * meta-box-loader flow doesn't reliably round-trip our $_POST-based
	 * save handlers (the meta box ends up in a `method="get"` form
	 * outside Gutenberg's iframe-POST scope), so a save through the
	 * block editor would silently drop video URLs, gallery edits,
	 * checkbox toggles, etc. Classic editor avoids the entire problem.
	 *
	 * Hooked to `use_block_editor_for_post_type`.
	 *
	 * @param bool   $use       Whether to use the block editor.
	 * @param string $post_type Post type slug being checked.
	 * @return bool
	 */
	public function disableBlockEditor( bool $use, string $post_type ): bool {
		return self::POST_TYPE === $post_type ? false : $use;
	}

	public function register(): void {
		$archive_slug = (string) get_option( 'trx_ad_archive_slug', 'inventory' );
		if ( $archive_slug === '' ) {
			$archive_slug = 'inventory';
		}

		$labels = array(
			'name'                  => _x( 'Listings', 'Post type general name', 'trx-auto-dealer' ),
			'singular_name'         => _x( 'Listing', 'Post type singular name', 'trx-auto-dealer' ),
			'menu_name'             => _x( 'Listings', 'Admin menu', 'trx-auto-dealer' ),
			'name_admin_bar'        => _x( 'Listing', 'Add new on admin bar', 'trx-auto-dealer' ),
			'add_new'               => __( 'Add New', 'trx-auto-dealer' ),
			'add_new_item'          => __( 'Add New Listing', 'trx-auto-dealer' ),
			'new_item'              => __( 'New Listing', 'trx-auto-dealer' ),
			'edit_item'             => __( 'Edit Listing', 'trx-auto-dealer' ),
			'view_item'             => __( 'View Listing', 'trx-auto-dealer' ),
			'all_items'             => __( 'All Listings', 'trx-auto-dealer' ),
			'search_items'          => __( 'Search Listings', 'trx-auto-dealer' ),
			'parent_item_colon'     => __( 'Parent Listing:', 'trx-auto-dealer' ),
			'not_found'             => __( 'No listings found.', 'trx-auto-dealer' ),
			'not_found_in_trash'    => __( 'No listings found in Trash.', 'trx-auto-dealer' ),
			'featured_image'        => __( 'Listing Main Image', 'trx-auto-dealer' ),
			'set_featured_image'    => __( 'Set listing main image', 'trx-auto-dealer' ),
			'remove_featured_image' => __( 'Remove listing main image', 'trx-auto-dealer' ),
			'use_featured_image'    => __( 'Use as listing main image', 'trx-auto-dealer' ),
			'archives'              => __( 'Listing Archives', 'trx-auto-dealer' ),
			'filter_items_list'     => __( 'Filter listings list', 'trx-auto-dealer' ),
			'items_list_navigation' => __( 'Listings list navigation', 'trx-auto-dealer' ),
			'items_list'            => __( 'Listings list', 'trx-auto-dealer' ),
		);

		$args = array(
			'labels'             => $labels,
			'public'             => true,
			'publicly_queryable' => true,
			'show_ui'            => true,
			'show_in_menu'       => true,
			'show_in_rest'       => true,
			'query_var'          => true,
			'rewrite'            => array(
				'slug'       => $archive_slug,
				'with_front' => false,
			),
			'capability_type'    => 'trx_ad_listing',
			'map_meta_cap'       => true,
			'has_archive'        => true,
			'hierarchical'       => false,
			'menu_position'      => 25,
			'menu_icon'          => 'dashicons-car',
			// Drop 'editor' — the Details tab in our Vehicle Data meta box
			// owns description via its own wp_editor instance.
			'supports'           => array( 'title', 'thumbnail', 'excerpt', 'revisions' ),
			'taxonomies'         => self::TAXONOMIES,
		);

		register_post_type( self::POST_TYPE, $args );

		add_filter( 'wp_untrash_post_status', array( self::class, 'restoreToPublishedStatus' ), 10, 3 );
	}

	/**
	 * Restore trashed listings back to "publish" instead of WP's "draft" default.
	 *
	 * Dealerships expect a trashed listing to come back live exactly as it was —
	 * losing visibility on Restore is surprising and undoes the operator's intent
	 * (they meant Trash → Restore as an undo, not as "send to draft for review").
	 * Only override when the previous status really was `publish` so private /
	 * pending listings retain their original state.
	 *
	 * @param string $new_status      The status WP would otherwise apply.
	 * @param int    $post_id         Restored post ID.
	 * @param string $previous_status The post's status before it was trashed.
	 * @return string
	 */
	public static function restoreToPublishedStatus( string $new_status, int $post_id, string $previous_status ): string {
		$post = get_post( $post_id );
		if ( ! $post instanceof \WP_Post || self::POST_TYPE !== $post->post_type ) {
			return $new_status;
		}
		if ( 'publish' === $previous_status ) {
			return 'publish';
		}
		return $new_status;
	}
}
