<?php
/**
 * "Assigned dealer" sidebar meta box on the listing edit screen.
 *
 * - Admin (`manage_options`): editable dropdown of all dealer posts.
 *   Pick + save writes the `_trx_ad_dealer_id` post meta.
 * - Dealer-role user (the one who owns the listing): read-only display
 *   showing which dealer the listing is assigned to.  They cannot
 *   reassign their own listings to another dealer.
 *
 * Wires into `Admin/AdminListTable` and `Pro/MultiDealer/DataIsolation`
 * which both already read `_trx_ad_dealer_id`.
 *
 * @package ThemeREX\AutoDealer
 */

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Admin;

defined( 'ABSPATH' ) || exit;
use ThemeREX\AutoDealer\PostTypes\DealerPostType;
use ThemeREX\AutoDealer\PostTypes\VehiclePostType;

final class DealerAssignmentMetaBox {

	public const META_KEY = '_trx_ad_dealer_id';
	public const NONCE    = 'trx_ad_dealer_assignment_nonce';

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

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

	public function render( \WP_Post $post ): void {
		$current_id = (int) get_post_meta( $post->ID, self::META_KEY, true );
		$can_edit   = current_user_can( 'manage_options' );

		wp_nonce_field( self::NONCE, self::NONCE );

		if ( ! $can_edit ) {
			$this->renderReadOnly( $current_id );
			return;
		}
		$this->renderEditable( $current_id );
	}

	private function renderReadOnly( int $current_id ): void {
		if ( $current_id <= 0 ) {
			echo '<p><em>' . esc_html__( 'No dealer assigned.', 'trx-auto-dealer' ) . '</em></p>';
			return;
		}
		$dealer = get_post( $current_id );
		if ( ! ( $dealer instanceof \WP_Post ) ) {
			echo '<p><em>' . esc_html__( 'Assigned dealer not found.', 'trx-auto-dealer' ) . '</em></p>';
			return;
		}
		printf(
			'<p><strong>%s</strong></p>',
			esc_html( $dealer->post_title )
		);
		echo '<p class="description">' . esc_html__( 'Only an administrator can change which dealer a listing belongs to.', 'trx-auto-dealer' ) . '</p>';
	}

	private function renderEditable( int $current_id ): void {
		$dealers = get_posts(
			array(
				'post_type'      => DealerPostType::POST_TYPE,
				'posts_per_page' => 200,
				'post_status'    => array( 'publish', 'draft', 'pending' ),
				'orderby'        => 'title',
				'order'          => 'ASC',
			)
		);
		?>
		<p>
			<label for="trx_ad_dealer_id" class="screen-reader-text">
				<?php esc_html_e( 'Dealer', 'trx-auto-dealer' ); ?>
			</label>
			<select id="trx_ad_dealer_id" name="trx_ad_dealer_id" style="width:100%;">
				<option value="0"><?php esc_html_e( '— Unassigned —', 'trx-auto-dealer' ); ?></option>
				<?php foreach ( $dealers as $d ) : ?>
					<option value="<?php echo esc_attr( (string) $d->ID ); ?>" <?php selected( $current_id, $d->ID ); ?>>
						<?php echo esc_html( $d->post_title ); ?>
					</option>
				<?php endforeach; ?>
			</select>
		</p>
		<?php if ( empty( $dealers ) ) : ?>
			<p class="description">
				<?php
				$add = admin_url( 'post-new.php?post_type=' . DealerPostType::POST_TYPE );
				printf(
					/* translators: %s = URL to create a dealer */
					wp_kses_post( __( 'No dealers exist yet. <a href="%s">Create one</a>.', 'trx-auto-dealer' ) ),
					esc_url( $add )
				);
				?>
			</p>
		<?php endif; ?>
		<?php
	}

	public function save( int $postId, \WP_Post $post ): void {
		if ( wp_is_post_autosave( $postId ) || wp_is_post_revision( $postId ) ) {
			return;
		}
		if ( ! isset( $_POST[ self::NONCE ] )
			|| ! wp_verify_nonce( sanitize_text_field( wp_unslash( (string) $_POST[ self::NONCE ] ) ), self::NONCE ) ) {
			return;
		}

		// Only admins can change dealer assignment via this field.  Dealer
		// role users see a read-only display, so the field isn't even
		// posted by them — but defend in depth anyway.
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		if ( ! isset( $_POST['trx_ad_dealer_id'] ) ) {
			return;
		}
		$new = (int) $_POST['trx_ad_dealer_id'];
		if ( $new <= 0 ) {
			delete_post_meta( $postId, self::META_KEY );
			return;
		}
		// Validate target is actually a dealer post.
		if ( DealerPostType::POST_TYPE !== get_post_type( $new ) ) {
			return;
		}
		update_post_meta( $postId, self::META_KEY, $new );
	}
}
