<?php
/**
 * Template part: dealer-listings
 *
 * Renders a vehicle grid filtered to a single dealer. Routes through
 * VehicleQuery so the result set matches the REST API for the same
 * inputs (ADR-03).
 *
 * @package ThemeREX\AutoDealer
 * @version 1.0.0
 *
 * @var int   $dealer_id  Dealer post ID (passed via extract).
 * @var int   $per_page   Optional. Listings to show. Default 12.
 * @var array $args       Optional extra args for FilterParams.
 */

declare(strict_types=1);

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

use ThemeREX\AutoDealer\Frontend\TemplateLoader;
use ThemeREX\AutoDealer\Search\FilterParams;
use ThemeREX\AutoDealer\Search\VehicleQuery;

if ( ! isset( $dealer_id ) || (int) $dealer_id < 1 ) {
	return;
}

$dealer_id = (int) $dealer_id;
$per_page  = isset( $per_page ) ? max( 1, (int) $per_page ) : 12;
$extra     = isset( $args ) && is_array( $args ) ? $args : array();

$params = FilterParams::fromArray(
	array_merge(
		array(
			'dealer_id' => $dealer_id,
			'per_page'  => $per_page,
			'orderby'   => 'date',
			'order'     => 'DESC',
		),
		$extra
	)
);

$rows = ( new VehicleQuery() )->fetch( $params );

if ( empty( $rows ) ) :
	?>
	<div class="trx-ad-dealer-listings trx-ad-dealer-listings--empty">
		<p><?php esc_html_e( 'No vehicles available from this dealer.', 'trx-auto-dealer' ); ?></p>
	</div>
	<?php
	return;
endif;
?>
<div class="trx-ad-dealer-listings">
	<div class="trx-ad-archive__grid" style="--trx-ad-grid-cols: 2;">
		<?php foreach ( $rows as $row ) : ?>
			<?php TemplateLoader::getTemplatePart( 'vehicle-card', array( 'post_id' => (int) $row['ID'] ) ); ?>
		<?php endforeach; ?>
	</div>
</div>
