<?php
/**
 * Custom columns for the vehicle admin list table.
 *
 * Adds 7 columns (year/make/model/price/status/condition/quality) plus a
 * thumbnail column, and renders each from the specs row with post-meta /
 * taxonomy fallback when the specs row is empty.
 *
 * @package ThemeREX\AutoDealer\Admin\ListTable
 */

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Admin\ListTable;

defined( 'ABSPATH' ) || exit;

use ThemeREX\AutoDealer\PostTypes\VehiclePostType;

final class Columns {

	public function __construct( private SpecsRowCache $specsCache ) {}

	public function register(): void {
		$postType = VehiclePostType::POST_TYPE;
		add_filter( "manage_{$postType}_posts_columns", array( $this, 'addColumns' ) );
		add_action( "manage_{$postType}_posts_custom_column", array( $this, 'renderColumn' ), 10, 2 );
		// Default-hide the noisier taxonomy columns. WP's Screen Options
		// panel still lets operators turn them back on per-user. With the
		// thumbnail column and 12+ data columns added, the unfiltered
		// default crammed Title down to ~50px and forced every word to
		// wrap a letter at a time — fixing the worst readability symptom.
		add_filter( 'default_hidden_columns', array( $this, 'defaultHiddenColumns' ), 10, 2 );
	}

	/**
	 * @param string[]    $hidden
	 * @param \WP_Screen  $screen
	 * @return string[]
	 */
	public function defaultHiddenColumns( array $hidden, $screen ): array {
		if ( ! ( $screen instanceof \WP_Screen ) || $screen->id !== 'edit-' . VehiclePostType::POST_TYPE ) {
			return $hidden;
		}
		// Keep the spec-backed columns visible (Year/Make/Model/Price/etc.);
		// hide the taxonomy facets by default. Users who triage by body
		// style can re-enable them via Screen Options.
		return array_values(
			array_unique(
				array_merge(
					$hidden,
					array(
						'taxonomy-trx_ad_body_style',
						'taxonomy-trx_ad_fuel_type',
						'taxonomy-trx_ad_vehicle_type',
					)
				)
			)
		);
	}

	// Column sizing CSS lives in assets/css/admin.css (enqueued on the
	// vehicles list screen by AdminAssets) — no inline <style> per wp.org
	// guidelines (2026-07 review finding).

	/**
	 * @param array<string,string> $columns Existing columns.
	 * @return array<string,string>
	 */
	public function addColumns( array $columns ): array {
		$newColumns = array();

		foreach ( $columns as $key => $label ) {
			if ( 'cb' === $key ) {
				$newColumns[ $key ]         = $label;
				$newColumns['trx_ad_thumb'] = '';
				continue;
			}

			$newColumns[ $key ] = $label;

			if ( 'title' === $key ) {
				$newColumns['trx_ad_year']      = __( 'Year', 'trx-auto-dealer' );
				$newColumns['trx_ad_make']      = __( 'Make', 'trx-auto-dealer' );
				$newColumns['trx_ad_model']     = __( 'Model', 'trx-auto-dealer' );
				$newColumns['trx_ad_price']     = __( 'Price', 'trx-auto-dealer' );
				$newColumns['trx_ad_status']    = __( 'Status', 'trx-auto-dealer' );
				$newColumns['trx_ad_condition'] = __( 'Condition', 'trx-auto-dealer' );
				$newColumns['trx_ad_quality']   = __( 'Quality', 'trx-auto-dealer' );
				$newColumns['trx_ad_featured']  = __( 'Featured', 'trx-auto-dealer' );
			}
		}

		return $newColumns;
	}

	public function renderColumn( string $column, int $postId ): void {
		$specs = $this->specsCache->get( $postId );

		// Fallback resolver — if the specs row is blank for a given column,
		// fall back to post meta / taxonomy. Defends against the case where
		// VehicleSpecsSync didn't fire (REST-imported listing, older plugin
		// version, hook conflict).
		$resolve = function ( string $col ) use ( $specs, $postId ) {
			if ( $specs && isset( $specs->$col ) && '' !== (string) $specs->$col && null !== $specs->$col ) {
				return (string) $specs->$col;
			}
			static $tax_for = array(
				'make'           => 'trx_ad_make',
				'model'          => 'trx_ad_model',
				'condition_type' => 'trx_ad_condition',
			);
			if ( isset( $tax_for[ $col ] ) ) {
				$terms = wp_get_object_terms( $postId, $tax_for[ $col ], array( 'fields' => 'names' ) );
				if ( ! is_wp_error( $terms ) && ! empty( $terms ) ) {
					return (string) $terms[0];
				}
			}
			$meta_key = '_trx_ad_' . ( 'condition_type' === $col ? 'condition' : $col );
			$value    = get_post_meta( $postId, $meta_key, true );
			return is_string( $value ) ? $value : (string) $value;
		};

		switch ( $column ) {
			case 'trx_ad_thumb':
				$this->renderThumbColumn( $postId );
				break;

			case 'trx_ad_year':
				$year = $resolve( 'year' );
				echo esc_html( '' !== $year ? $year : '---' );
				break;

			case 'trx_ad_make':
				$make = $resolve( 'make' );
				echo esc_html( '' !== $make ? $make : '---' );
				break;

			case 'trx_ad_model':
				$model = $resolve( 'model' );
				echo esc_html( '' !== $model ? $model : '---' );
				break;

			case 'trx_ad_price':
				$this->renderPriceColumn( $specs, $postId );
				break;

			case 'trx_ad_status':
				$this->renderStatusColumn( $specs, $postId );
				break;

			case 'trx_ad_condition':
				$this->renderConditionColumn( $specs, $postId );
				break;

			case 'trx_ad_quality':
				$this->renderQualityColumn( $specs );
				break;

			case 'trx_ad_featured':
				$this->renderFeaturedColumn( $postId );
				break;
		}
	}

	private function renderFeaturedColumn( int $postId ): void {
		$is_featured = (bool) get_post_meta( $postId, '_trx_ad_featured', true );
		if ( $is_featured ) {
			printf(
				'<span class="trx-ad-badge" style="background:#f59e0b;color:#fff;padding:2px 8px;border-radius:999px;font-size:0.85em;">%s</span>',
				esc_html__( 'Featured', 'trx-auto-dealer' )
			);
		} else {
			echo '<span style="color:#999;">—</span>';
		}
	}

	private function renderPriceColumn( ?object $specs, int $postId = 0 ): void {
		$pick = static function ( ?object $specs, string $col, int $postId, string $metaKey ) {
			$val = $specs && isset( $specs->$col ) ? $specs->$col : null;
			if ( null !== $val && '' !== (string) $val ) {
				return $val;
			}
			if ( $postId <= 0 ) {
				return null;
			}
			$m = get_post_meta( $postId, $metaKey, true );
			return ( '' !== $m && null !== $m ) ? $m : null;
		};

		$on_request = (bool) $pick( $specs, 'price_on_request', $postId, '_trx_ad_price_on_request' );
		$price      = (float) ( $pick( $specs, 'price', $postId, '_trx_ad_price' ) ?? 0 );
		$sale_price = (float) ( $pick( $specs, 'sale_price', $postId, '_trx_ad_sale_price' ) ?? 0 );

		if ( $on_request ) {
			esc_html_e( 'On Request', 'trx-auto-dealer' );
			return;
		}

		$settings = get_option( 'trx_ad_settings', array() );
		$currency = is_array( $settings ) && isset( $settings['currency_symbol'] )
			? $settings['currency_symbol']
			: '$';

		if ( $sale_price > 0 ) {
			printf(
				'<del>%s%s</del> <ins>%s%s</ins>',
				esc_html( $currency ),
				esc_html( number_format( $price, 0 ) ),
				esc_html( $currency ),
				esc_html( number_format( $sale_price, 0 ) )
			);
		} elseif ( $price > 0 ) {
			printf(
				'%s%s',
				esc_html( $currency ),
				esc_html( number_format( $price, 0 ) )
			);
		} else {
			echo '---';
		}
	}

	private function renderStatusColumn( ?object $specs, int $postId = 0 ): void {
		$status = $specs->status ?? null;
		if ( ( null === $status || '' === $status ) && $postId > 0 ) {
			$meta = get_post_meta( $postId, '_trx_ad_status', true );
			if ( is_string( $meta ) && '' !== $meta ) {
				$status = $meta;
			}
		}
		if ( null === $status || '' === $status ) {
			$status = 'available';
		}
		$labels = array(
			'available'   => __( 'Available', 'trx-auto-dealer' ),
			'sold'        => __( 'Sold', 'trx-auto-dealer' ),
			'reserved'    => __( 'Reserved', 'trx-auto-dealer' ),
			'coming_soon' => __( 'Coming Soon', 'trx-auto-dealer' ),
		);

		$label    = $labels[ $status ] ?? ucfirst( str_replace( '_', ' ', $status ) );
		$modifier = sanitize_html_class( str_replace( '_', '-', $status ) );

		printf(
			'<span class="trx-ad-badge trx-ad-badge--%s">%s</span>',
			esc_attr( $modifier ),
			esc_html( $label )
		);
	}

	private function renderThumbColumn( int $postId ): void {
		$thumb_id = (int) get_post_thumbnail_id( $postId );

		if ( $thumb_id > 0 ) {
			$src = wp_get_attachment_image_url( $thumb_id, array( 60, 60 ) );
			if ( is_string( $src ) && '' !== $src ) {
				printf(
					'<a href="%1$s" class="trx-ad-thumb"><img src="%2$s" alt="" loading="lazy" width="60" height="60"></a>',
					esc_url( get_edit_post_link( $postId ) ?? '' ),
					esc_url( $src )
				);
				return;
			}
		}

		echo '<span class="trx-ad-thumb trx-ad-thumb--empty" aria-hidden="true"></span>';
	}

	private function renderConditionColumn( ?object $specs, int $postId = 0 ): void {
		$condition = $specs->condition_type ?? '';
		if ( ( '' === $condition || null === $condition ) && $postId > 0 ) {
			$terms = wp_get_object_terms( $postId, 'trx_ad_condition', array( 'fields' => 'slugs' ) );
			if ( ! is_wp_error( $terms ) && ! empty( $terms ) ) {
				$condition = (string) $terms[0];
			} else {
				$meta = get_post_meta( $postId, '_trx_ad_condition_type', true );
				if ( is_string( $meta ) && '' !== $meta ) {
					$condition = $meta;
				}
			}
		}
		$labels = array(
			'new'  => __( 'New', 'trx-auto-dealer' ),
			'used' => __( 'Used', 'trx-auto-dealer' ),
			'cpo'  => __( 'CPO', 'trx-auto-dealer' ),
		);

		echo esc_html( $labels[ $condition ] ?? ( '' !== $condition ? ucfirst( (string) $condition ) : '---' ) );
	}

	private function renderQualityColumn( ?object $specs ): void {
		$score = (int) ( $specs->listing_quality ?? 0 );

		if ( $score >= 80 ) {
			$color = '#00a32a';
		} elseif ( $score >= 50 ) {
			$color = '#dba617';
		} else {
			$color = '#d63638';
		}

		printf(
			'<span style="color:%s;font-weight:600;">%d%%</span>',
			esc_attr( $color ),
			(int) $score
		);
	}
}
