<?php
/**
 * Featured Carousel widget — Swiper-based carousel of featured listings.
 *
 * Reuses the existing vehicle-card template part for each slide so the card
 * markup stays consistent with the grid + archive surfaces. Uses the swiper
 * script already registered in ElementorIntegration::registerAssets().
 *
 * @package ThemeREX\AutoDealer
 */

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Elementor\Widgets;

if ( ! class_exists( '\Elementor\Widget_Base' ) ) {
	return;
}

use Elementor\Controls_Manager;
use Elementor\Widget_Base;
use ThemeREX\AutoDealer\Frontend\TemplateLoader;
use ThemeREX\AutoDealer\Search\FilterParams;
use ThemeREX\AutoDealer\Search\VehicleQuery;

class FeaturedCarouselWidget extends Widget_Base {

	public function get_name(): string {
		return 'trx_ad_featured_carousel';
	}

	public function get_title(): string {
		return __( 'Featured Carousel', 'trx-auto-dealer' );
	}

	public function get_icon(): string {
		return 'eicon-slider-album';
	}

	public function get_categories(): array {
		return array( 'trx-auto-dealer' );
	}

	public function get_keywords(): array {
		return array( 'featured', 'carousel', 'slider', 'vehicle' );
	}

	public function get_script_depends(): array {
		return array( 'trx-ad-frontend', 'trx-ad-swiper', 'trx-ad-widget-featured-carousel' );
	}

	public function get_style_depends(): array {
		return array( 'trx-ad-frontend', 'trx-ad-swiper' );
	}

	protected function register_controls(): void {
		$this->start_controls_section(
			'section_query',
			array(
				'label' => __( 'Query', 'trx-auto-dealer' ),
			)
		);

		$this->add_control(
			'limit',
			array(
				'label'   => __( 'Maximum Listings', 'trx-auto-dealer' ),
				'type'    => Controls_Manager::NUMBER,
				'min'     => 2,
				'max'     => 24,
				'default' => 8,
			)
		);

		$this->add_control(
			'featured_only',
			array(
				'label'        => __( 'Featured Only', 'trx-auto-dealer' ),
				'type'         => Controls_Manager::SWITCHER,
				'default'      => 'yes',
				'return_value' => 'yes',
			)
		);

		$this->add_control(
			'orderby',
			array(
				'label'   => __( 'Order By', 'trx-auto-dealer' ),
				'type'    => Controls_Manager::SELECT,
				'default' => 'date',
				'options' => array(
					'date'  => __( 'Most Recent', 'trx-auto-dealer' ),
					'price' => __( 'Price', 'trx-auto-dealer' ),
					'title' => __( 'Title', 'trx-auto-dealer' ),
					'rand'  => __( 'Random', 'trx-auto-dealer' ),
				),
			)
		);

		$this->end_controls_section();

		$this->start_controls_section(
			'section_carousel',
			array(
				'label' => __( 'Carousel', 'trx-auto-dealer' ),
			)
		);

		$this->add_responsive_control(
			'slides_per_view',
			array(
				'label'          => __( 'Slides per View', 'trx-auto-dealer' ),
				'type'           => Controls_Manager::NUMBER,
				'default'        => 3,
				'min'            => 1,
				'max'            => 6,
				'tablet_default' => 2,
				'mobile_default' => 1,
			)
		);

		$this->add_control(
			'space_between',
			array(
				'label'   => __( 'Space Between Slides (px)', 'trx-auto-dealer' ),
				'type'    => Controls_Manager::NUMBER,
				'default' => 24,
				'min'     => 0,
				'max'     => 100,
			)
		);

		$this->add_control(
			'autoplay',
			array(
				'label'        => __( 'Autoplay', 'trx-auto-dealer' ),
				'type'         => Controls_Manager::SWITCHER,
				'default'      => '',
				'return_value' => 'yes',
			)
		);

		$this->add_control(
			'autoplay_delay',
			array(
				'label'     => __( 'Autoplay Delay (ms)', 'trx-auto-dealer' ),
				'type'      => Controls_Manager::NUMBER,
				'default'   => 4000,
				'min'       => 1000,
				'max'       => 15000,
				'condition' => array( 'autoplay' => 'yes' ),
			)
		);

		$this->add_control(
			'loop',
			array(
				'label'        => __( 'Loop', 'trx-auto-dealer' ),
				'type'         => Controls_Manager::SWITCHER,
				'default'      => 'yes',
				'return_value' => 'yes',
			)
		);

		$this->add_control(
			'show_navigation',
			array(
				'label'        => __( 'Show Navigation Arrows', 'trx-auto-dealer' ),
				'type'         => Controls_Manager::SWITCHER,
				'default'      => 'yes',
				'return_value' => 'yes',
			)
		);

		$this->add_control(
			'show_pagination',
			array(
				'label'        => __( 'Show Pagination Dots', 'trx-auto-dealer' ),
				'type'         => Controls_Manager::SWITCHER,
				'default'      => '',
				'return_value' => 'yes',
			)
		);

		$this->end_controls_section();
	}

	protected function render(): void {
		$settings = $this->get_settings_for_display();

		$args = array_filter(
			array(
				'per_page' => max( 2, (int) ( $settings['limit'] ?? 8 ) ),
				'featured' => 'yes' === ( $settings['featured_only'] ?? 'yes' ) ? 1 : '',
				'orderby'  => (string) ( $settings['orderby'] ?? 'date' ),
			),
			static fn( $v ) => '' !== $v && null !== $v
		);

		$rows = ( new VehicleQuery() )->fetch( FilterParams::fromArray( $args ) );

		if ( empty( $rows ) ) {
			if ( ElementorPreviewContext::isEditor() ) {
				echo '<p>' . esc_html__( 'No featured listings found. Mark some listings as featured.', 'trx-auto-dealer' ) . '</p>';
			}
			return;
		}

		$id              = 'trx-ad-fc-' . wp_generate_uuid4();
		$slides_per      = max( 1, (int) ( $settings['slides_per_view'] ?? 3 ) );
		$slides_tablet   = max( 1, (int) ( $settings['slides_per_view_tablet'] ?? 2 ) );
		$slides_mobile   = max( 1, (int) ( $settings['slides_per_view_mobile'] ?? 1 ) );
		$space_between   = max( 0, (int) ( $settings['space_between'] ?? 24 ) );
		$autoplay        = 'yes' === ( $settings['autoplay'] ?? '' );
		$autoplay_delay  = max( 1000, (int) ( $settings['autoplay_delay'] ?? 4000 ) );
		$loop            = 'yes' === ( $settings['loop'] ?? 'yes' );
		$show_nav        = 'yes' === ( $settings['show_navigation'] ?? 'yes' );
		$show_pagination = 'yes' === ( $settings['show_pagination'] ?? '' );

		$config = array(
			'slidesPerView' => $slides_per,
			'spaceBetween'  => $space_between,
			'loop'          => $loop,
			'breakpoints'   => array(
				'0'    => array( 'slidesPerView' => $slides_mobile ),
				'782'  => array( 'slidesPerView' => $slides_tablet ),
				'1024' => array( 'slidesPerView' => $slides_per ),
			),
		);
		if ( $autoplay ) {
			$config['autoplay'] = array(
				'delay'             => $autoplay_delay,
				'pauseOnMouseEnter' => true,
			);
		}
		// Navigation/pagination are wired up by featured-carousel.js from the
		// child elements below, so the config never carries per-instance
		// selectors and no inline <script> is needed (wp.org 2026-07 review).

		?>
		<div id="<?php echo esc_attr( $id ); ?>" class="trx-ad-featured-carousel swiper" data-swiper-config="<?php echo esc_attr( (string) wp_json_encode( $config ) ); ?>">
			<div class="swiper-wrapper">
				<?php foreach ( $rows as $row ) : ?>
					<div class="swiper-slide">
						<?php TemplateLoader::getTemplatePart( 'vehicle-card', array( 'post_id' => (int) $row['ID'] ) ); ?>
					</div>
				<?php endforeach; ?>
			</div>
			<?php if ( $show_nav ) : ?>
				<div class="swiper-button-prev"></div>
				<div class="swiper-button-next"></div>
			<?php endif; ?>
			<?php if ( $show_pagination ) : ?>
				<div class="swiper-pagination"></div>
			<?php endif; ?>
		</div>
		<?php
	}
}
