<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit; }
use Elementor\Widget_Base;
use Sifency\Classes\Sifency_Addons_Widget_Base;
use Sifency\Classes\Sifency_Themebuilder_Widget_Base;
use Elementor\Controls_Manager;
use Elementor\Group_Control_Image_Size;
use Elementor\Group_Control_Border;
use Elementor\Group_Control_Box_Shadow;
use Elementor\Icons_Manager;
use Sifency\Traits\Sifency_Addons_Animation_Controls;
use Sifency\Traits\Sifency_Addons_Animation_Manager;
use Sifency\Traits\Sifency_Addons_Help_Controls;
class Sifency_Widget_Digital_Product_Video extends Sifency_Themebuilder_Widget_Base {
	use Sifency_Addons_Animation_Controls;
	use Sifency_Addons_Help_Controls;

	protected function get_allowed_template_types() {
		return 'digital';
	}
	public function __construct( $data = array(), $args = null ) {
		parent::__construct( $data, $args );
		$this->wg_config = array(
			'name'           => 'sifency-digital-product-video',
			'title'          => 'Product Video',
			'icon'           => 'eicon-meta-data',
			'category'       => array( 'sifency-digital-components' ),
			'keywords'       => array( 'digital', 'product', 'video', 'youtube', 'vimeo', 'meta', 'sifency' ),
			'script_depends' => array( 'sifency-digital-script' ),
			'style_depends'  => array( 'sifency-digital-style' ),
		);}
	protected function register_controls() {
		$this->start_controls_section( 'section_video_content', array( 'label' => esc_html__( 'Video', 'sifency-addons' ) ) );
		$this->add_control(
			'custom_thumbnail',
			array(
				'label'       => 'Custom Thumbnail',
				'type'        => Controls_Manager::MEDIA,
				'description' => 'If not set, will try to use the product\'s featured image.',
			)
		);
		$this->add_group_control(
			Group_Control_Image_Size::get_type(),
			array(
				'name'      => 'thumbnail_size',
				'default'   => 'large',
				'condition' => array( 'custom_thumbnail[url]!' => '' ),
			)
		);
		$this->add_control(
			'play_icon',
			array(
				'label'   => esc_html__( 'Play Icon', 'sifency-addons' ),
				'type'    => Controls_Manager::ICONS,
				'default' => array(
					'value'   => 'fas fa-play',
					'library' => 'fa-solid',
				),
			)
		);
		$this->end_controls_section();
		$this->add_sifency_addons_help_controls();
		$this->start_controls_section(
			'section_image_style',
			array(
				'label' => esc_html__( 'Container', 'sifency-addons' ),
				'tab'   => Controls_Manager::TAB_STYLE,
			)
		);
		$this->add_responsive_control(
			'aspect_ratio',
			array(
				'label'     => 'Aspect Ratio',
				'type'      => Controls_Manager::SLIDER,
				'range'     => array(
					'px' => array(
						'min'  => 0.1,
						'max'  => 2,
						'step' => 0.01,
					),
				),
				'default'   => array( 'size' => 0.5625 ),
				'selectors' => array( '{{WRAPPER}} .sifency-video-iframe-container' => 'padding-bottom: calc( {{SIZE}} * 100% );' ),
			)
		);
		$this->add_group_control(
			Group_Control_Border::get_type(),
			array(
				'name'     => 'container_border',
				'selector' => '{{WRAPPER}} .sifency-video-wrapper',
			)
		);
		$this->add_responsive_control(
			'container_radius',
			array(
				'label'     => 'Border Radius',
				'type'      => Controls_Manager::DIMENSIONS,
				'selectors' => array( '{{WRAPPER}} .sifency-video-wrapper' => 'border-radius: {{TOP}}px {{RIGHT}}px {{BOTTOM}}px {{LEFT}}px;' ),
			)
		);
		$this->add_group_control(
			Group_Control_Box_Shadow::get_type(),
			array(
				'name'     => 'container_shadow',
				'selector' => '{{WRAPPER}} .sifency-video-wrapper',
			)
		);
		$this->end_controls_section();
		$this->start_controls_section(
			'section_play_icon_style',
			array(
				'label' => esc_html__( 'Play Icon', 'sifency-addons' ),
				'tab'   => Controls_Manager::TAB_STYLE,
			)
		);
		$this->add_responsive_control(
			'play_icon_size',
			array(
				'label'     => 'Size',
				'type'      => Controls_Manager::SLIDER,
				'range'     => array(
					'px' => array(
						'min' => 10,
						'max' => 200,
					),
				),
				'selectors' => array( '{{WRAPPER}} .sifency-video-play-button i' => 'font-size: {{SIZE}}px;' ),
			)
		);
		$this->add_control(
			'play_icon_color',
			array(
				'label'     => 'Color',
				'type'      => Controls_Manager::COLOR,
				'selectors' => array( '{{WRAPPER}} .sifency-video-play-button i' => 'color: {{VALUE}};' ),
			)
		);
		$this->add_control(
			'play_icon_bg_color',
			array(
				'label'     => 'Background Color',
				'type'      => Controls_Manager::COLOR,
				'selectors' => array( '{{WRAPPER}} .sifency-video-play-button i' => 'background-color: {{VALUE}};' ),
			)
		);
		$this->add_responsive_control(
			'play_icon_padding',
			array(
				'label'     => 'Padding',
				'type'      => Controls_Manager::SLIDER,
				'range'     => array(
					'px' => array(
						'min' => 0,
						'max' => 100,
					),
				),
				'selectors' => array( '{{WRAPPER}} .sifency-video-play-button i' => 'padding: {{SIZE}}px;' ),
			)
		);
		$this->end_controls_section();
		$this->add_Sifency_Addons_Animation_Controls();
	}
	protected function render_dom( array $context ) {
		$wrapper_id = esc_attr( $context['dom_id'] );
		$settings   = $this->get_settings_for_display();

		$video_url = sifency_get_field( 'digital_video_url' );

		if ( empty( $video_url ) ) {
			if ( \Elementor\Plugin::$instance->editor->is_edit_mode() ) {
				echo '<div class="elementor-alert elementor-alert-warning">' . esc_html__( 'No video URL is set for this product.', 'sifency-addons' ) . '</div>';
			}
			return;
		}

		$embed_url = $this->get_embed_url( $video_url );
		if ( ! $embed_url ) {
			if ( \Elementor\Plugin::$instance->editor->is_edit_mode() ) {
				echo '<div class="elementor-alert elementor-alert-danger">' . esc_html__( 'Invalid video URL. Please use a YouTube or Vimeo link.', 'sifency-addons' ) . '</div>';
			}
			return;
		}

		$thumbnail_url = '';
		if ( ! empty( $settings['custom_thumbnail']['url'] ) ) {
			$thumbnail_url = \Elementor\Group_Control_Image_Size::get_attachment_image_src( $settings['custom_thumbnail']['id'], 'thumbnail_size', $settings ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Elementor already escapes content internally.
		} elseif ( has_post_thumbnail() ) {
			$thumbnail_url = get_the_post_thumbnail_url( get_the_ID(), 'large' );
		} else {
			$thumbnail_url = \Elementor\Utils::get_placeholder_image_src();
		}

		$animation_manager = new Sifency_Addons_Animation_Manager( $settings );
		$animation_attrs   = $animation_manager->get_wrapper_attributes( array() );

		?>
		<div id="<?php echo esc_attr ( $wrapper_id ); ?>" class="sifency-video-wrapper" <?php echo $animation_attrs; // phpcs:ignore ?>>
			<div class="sifency-video-play-button" role="button">
				<?php Icons_Manager::render_icon( $settings['play_icon'], array( 'aria-hidden' => 'true' ) ); ?>
			</div>
			<img src="<?php echo esc_url( $thumbnail_url ); ?>" alt="<?php echo esc_attr( get_the_title() ); ?>" />
			
			<script type="text/html">
				<div class="sifency-video-iframe-container">
					<iframe src="<?php echo esc_url( $embed_url ); ?>" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
				</div>
			</script>
		</div>
		<?php
	}

	/**
	 * Helper function to convert a YouTube/Vimeo URL to its embeddable version with autoplay.
	 */
	private function get_embed_url( $url ) {
		$embed_url = '';
		if ( preg_match( '%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $match ) ) {
			$video_id  = $match[1];
			$embed_url = 'https://www.youtube.com/embed/' . $video_id . '?autoplay=1&rel=0';
		} elseif ( preg_match( '/(https?:\/\/)?(www\.)?(player\.)?vimeo\.com\/([a-z]*\/)*([0-9]{6,11})[?]?/i', $url, $match ) ) {
			$video_id  = $match[5];
			$embed_url = 'https://player.vimeo.com/video/' . $video_id . '?autoplay=1';
		}
		return $embed_url;
	}
}
