<?php
/**
 * Template part: vehicle-card
 *
 * Renders a single vehicle listing card for archive grids.
 *
 * @package ThemeREX\AutoDealer
 * @version 1.0.0
 *
 * @var int $post_id Vehicle post ID (passed via extract).
 */

declare(strict_types=1);

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use function ThemeREX\AutoDealer\getVehicleSpecs;
use function ThemeREX\AutoDealer\formatPrice;

$post_id = $post_id ?? get_the_ID();
$specs   = getVehicleSpecs( (int) $post_id );

// Fall back to post meta + taxonomy when the specs row is missing or
// has empty columns. Defends against the "I created a listing, set
// year/make/model/price, but the inventory card shows blank" symptom
// caused by `VehicleSpecsSync` not having fired yet for that listing.
$pick = static function ( ?array $specs, string $col, int $postId, string $metaKey ) {
	if ( $specs && isset( $specs[ $col ] ) && '' !== (string) $specs[ $col ] && null !== $specs[ $col ] ) {
		return (string) $specs[ $col ];
	}
	$m = get_post_meta( $postId, $metaKey, true );
	return is_string( $m ) ? $m : (string) $m;
};
// Prefer the term NAME (e.g. "Toyota") over the slug stored in specs
// ("toyota") — slugs render as lowercase in the visible card title,
// which looks broken. Term name first, specs slug as fallback only when
// taxonomy assignment is missing entirely.
$pick_tax = static function ( ?array $specs, string $col, int $postId, string $taxonomy ) {
	$names = wp_get_object_terms( $postId, $taxonomy, array( 'fields' => 'names' ) );
	if ( ! is_wp_error( $names ) && ! empty( $names ) ) {
		return (string) $names[0];
	}
	if ( $specs && isset( $specs[ $col ] ) && '' !== (string) $specs[ $col ] && null !== $specs[ $col ] ) {
		return (string) $specs[ $col ];
	}
	return '';
};

$post_id_int  = (int) $post_id;
$year         = (int) $pick( $specs, 'year', $post_id_int, '_trx_ad_year' );
$make         = $pick_tax( $specs, 'make', $post_id_int, 'trx_ad_make' );
$model        = $pick_tax( $specs, 'model', $post_id_int, 'trx_ad_model' );
$price        = (float) $pick( $specs, 'price', $post_id_int, '_trx_ad_price' );
$sale_price   = (float) $pick( $specs, 'sale_price', $post_id_int, '_trx_ad_sale_price' );
$mileage      = (int) $pick( $specs, 'mileage', $post_id_int, '_trx_ad_mileage' );
$fuel_type    = $pick_tax( $specs, 'fuel_type', $post_id_int, 'trx_ad_fuel_type' );
$transmission = $pick_tax( $specs, 'transmission', $post_id_int, 'trx_ad_transmission' );
$drivetrain   = $pick_tax( $specs, 'drivetrain', $post_id_int, 'trx_ad_drivetrain' );
$condition    = $pick_tax( $specs, 'condition_type', $post_id_int, 'trx_ad_condition' );
$status       = $pick( $specs, 'status', $post_id_int, '_trx_ad_status' ) ?: 'available';
$on_request   = ! empty( $specs['price_on_request'] ) || (bool) get_post_meta( $post_id_int, '_trx_ad_price_on_request', true );
$is_featured  = (bool) get_post_meta( $post_id_int, '_trx_ad_featured', true );
$permalink    = get_permalink( $post_id_int );

$show_price          = (bool) \ThemeREX\AutoDealer\getSettings( 'show_price', 1 );
$show_featured_badge = (bool) \ThemeREX\AutoDealer\getSettings( 'show_featured_badge', 1 );
$enable_compare      = (bool) \ThemeREX\AutoDealer\getSettings( 'enable_compare', 1 );
$enable_favorites    = (bool) \ThemeREX\AutoDealer\getSettings( 'enable_favorites', 1 );

// Build title from year/make/model only when at least 2 of the 3 are
// present — avoids "2015" (year only) or "Ford" (make only) leaking into
// the card. Falls back to the post title when the constructed string
// would be too thin to identify the vehicle.
$title_parts = array_values(
	array_filter(
		array( $year > 0 ? (string) $year : '', $make, $model ),
		static fn( $p ) => '' !== trim( (string) $p )
	)
);
$card_title  = count( $title_parts ) >= 2 ? implode( ' ', $title_parts ) : get_the_title( $post_id );

$unit_label = \ThemeREX\AutoDealer\getSettings( 'distance_unit', 'km' );
?>

<article class="trx-ad-card" data-vehicle-id="<?php echo esc_attr( (string) $post_id ); ?>">

	<a href="<?php echo esc_url( (string) $permalink ); ?>" class="trx-ad-card__link" aria-label="<?php echo esc_attr( $card_title ); ?>">

		<div class="trx-ad-card__image">
			<?php if ( has_post_thumbnail( $post_id ) ) : ?>
				<?php
				echo get_the_post_thumbnail(
					$post_id,
					'medium_large',
					array(
						'class'   => 'trx-ad-card__img',
						'loading' => 'lazy',
					)
				);
				?>
			<?php else : ?>
				<div class="trx-ad-card__placeholder">
					<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" width="48" height="48" aria-hidden="true">
						<rect x="3" y="3" width="18" height="18" rx="2" ry="2"/>
						<circle cx="8.5" cy="8.5" r="1.5"/>
						<polyline points="21 15 16 10 5 21"/>
					</svg>
					<span><?php esc_html_e( 'No image', 'trx-auto-dealer' ); ?></span>
				</div>
			<?php endif; ?>

			<div class="trx-ad-card__badges">
				<?php if ( '' !== $condition ) : ?>
					<span class="trx-ad-card__badge trx-ad-card__badge--condition trx-ad-card__badge--<?php echo esc_attr( sanitize_html_class( $condition ) ); ?>">
						<?php echo esc_html( ucfirst( $condition ) ); ?>
					</span>
				<?php endif; ?>

				<?php if ( 'available' !== $status && '' !== $status ) : ?>
					<span class="trx-ad-card__badge trx-ad-card__badge--status trx-ad-card__badge--<?php echo esc_attr( sanitize_html_class( $status ) ); ?>">
						<?php echo esc_html( ucfirst( str_replace( '_', ' ', $status ) ) ); ?>
					</span>
				<?php endif; ?>

				<?php if ( $is_featured && $show_featured_badge ) : ?>
					<span class="trx-ad-card__badge trx-ad-card__badge--featured">
						<?php esc_html_e( 'Featured', 'trx-auto-dealer' ); ?>
					</span>
				<?php endif; ?>
			</div>
		</div>

		<div class="trx-ad-card__body">
			<h3 class="trx-ad-card__title"><?php echo esc_html( $card_title ); ?></h3>

			<?php if ( $show_price ) : ?>
			<div class="trx-ad-card__price">
				<?php if ( $on_request ) : ?>
					<span class="trx-ad-card__price-text"><?php esc_html_e( 'Contact for Price', 'trx-auto-dealer' ); ?></span>
				<?php elseif ( $sale_price > 0 ) : ?>
					<span class="trx-ad-card__price-original"><?php echo wp_kses( formatPrice( $price ), array( 'span' => array( 'class' => true ) ) ); ?></span>
					<span class="trx-ad-card__price-sale"><?php echo wp_kses( formatPrice( $sale_price ), array( 'span' => array( 'class' => true ) ) ); ?></span>
				<?php elseif ( $price > 0 ) : ?>
					<?php echo wp_kses( formatPrice( $price ), array( 'span' => array( 'class' => true ) ) ); ?>
				<?php else : ?>
					<span class="trx-ad-card__price-text"><?php esc_html_e( 'Price not set', 'trx-auto-dealer' ); ?></span>
				<?php endif; ?>
				<?php
				/**
				 * Fires immediately after the price block on a vehicle card.
				 * Pro PriceTracking hooks this to render the "Price reduced by $X" badge.
				 *
				 * @param int $post_id
				 */
				do_action( 'trx_ad_card_after_price', $post_id );
				?>
			</div>
			<?php endif; ?>

			<ul class="trx-ad-card__specs">
				<?php if ( $mileage > 0 ) : ?>
					<li class="trx-ad-card__spec">
						<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="M12 22c5.523 0 10-4.477 10-10S17.523 2 12 2 2 6.477 2 12s4.477 10 10 10z"/><path d="M12 6v6l4 2"/></svg>
						<?php echo esc_html( number_format_i18n( $mileage ) . ' ' . $unit_label ); ?>
					</li>
				<?php endif; ?>

				<?php if ( '' !== $fuel_type ) : ?>
					<li class="trx-ad-card__spec">
						<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="M3 22V6a2 2 0 012-2h8a2 2 0 012 2v16"/><path d="M15 10h2a2 2 0 012 2v2a2 2 0 002 2"/><path d="M7 10h4"/></svg>
						<?php echo esc_html( ucfirst( $fuel_type ) ); ?>
					</li>
				<?php endif; ?>

				<?php if ( '' !== $transmission ) : ?>
					<li class="trx-ad-card__spec">
						<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><circle cx="6" cy="6" r="2"/><circle cx="18" cy="6" r="2"/><circle cx="6" cy="18" r="2"/><line x1="6" y1="8" x2="6" y2="16"/><line x1="18" y1="8" x2="18" y2="12"/><line x1="6" y1="12" x2="18" y2="12"/></svg>
						<?php echo esc_html( ucfirst( $transmission ) ); ?>
					</li>
				<?php endif; ?>

				<?php if ( '' !== $drivetrain ) : ?>
					<li class="trx-ad-card__spec">
						<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><circle cx="12" cy="12" r="3"/><circle cx="12" cy="12" r="8"/><line x1="12" y1="4" x2="12" y2="1"/><line x1="12" y1="23" x2="12" y2="20"/></svg>
						<?php echo esc_html( strtoupper( $drivetrain ) ); ?>
					</li>
				<?php endif; ?>
			</ul>
		</div>

	</a>

	<?php if ( $enable_favorites || $enable_compare ) : ?>
	<div class="trx-ad-card__actions">
		<?php if ( $enable_favorites ) : ?>
		<button type="button" class="trx-ad-card__action trx-ad-card__action--favorite" data-vehicle-id="<?php echo esc_attr( (string) $post_id ); ?>" aria-pressed="false" aria-label="<?php esc_attr_e( 'Add to favorites', 'trx-auto-dealer' ); ?>">
			<?php echo wp_kses( \ThemeREX\AutoDealer\getActionIconSvg( 'favorite' ), \ThemeREX\AutoDealer\allowedSvgTags() ); ?>
		</button>
		<?php endif; ?>
		<?php if ( $enable_compare ) : ?>
		<button type="button" class="trx-ad-card__action trx-ad-card__action--compare" data-vehicle-id="<?php echo esc_attr( (string) $post_id ); ?>" aria-pressed="false" aria-label="<?php esc_attr_e( 'Add to compare', 'trx-auto-dealer' ); ?>">
			<?php echo wp_kses( \ThemeREX\AutoDealer\getActionIconSvg( 'compare' ), \ThemeREX\AutoDealer\allowedSvgTags() ); ?>
		</button>
		<?php endif; ?>
	</div>
	<?php endif; ?>

</article>
