<?php
/**
 * Featured-listing meta box for vehicle listings.
 *
 * Renders a compact side meta box on the listing edit screen that lets an
 * admin/editor toggle the listing's "featured" state. The checkbox is bound
 * to the `_trx_ad_featured` post meta, which `VehicleSpecsSync` mirrors into
 * the `featured` column of `wp_trx_ad_vehicle_specs` so the Featured
 * Carousel block, `[trx_ad_featured]` shortcode, and admin list table all
 * pick it up immediately on save.
 *
 * @package ThemeREX\AutoDealer
 */

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Admin;

defined( 'ABSPATH' ) || exit;

use ThemeREX\AutoDealer\PostTypes\VehiclePostType;

class FeaturedMetaBox {

	private const META_KEY = '_trx_ad_featured';
	private const NONCE    = 'trx_ad_featured_metabox';

	public function register(): void {
		add_action( 'add_meta_boxes_' . VehiclePostType::POST_TYPE, array( $this, 'addMetaBox' ) );
		add_action( 'save_post_' . VehiclePostType::POST_TYPE, array( $this, 'save' ), 12, 2 );
	}

	public function addMetaBox(): void {
		add_meta_box(
			'trx_ad_featured',
			__( 'Featured Listing', 'trx-auto-dealer' ),
			array( $this, 'render' ),
			VehiclePostType::POST_TYPE,
			'side',
			'high'
		);
	}

	public function render( \WP_Post $post ): void {
		$is_featured = (bool) get_post_meta( $post->ID, self::META_KEY, true );
		wp_nonce_field( self::NONCE, self::NONCE . '_nonce' );
		?>
		<p style="margin:0 0 8px;">
			<label>
				<input type="checkbox" name="trx_ad_featured" value="1" <?php checked( $is_featured ); ?>>
				<strong><?php esc_html_e( 'Mark as Featured', 'trx-auto-dealer' ); ?></strong>
			</label>
		</p>
		<p class="description" style="margin:0;">
			<?php
			esc_html_e(
				'Featured listings appear in the Featured Carousel block, the [trx_ad_featured] shortcode, and at the top of the inventory page (when "Show featured first" is enabled).',
				'trx-auto-dealer'
			);
			?>
		</p>
		<?php
	}

	public function save( int $post_id, \WP_Post $post ): void {
		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
			return;
		}

		if ( wp_is_post_revision( $post_id ) ) {
			return;
		}

		if ( ! isset( $_POST[ self::NONCE . '_nonce' ] ) ) {
			return;
		}

		$nonce = sanitize_text_field( wp_unslash( (string) $_POST[ self::NONCE . '_nonce' ] ) );
		if ( ! wp_verify_nonce( $nonce, self::NONCE ) ) {
			return;
		}

		if ( ! current_user_can( 'edit_post', $post_id ) ) {
			return;
		}

		$featured = ! empty( $_POST['trx_ad_featured'] ) ? '1' : '0';
		update_post_meta( $post_id, self::META_KEY, $featured );
	}
}
