<?php

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Elementor\Widgets;

use Elementor\Controls_Manager;
use Elementor\Widget_Base;
use ThemeREX\AutoDealer\Frontend\MediaSliderRenderer;
use ThemeREX\AutoDealer\Frontend\TemplateLoader;

/**
 * Media Slider widget — gallery images + videos in a Swiper slider.
 *
 * @package ThemeREX\AutoDealer
 */
// Bail if Elementor isn't loaded — prevents a fatal during PSR-4 autoload
// when this file is included on a site that doesn't have Elementor active.
if ( ! class_exists( '\Elementor\Widget_Base' ) ) {
	return;
}

class MediaSliderWidget extends Widget_Base {

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

	public function get_title(): string {
		return __( 'Listing Media Slider', 'trx-auto-dealer' );
	}

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

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

	public function get_script_depends(): array {
		return array( 'trx-ad-widget-media-slider' );
	}

	public function get_style_depends(): array {
		return array( 'trx-ad-widget-media-slider' );
	}

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

		$this->add_control(
			'vehicle_id',
			array(
				'label'       => __( 'Vehicle', 'trx-auto-dealer' ),
				'type'        => Controls_Manager::SELECT2,
				'options'     => WidgetHelpers::vehicleOptions( __( '— Use current vehicle —', 'trx-auto-dealer' ) ),
				'default'     => '',
				'description' => __( 'Leave empty to use the current vehicle.', 'trx-auto-dealer' ),
				'label_block' => true,
			)
		);

		$this->add_control(
			'aspect_ratio',
			array(
				'label'   => __( 'Aspect Ratio', 'trx-auto-dealer' ),
				'type'    => Controls_Manager::SELECT,
				'default' => '16:9',
				'options' => array(
					'16:9' => '16:9',
					'4:3'  => '4:3',
					'3:2'  => '3:2',
					'1:1'  => '1:1',
				),
			)
		);

		$this->add_control(
			'thumbs_per_view',
			array(
				'label'   => __( 'Thumbnails Per View', 'trx-auto-dealer' ),
				'type'    => Controls_Manager::NUMBER,
				'default' => 5,
				'min'     => 3,
				'max'     => 10,
			)
		);

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

		$this->add_control(
			'loop',
			array(
				'label'        => __( 'Loop', '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();
		$post_id  = (int) ( $settings['vehicle_id'] ?? 0 );
		if ( $post_id <= 0 ) {
			$post_id = (int) $this->getPreviewPostId();
		}

		if ( ! $post_id ) {
			if ( \Elementor\Plugin::$instance->editor->is_edit_mode() ) {
				echo '<div class="trx-ad-media-slider trx-ad-media-slider--empty">' .
					esc_html__( 'Listing Media Slider — no listing context available.', 'trx-auto-dealer' ) .
					'</div>';
			}
			return;
		}

		TemplateLoader::getTemplatePart(
			'media-slider',
			array(
				'slides'     => MediaSliderRenderer::buildSlides( (int) $post_id ),
				'aspect'     => MediaSliderRenderer::aspectToPadding( $settings['aspect_ratio'] ?? '16:9' ),
				'thumbs_per' => (int) ( $settings['thumbs_per_view'] ?? 5 ),
				'autoplay'   => ( $settings['autoplay'] ?? '' ) === 'yes',
				'loop'       => ( $settings['loop'] ?? '' ) === 'yes',
			)
		);
	}

	/**
	 * Get the correct post ID for preview — uses a real listing in editor mode.
	 *
	 * @return int|false
	 */
	private function getPreviewPostId() {
		if ( ! \Elementor\Plugin::$instance->editor->is_edit_mode() && ! \Elementor\Plugin::$instance->preview->is_preview_mode() ) {
			return get_the_ID();
		}

		$preview_id = \Elementor\Plugin::$instance->documents->get_current()
			? \Elementor\Plugin::$instance->documents->get_current()->get_settings( 'preview_id' )
			: 0;

		if ( $preview_id && 'trx_ad_listing' === get_post_type( $preview_id ) ) {
			return (int) $preview_id;
		}

		$posts = get_posts(
			array(
				'post_type'      => 'trx_ad_listing',
				'posts_per_page' => 1,
				'post_status'    => 'publish',
				'fields'         => 'ids',
			)
		);

		return ! empty( $posts ) ? (int) $posts[0] : false;
	}
}
