<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

use Elementor\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_Animation_Controls; 
use Sifency\Traits\Sifency_Animation_Manager;  

class Sifency_Widget_Digital_Product_Video extends Widget_Base {
	use Sifency_Animation_Controls;

	public function get_name() { return 'sifency-digital-product-video'; }
	public function get_title() { return esc_html__( 'Product Video', 'sifency-addons' ); }
	public function get_icon() { return 'eicon-meta-data'; }
	public function get_categories() { return [ 'sifency-digital-components' ]; }
	public function get_keywords() { return [ 'digital', 'product', 'video', 'youtube', 'vimeo', 'meta', 'sifency' ]; }
    public function get_script_depends() { return [ 'sifency-digital-script' ]; }
    public function get_style_depends() { return [ 'sifency-digital-style' ]; }

	protected function register_controls() {
		// --- Content Tab: Video Settings ---
		$this->start_controls_section( 'section_video_content', [ 'label' => esc_html__( 'Video', 'sifency-addons' ) ] );
		$this->add_control( 'custom_thumbnail', [ '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(), [ 'name' => 'thumbnail_size', 'default' => 'large', 'condition' => [ 'custom_thumbnail[url]!' => '' ] ] );
		$this->add_control( 'play_icon', [ 'label' => esc_html__( 'Play Icon', 'sifency-addons' ), 'type' => Controls_Manager::ICONS, 'default' => [ 'value' => 'fas fa-play', 'library' => 'fa-solid' ] ] );
		$this->end_controls_section();

		// --- Style Tab: Image & Container ---
		$this->start_controls_section( 'section_image_style', [ 'label' => esc_html__( 'Container', 'sifency-addons' ), 'tab' => Controls_Manager::TAB_STYLE ] );
		$this->add_responsive_control( 'aspect_ratio', [ 'label' => 'Aspect Ratio', 'type' => Controls_Manager::SLIDER, 'range' => [ 'px' => [ 'min' => 0.1, 'max' => 2, 'step' => 0.01 ] ], 'default' => [ 'size' => 0.5625 ], 'selectors' => [ '{{WRAPPER}} .sifency-video-iframe-container' => 'padding-bottom: calc( {{SIZE}} * 100% );' ] ] );
		$this->add_group_control( Group_Control_Border::get_type(), [ 'name' => 'container_border', 'selector' => '{{WRAPPER}} .sifency-video-wrapper' ] );
		$this->add_responsive_control( 'container_radius', [ 'label' => 'Border Radius', 'type' => Controls_Manager::DIMENSIONS, 'selectors' => [ '{{WRAPPER}} .sifency-video-wrapper' => 'border-radius: {{TOP}}px {{RIGHT}}px {{BOTTOM}}px {{LEFT}}px;' ] ] );
		$this->add_group_control( Group_Control_Box_Shadow::get_type(), [ 'name' => 'container_shadow', 'selector' => '{{WRAPPER}} .sifency-video-wrapper' ] );
		$this->end_controls_section();

		// --- Style Tab: Play Icon ---
		$this->start_controls_section( 'section_play_icon_style', [ 'label' => esc_html__( 'Play Icon', 'sifency-addons' ), 'tab' => Controls_Manager::TAB_STYLE ] );
		$this->add_responsive_control( 'play_icon_size', [ 'label' => 'Size', 'type' => Controls_Manager::SLIDER, 'range' => [ 'px' => [ 'min' => 10, 'max' => 200 ] ], 'selectors' => [ '{{WRAPPER}} .sifency-video-play-button i' => 'font-size: {{SIZE}}px;' ] ] );
		$this->add_control( 'play_icon_color', [ 'label' => 'Color', 'type' => Controls_Manager::COLOR, 'selectors' => [ '{{WRAPPER}} .sifency-video-play-button i' => 'color: {{VALUE}};' ] ] );
		$this->add_control( 'play_icon_bg_color', [ 'label' => 'Background Color', 'type' => Controls_Manager::COLOR, 'selectors' => [ '{{WRAPPER}} .sifency-video-play-button i' => 'background-color: {{VALUE}};' ] ] );
		$this->add_responsive_control( 'play_icon_padding', [ 'label' => 'Padding', 'type' => Controls_Manager::SLIDER, 'range' => [ 'px' => [ 'min' => 0, 'max' => 100 ] ], 'selectors' => [ '{{WRAPPER}} .sifency-video-play-button i' => 'padding: {{SIZE}}px;' ] ] );
		$this->end_controls_section();

		$this->add_sifency_animation_controls();
	}

	protected function render() {
		$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 );
		} 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_Animation_Manager( $settings );
		$animation_attrs   = $animation_manager->get_wrapper_attributes( [] );

		?>
		<div 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'], [ '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;
	}
}