<?php
/**
 * 360 View widget — interactive 360° rotation viewer.
 *
 * Free tier reads the listing's `_trx_ad_view360_frames` meta (a JSON array
 * of image URLs, one per rotation frame) and renders a drag-to-rotate viewer
 * using the same CSS sprite swap approach 360-image libraries use. If the
 * listing has a `_trx_ad_view360_iframe` URL set instead, it embeds that in
 * an iframe (covers third-party 360 hosts the user already pays for).
 *
 * Empty meta → widget renders nothing. Editor preview shows a placeholder so
 * the canvas is not blank.
 *
 * @package ThemeREX\AutoDealer
 */

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Elementor\Widgets;

defined( 'ABSPATH' ) || exit;
if ( ! class_exists( '\Elementor\Widget_Base' ) ) {
	return;
}

use Elementor\Controls_Manager;
use Elementor\Widget_Base;
use ThemeREX\AutoDealer\PostTypes\VehiclePostType;

class View360Widget extends Widget_Base {

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

	public function get_title(): string {
		return __( '360° View', 'trx-auto-dealer' );
	}

	public function get_icon(): string {
		// Must be a class that exists in Elementor's eicons font — an unknown
		// class renders as a blank tile in the widget panel (tester feedback #10).
		return 'eicon-slider-3d';
	}

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

	public function get_keywords(): array {
		return array( '360', 'view', 'rotate', 'panorama' );
	}

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

	public function get_script_depends(): array {
		return array( 'trx-ad-frontend', 'trx-ad-widget-view-360' );
	}

	protected function register_controls(): void {
		$this->start_controls_section(
			'section_content',
			array(
				'label' => __( 'Content', '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'     => '',
				'label_block' => true,
			)
		);

		$this->add_responsive_control(
			'height',
			array(
				'label'     => __( 'Viewer Height', 'trx-auto-dealer' ),
				'type'      => Controls_Manager::SLIDER,
				'range'     => array(
					'px' => array(
						'min' => 200,
						'max' => 800,
					),
				),
				'default'   => array(
					'size' => 420,
					'unit' => 'px',
				),
				'selectors' => array(
					'{{WRAPPER}} .trx-ad-view-360, {{WRAPPER}} .trx-ad-view-360 iframe' => 'height: {{SIZE}}{{UNIT}};',
				),
			)
		);

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

		$this->add_control(
			'rotate_speed',
			array(
				'label'     => __( 'Auto Rotate Speed (ms per frame)', 'trx-auto-dealer' ),
				'type'      => Controls_Manager::NUMBER,
				'default'   => 80,
				'min'       => 30,
				'max'       => 500,
				'condition' => array( 'auto_rotate' => 'yes' ),
			)
		);

		$this->end_controls_section();
	}

	protected function render(): void {
		$settings = $this->get_settings_for_display();
		$id       = (int) ( $settings['vehicle_id'] ?? 0 );
		if ( $id <= 0 ) {
			$id = ElementorPreviewContext::resolveVehicleId();
		}

		if ( $id <= 0 || VehiclePostType::POST_TYPE !== get_post_type( $id ) ) {
			return;
		}

		$iframe = trim( (string) get_post_meta( $id, '_trx_ad_view360_iframe', true ) );
		if ( '' !== $iframe ) {
			?>
			<div class="trx-ad-view-360 trx-ad-view-360--iframe">
				<iframe src="<?php echo esc_url( $iframe ); ?>" loading="lazy" allowfullscreen style="width:100%; border:0; display:block;"></iframe>
			</div>
			<?php
			return;
		}

		$frames_raw = get_post_meta( $id, '_trx_ad_view360_frames', true );
		$frames     = is_array( $frames_raw ) ? $frames_raw : json_decode( (string) $frames_raw, true );
		if ( ! is_array( $frames ) || count( $frames ) < 4 ) {
			if ( ElementorPreviewContext::isEditor() ) {
				echo '<div class="trx-ad-view-360 trx-ad-view-360--empty"><p>' .
					esc_html__( '360 frames not configured for this vehicle. Add a JSON array of image URLs in the `_trx_ad_view360_frames` meta key.', 'trx-auto-dealer' ) .
					'</p></div>';
			}
			return;
		}

		$frames       = array_values( array_filter( array_map( 'esc_url_raw', $frames ) ) );
		$auto_rotate  = 'yes' === ( $settings['auto_rotate'] ?? '' );
		$rotate_speed = max( 30, (int) ( $settings['rotate_speed'] ?? 80 ) );
		$widget_uniq  = 'trx-ad-v360-' . wp_generate_uuid4();
		?>
		<div id="<?php echo esc_attr( $widget_uniq ); ?>" class="trx-ad-view-360" data-frames="<?php echo esc_attr( wp_json_encode( $frames ) ); ?>" data-auto-rotate="<?php echo $auto_rotate ? '1' : '0'; ?>" data-rotate-speed="<?php echo esc_attr( (string) $rotate_speed ); ?>">
			<img class="trx-ad-view-360__frame" src="<?php echo esc_url( $frames[0] ); ?>" alt="<?php echo esc_attr( get_the_title( $id ) ); ?>" style="width:100%; height:100%; object-fit:contain; user-select:none; cursor:grab;" draggable="false" />
		</div>
		<?php
		// Drag/auto-rotate behaviour lives in view-360.js (get_script_depends) --
		// fully driven by the data attributes above; no inline <script> (wp.org 2026-07).
		?>
		<?php
	}
}
