<?php
/**
 * Template part: single-listing
 *
 * The full single-vehicle layout body — extracted from single-vehicle.php
 * so it can be embedded by:
 *   - the default PHP single template (TemplateLoader::loadTemplate)
 *   - the Gutenberg `trx-auto-dealer/single-listing` block
 *   - the Elementor `trx_ad_single_listing` widget
 *
 * Output is byte-identical across all three callers, which is the only
 * way the auto-seeded Gutenberg + Elementor starters can match the PHP
 * default.
 *
 * Expected variable (passed via getTemplatePart):
 *   $post_id  int  Vehicle post ID. Defaults to get_the_ID() if missing.
 *
 * @package ThemeREX\AutoDealer
 * @version 1.0.0
 */

declare(strict_types=1);

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

use ThemeREX\AutoDealer\Frontend\MediaSliderRenderer;
use ThemeREX\AutoDealer\Frontend\SpecsHighlightsRenderer;
use ThemeREX\AutoDealer\Frontend\TemplateLoader;
use function ThemeREX\AutoDealer\getVehicleSpecs;
use function ThemeREX\AutoDealer\formatPrice;
use function ThemeREX\AutoDealer\getSettings;

$post_id = (int) ( $post_id ?? get_the_ID() );
if ( $post_id <= 0 ) {
	return;
}

$specs = getVehicleSpecs( $post_id );
if ( null === $specs ) {
	$specs = array();
}

$meta_or = static function ( ?string $specsValue, int $postId, string $metaKey ) {
	if ( null !== $specsValue && '' !== $specsValue ) {
		return $specsValue;
	}
	$m = get_post_meta( $postId, $metaKey, true );
	return is_string( $m ) ? $m : (string) $m;
};

$year = (int) $meta_or( isset( $specs['year'] ) ? (string) $specs['year'] : null, $post_id, '_trx_ad_year' );

// Make/model are stored as taxonomy slugs in the specs row but we want
// the human term name in the displayed title. Read the term name first;
// fall back to specs slug, then to post meta, then to the slug — covers
// imports that wrote the meta keys without setting taxonomy too.
$tax_name = static function ( int $postId, string $taxonomy ): string {
	$names = wp_get_object_terms( $postId, $taxonomy, array( 'fields' => 'names' ) );
	return ! is_wp_error( $names ) && ! empty( $names ) ? (string) $names[0] : '';
};
$make     = $tax_name( $post_id, 'trx_ad_make' );
if ( '' === $make ) {
	$make = $meta_or( isset( $specs['make'] ) ? (string) $specs['make'] : null, $post_id, '_trx_ad_make_name' );
}
$model = $tax_name( $post_id, 'trx_ad_model' );
if ( '' === $model ) {
	$model = $meta_or( isset( $specs['model'] ) ? (string) $specs['model'] : null, $post_id, '_trx_ad_model_name' );
}
$trim_level     = $specs['trim_level'] ?? get_post_meta( $post_id, '_trx_ad_trim_level', true );
$price          = (float) $meta_or( isset( $specs['price'] ) ? (string) $specs['price'] : null, $post_id, '_trx_ad_price' );
$sale_price_raw = $meta_or( isset( $specs['sale_price'] ) ? (string) $specs['sale_price'] : null, $post_id, '_trx_ad_sale_price' );
$sale_price     = '' !== $sale_price_raw && (float) $sale_price_raw > 0 ? (float) $sale_price_raw : 0.0;
$on_request     = ! empty( $specs['price_on_request'] ) || (bool) get_post_meta( $post_id, '_trx_ad_price_on_request', true );
$condition      = $specs['condition_type'] ?? get_post_meta( $post_id, '_trx_ad_condition_type', true );
$status         = $specs['status'] ?? ( get_post_meta( $post_id, '_trx_ad_status', true ) ?: 'available' );
$accident_free  = ! empty( $specs['accident_free'] ) || (bool) get_post_meta( $post_id, '_trx_ad_accident_free', true );
$mileage        = (int) $meta_or( isset( $specs['mileage'] ) ? (string) $specs['mileage'] : null, $post_id, '_trx_ad_mileage' );
$fuel_type      = $specs['fuel_type'] ?? get_post_meta( $post_id, '_trx_ad_fuel_type_name', true );
$dealer_id      = (int) get_post_meta( $post_id, '_trx_ad_dealer_id', true );
if ( $dealer_id <= 0 ) {
	$dealer_id = (int) get_post_meta( $post_id, TRX_AD_PREFIX . 'dealer_id', true );
}

// Vehicle title — same partial-fallback rule the card uses, so listings
// whose specs sync only captured year don't render as "2015".
$vt_parts      = array_values(
	array_filter(
		array( $year > 0 ? (string) $year : '', $make, $model ),
		static fn( $p ) => '' !== trim( (string) $p )
	)
);
$vehicle_title = count( $vt_parts ) >= 2 ? implode( ' ', $vt_parts ) : get_the_title( $post_id );
if ( '' !== $trim_level ) {
	$vehicle_title .= ' ' . $trim_level;
}
if ( '' === trim( $vehicle_title ) ) {
	$vehicle_title = get_the_title( $post_id );
}

$post_date      = get_the_date( 'U', $post_id );
$days_on_market = $post_date ? (int) floor( ( time() - (int) $post_date ) / 86400 ) : 0;

$price_reduced = $sale_price > 0 && $price > 0 && $sale_price < $price;

$features = wp_get_post_terms( $post_id, 'trx_ad_feature', array( 'fields' => 'names' ) );
$features = is_array( $features ) ? $features : array();

$is_ev = in_array( strtolower( (string) $fuel_type ), array( 'electric', 'phev', 'plug-in hybrid' ), true );
?>

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

	<?php TemplateLoader::getTemplatePart( 'breadcrumbs' ); ?>

	<div class="trx-ad-single__layout">

		<main class="trx-ad-single__content">

			<!-- Title & Price Header — promoted above the gallery so the most
				scan-worthy info (what + how much) lands above the fold on
				every viewport, per pre-launch testing-feedback #20. -->
			<?php $show_price_single = (bool) getSettings( 'show_price', 1 ); ?>
			<header class="trx-ad-single__header trx-ad-single__header--top">
				<h1 class="trx-ad-single__title"><?php echo esc_html( $vehicle_title ); ?></h1>

				<?php if ( $show_price_single ) : ?>
				<div class="trx-ad-single__price">
					<?php if ( $on_request ) : ?>
						<span class="trx-ad-single__price-request"><?php esc_html_e( 'Contact for Price', 'trx-auto-dealer' ); ?></span>
					<?php elseif ( $sale_price > 0 ) : ?>
						<span class="trx-ad-single__price-original"><?php echo wp_kses( formatPrice( $price ), array( 'span' => array( 'class' => true ) ) ); ?></span>
						<span class="trx-ad-single__price-sale"><?php echo wp_kses( formatPrice( $sale_price ), array( 'span' => array( 'class' => true ) ) ); ?></span>
					<?php elseif ( $price > 0 ) : ?>
						<span class="trx-ad-single__price-current"><?php echo wp_kses( formatPrice( $price ), array( 'span' => array( 'class' => true ) ) ); ?></span>
					<?php else : ?>
						<span class="trx-ad-single__price-request"><?php esc_html_e( 'Price not set', 'trx-auto-dealer' ); ?></span>
					<?php endif; ?>
				</div>
				<?php endif; ?>
			</header>

			<!-- Media Slider (Gallery + Video) — wrapped so the status badge
				can overlay the main image (feedback #16). -->
			<div class="trx-ad-single__media">
				<?php
				$status_display = (string) ( $status ?? '' );
				if ( '' !== $status_display && 'available' !== $status_display ) :
					?>
					<span class="trx-ad-single__media-badge trx-ad-single__media-badge--<?php echo esc_attr( sanitize_html_class( $status_display ) ); ?>">
						<?php echo esc_html( ucfirst( str_replace( '_', ' ', $status_display ) ) ); ?>
					</span>
				<?php endif; ?>
				<?php
				TemplateLoader::getTemplatePart(
					'media-slider',
					array(
						'slides' => MediaSliderRenderer::buildSlides( $post_id ),
						'loop'   => true,
					)
				);
				?>
			</div>

			<!-- Specs Highlights -->
			<?php
			TemplateLoader::getTemplatePart(
				'specs-highlights',
				array( 'items' => SpecsHighlightsRenderer::buildItems( $post_id ) )
			);
			?>

			<!-- Trust Badges -->
			<div class="trx-ad-single__badges">
				<?php if ( '' !== (string) $condition ) : ?>
					<span class="trx-ad-single__badge trx-ad-single__badge--condition">
						<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="M22 11.08V12a10 10 0 11-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
						<?php echo esc_html( ucfirst( (string) $condition ) ); ?>
					</span>
				<?php endif; ?>

				<?php if ( $accident_free ) : ?>
					<span class="trx-ad-single__badge trx-ad-single__badge--accident-free">
						<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 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>
						<?php esc_html_e( 'Accident-Free', 'trx-auto-dealer' ); ?>
					</span>
				<?php endif; ?>

				<?php if ( $price_reduced ) : ?>
					<span class="trx-ad-single__badge trx-ad-single__badge--price-reduced">
						<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"><line x1="12" y1="1" x2="12" y2="23"/><path d="M17 5H9.5a3.5 3.5 0 000 7h5a3.5 3.5 0 010 7H6"/></svg>
						<?php esc_html_e( 'Price Reduced', 'trx-auto-dealer' ); ?>
					</span>
				<?php endif; ?>

				<?php if ( $days_on_market > 0 ) : ?>
					<span class="trx-ad-single__badge trx-ad-single__badge--days">
						<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="10"/><polyline points="12 6 12 12 16 14"/></svg>
						<?php
						printf(
							/* translators: %d: number of days */
							esc_html( _n( '%d day on market', '%d days on market', $days_on_market, 'trx-auto-dealer' ) ),
							absint( $days_on_market )
						);
						?>
					</span>
				<?php endif; ?>
			</div>

			<!-- Description -->
			<?php
			// Avoid running the full `the_content` filter chain here:
			// when this partial is rendered from inside the
			// `trx-auto-dealer/single-listing` block (which itself runs
			// inside `the_content` on a Gutenberg layout), `the_content`
			// would re-trigger `do_blocks`, re-render our block, and
			// recurse until the stack overflows. Apply the safe subset
			// of filters explicitly instead.
			$raw_content = get_the_content( null, false, $post_id );
			if ( '' !== trim( (string) $raw_content ) ) :
				$content = do_blocks( $raw_content );
				$content = wpautop( $content );
				$content = do_shortcode( $content );
				?>
				<div class="trx-ad-single__description">
					<h2><?php esc_html_e( 'Description', 'trx-auto-dealer' ); ?></h2>
					<div class="trx-ad-single__description-text">
						<?php echo wp_kses( $content, \ThemeREX\AutoDealer\allowedHtml() ); ?>
					</div>
				</div>
			<?php endif; ?>

			<!-- Specs Table -->
			<?php TemplateLoader::getTemplatePart( 'vehicle-specs-table', array( 'specs' => $specs ) ); ?>

			<?php
			/**
			 * Fires immediately after the specs table on the single-listing page.
			 * Pro CustomFields hooks this to render the per-listing custom field block.
			 *
			 * @param int $post_id
			 */
			do_action( 'trx_ad_after_specs_table', $post_id );
			?>

			<!-- Features -->
			<?php if ( ! empty( $features ) ) : ?>
				<div class="trx-ad-single__features">
					<h2 class="trx-ad-single__features-heading"><?php esc_html_e( 'Features & Options', 'trx-auto-dealer' ); ?></h2>
					<ul class="trx-ad-single__features-list">
						<?php foreach ( $features as $feature_name ) : ?>
							<li class="trx-ad-single__features-item">
								<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" aria-hidden="true"><polyline points="20 6 9 17 4 12"/></svg>
								<?php echo esc_html( $feature_name ); ?>
							</li>
						<?php endforeach; ?>
					</ul>
				</div>
			<?php endif; ?>

			<!-- EV Panel -->
			<?php if ( $is_ev ) : ?>
				<div class="trx-ad-single__ev-panel">
					<h2 class="trx-ad-single__ev-panel-heading">
						<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>
						<?php esc_html_e( 'Electric Vehicle Details', 'trx-auto-dealer' ); ?>
					</h2>
					<div class="trx-ad-single__ev-panel-grid">
						<?php
						$ev_fields = array(
							'battery_capacity' => array( __( 'Battery Capacity', 'trx-auto-dealer' ), 'kWh' ),
							'electric_range'   => array( __( 'Electric Range', 'trx-auto-dealer' ), getSettings( 'distance_unit', 'km' ) ),
							'charge_time'      => array( __( 'Charge Time', 'trx-auto-dealer' ), '' ),
						);

						foreach ( $ev_fields as $ev_key => $ev_info ) :
							$ev_val = $specs[ $ev_key ] ?? '';
							if ( '' === (string) $ev_val || null === $ev_val ) {
								continue;
							}
							$ev_display = is_numeric( $ev_val )
								? number_format_i18n( (float) $ev_val ) . ( '' !== $ev_info[1] ? ' ' . $ev_info[1] : '' )
								: (string) $ev_val;
							?>
							<div class="trx-ad-single__ev-stat">
								<span class="trx-ad-single__ev-stat-label"><?php echo esc_html( $ev_info[0] ); ?></span>
								<span class="trx-ad-single__ev-stat-value"><?php echo esc_html( $ev_display ); ?></span>
							</div>
						<?php endforeach; ?>
					</div>
				</div>
			<?php endif; ?>

			<!-- Actions row -->
			<div class="trx-ad-single__actions">
				<button type="button" class="trx-ad-single__action-btn trx-ad-card__action--favorite" data-vehicle-id="<?php echo esc_attr( (string) $post_id ); ?>" aria-pressed="false">
					<?php echo wp_kses( \ThemeREX\AutoDealer\getActionIconSvg( 'favorite' ), \ThemeREX\AutoDealer\allowedSvgTags() ); ?>
					<?php esc_html_e( 'Save', 'trx-auto-dealer' ); ?>
				</button>
				<button type="button" class="trx-ad-single__action-btn trx-ad-card__action--compare" data-vehicle-id="<?php echo esc_attr( (string) $post_id ); ?>" aria-pressed="false">
					<?php echo wp_kses( \ThemeREX\AutoDealer\getActionIconSvg( 'compare' ), \ThemeREX\AutoDealer\allowedSvgTags() ); ?>
					<?php esc_html_e( 'Compare', 'trx-auto-dealer' ); ?>
				</button>
				<button type="button" class="trx-ad-single__action-btn" data-trx-ad-print>
					<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><polyline points="6 9 6 2 18 2 18 9"/><path d="M6 18H4a2 2 0 01-2-2v-5a2 2 0 012-2h16a2 2 0 012 2v5a2 2 0 01-2 2h-2"/><rect x="6" y="14" width="12" height="8"/></svg>
					<?php esc_html_e( 'Print', 'trx-auto-dealer' ); ?>
				</button>
				<?php
				/**
				 * Extension point for extra single-listing action buttons.
				 * Pro hooks its "Reserve — deposit" button here (R2-7).
				 *
				 * @param int $post_id Listing ID.
				 */
				do_action( 'trx_ad_single_actions', $post_id );
				?>
			</div>

			<?php
			TemplateLoader::getTemplatePart(
				'vehicle-similar',
				array(
					'post_id' => $post_id,
					'limit'   => 4,
				)
			);

			TemplateLoader::getTemplatePart(
				'vehicle-recently-viewed',
				array(
					'exclude' => $post_id,
					'limit'   => 4,
				)
			);
			?>

		</main>

		<!-- Sidebar -->
		<aside class="trx-ad-single__sidebar">
			<?php
			if ( $dealer_id > 0 ) {
				TemplateLoader::getTemplatePart( 'dealer-card', array( 'dealer_id' => $dealer_id ) );
				do_action( 'trx_ad_after_dealer_card', $dealer_id, $post_id );
			}

			TemplateLoader::getTemplatePart(
				'listing-form',
				array(
					'form_id' => 'inquiry',
					'post_id' => $post_id,
					'title'   => __( 'Inquire About This Vehicle', 'trx-auto-dealer' ),
				)
			);
			?>
		</aside>

	</div>

</div>

<!-- Sticky mobile contact bar -->
<?php
if ( $dealer_id > 0 ) :
	$dealer_meta = \ThemeREX\AutoDealer\getDealerMeta( $dealer_id );
	$d_phone     = $dealer_meta['phone'] ?? '';
	$d_whatsapp  = preg_replace( '/[^0-9]/', '', (string) ( $dealer_meta['whatsapp'] ?? '' ) );
	$d_email     = $dealer_meta['email'] ?? '';
	?>
	<div class="trx-ad-mobile-bar" id="trx-ad-mobile-bar">
		<?php if ( '' !== $d_phone ) : ?>
			<a href="tel:<?php echo esc_attr( $d_phone ); ?>" class="trx-ad-mobile-bar__btn trx-ad-mobile-bar__btn--call">
				<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="M22 16.92v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07 19.5 19.5 0 01-6-6 19.79 19.79 0 01-3.07-8.67A2 2 0 014.11 2h3a2 2 0 012 1.72 12.84 12.84 0 00.7 2.81 2 2 0 01-.45 2.11L8.09 9.91a16 16 0 006 6l1.27-1.27a2 2 0 012.11-.45 12.84 12.84 0 002.81.7A2 2 0 0122 16.92z"/></svg>
				<?php esc_html_e( 'Call', 'trx-auto-dealer' ); ?>
			</a>
		<?php endif; ?>
		<?php if ( '' !== (string) $d_whatsapp ) : ?>
			<a href="https://wa.me/<?php echo esc_attr( (string) $d_whatsapp ); ?>" class="trx-ad-mobile-bar__btn trx-ad-mobile-bar__btn--whatsapp" target="_blank" rel="noopener noreferrer">
				<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347z"/><path d="M12 0C5.373 0 0 5.373 0 12c0 2.127.555 4.124 1.529 5.857L.06 23.524l5.826-1.529A11.94 11.94 0 0012 24c6.627 0 12-5.373 12-12S18.627 0 12 0zm0 21.818c-1.93 0-3.762-.523-5.362-1.51l-.384-.228-3.985 1.046 1.064-3.885-.25-.397A9.77 9.77 0 012.182 12c0-5.414 4.404-9.818 9.818-9.818S21.818 6.586 21.818 12 17.414 21.818 12 21.818z"/></svg>
				<?php esc_html_e( 'WhatsApp', 'trx-auto-dealer' ); ?>
			</a>
		<?php endif; ?>
		<?php if ( '' !== $d_email ) : ?>
			<a href="mailto:<?php echo esc_attr( $d_email ); ?>" class="trx-ad-mobile-bar__btn trx-ad-mobile-bar__btn--email">
				<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></svg>
				<?php esc_html_e( 'Email', 'trx-auto-dealer' ); ?>
			</a>
		<?php endif; ?>
	</div>
<?php endif; ?>
