<?php
namespace owpElementor\Modules\MediaVideo\Widgets;

// Elementor Classes
use Elementor\Widget_Base;
use Elementor\Group_Control_Typography;
use Elementor\Group_Control_Text_Shadow;
use Elementor\Group_Control_Box_Shadow;
use Elementor\Group_Control_Border;
use Elementor\Controls_Manager;
use Elementor\Group_Control_Css_Filter;
use Elementor\Group_Control_Image_Size;
use Elementor\Icons_Manager;
use Elementor\Plugin;

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

class MediaVideo extends Widget_Base {

	public function get_name() {
		return 'oew-media-video';
	}

	public function get_title() {
		return __( 'MediaVideo', 'ocean-elementor-widgets' );
	}

	public function get_icon() {
		return 'oew-icon eicon-instagram-video';
	}

	public function get_categories() {
		return array( 'oceanwp-elements' );
	}

	public function get_keywords() {
		return array(
			'media-video',
			'owp',
		);
	}

	public function get_style_depends() {
		return array( 'oew-media-video' );
	}

	public function get_script_depends() {
		return array( 'oew-media-video' );
	}


	protected function register_controls() {

		$this->start_controls_section(
			'section_video',
			array(
				'label' => esc_html__( 'Video', 'ocean-elementor-widgets' ),
			)
		);

		$this->add_control(
			'video_type',
			array(
				'label'   => esc_html__( 'Video Type', 'ocean-elementor-widgets' ),
				'type'    => Controls_Manager::SELECT,
				'default' => 'youtube',
				'options' => array(
					'youtube'   => esc_html__( 'YouTube', 'ocean-elementor-widgets' ),
					'instagram' => esc_html__( 'Instagram Reels', 'ocean-elementor-widgets' ),
					'facebook'  => esc_html__( 'Facebook Reels', 'ocean-elementor-widgets' ),
				),
			)
		);

		$this->add_control(
			'video_url',
			array(
				'label'       => esc_html__( 'Video URL', 'ocean-elementor-widgets' ),
				'label_block' => true,
				'type'        => Controls_Manager::TEXT,
				'placeholder' => esc_html__( 'Enter your video URL', 'ocean-elementor-widgets' ),
				'default'     => '',
			)
		);

		$this->add_control(
			'start_time',
			array(
				'label'     => esc_html__( 'Start Time (in seconds)', 'ocean-elementor-widgets' ),
				'type'      => Controls_Manager::NUMBER,
				'default'   => '',
				'condition' => array(
					'video_type' => 'youtube',
				),
			)
		);

		$this->add_control(
			'end_time',
			array(
				'label'     => esc_html__( 'End Time (in seconds)', 'ocean-elementor-widgets' ),
				'type'      => Controls_Manager::NUMBER,
				'default'   => '',
				'condition' => array(
					'video_type' => 'youtube',
				),
			)
		);

		$this->add_control(
			'autoplay',
			array(
				'label'     => esc_html__( 'Autoplay', 'ocean-elementor-widgets' ),
				'type'      => Controls_Manager::SWITCHER,
				'default'   => '',
				'condition' => array(
					'video_type' => 'youtube',
				),
			)
		);

		$this->add_control(
			'mute',
			array(
				'label'     => esc_html__( 'Mute', 'ocean-elementor-widgets' ),
				'type'      => Controls_Manager::SWITCHER,
				'default'   => '',
				'condition' => array(
					'video_type' => 'youtube',
				),
			)
		);

		$this->add_control(
			'loop',
			array(
				'label'     => esc_html__( 'Loop', 'ocean-elementor-widgets' ),
				'type'      => Controls_Manager::SWITCHER,
				'default'   => '',
				'condition' => array(
					'video_type' => 'youtube',
				),
			)
		);

		$this->add_control(
			'controls',
			array(
				'label'     => esc_html__( 'Player Controls', 'ocean-elementor-widgets' ),
				'type'      => Controls_Manager::SWITCHER,
				'label_on'  => esc_html__( 'Show', 'ocean-elementor-widgets' ),
				'label_off' => esc_html__( 'Hide', 'ocean-elementor-widgets' ),
				'default'   => 'yes',
				'condition' => array(
					'video_type' => 'youtube',
				),
			)
		);

		$this->add_control(
			'thumbnail',
			array(
				'label'     => esc_html__( 'Thumbnail Image', 'ocean-elementor-widgets' ),
				'type'      => Controls_Manager::MEDIA,
				'default'   => array(),
				'dynamic'   => array( 'active' => true ),
				'separator' => 'before',
				'condition' => array(
					'video_type' => 'youtube',
				),
			)
		);

		$this->add_group_control(
			Group_Control_Image_Size::get_type(),
			array(
				'name'      => 'thumbnail',
				'default'   => 'full',
				'condition' => array(
					'video_type'     => 'youtube',
					'thumbnail[id]!' => '',
				),
			)
		);

		$this->add_control(
			'show_play_button',
			array(
				'label'     => esc_html__( 'Show Play Button', 'ocean-elementor-widgets' ),
				'type'      => Controls_Manager::SWITCHER,
				'default'   => 'yes',
				'condition' => array(
					'video_type'     => 'youtube',
					'thumbnail[id]!' => '',
				),
			)
		);

		$this->add_control(
			'play_button_icon',
			array(
				'label'       => esc_html__( 'Play Button Icon', 'ocean-elementor-widgets' ),
				'type'        => Controls_Manager::ICONS,
				// 'fa4compatibility' => 'play_button_icon',
				'default'     => array(
					'value'   => 'fas fa-play',
					'library' => 'fa-solid',
				),
				'label_block' => true,
				'condition'   => array(
					'show_play_button' => 'yes',
					'video_type'       => 'youtube',
					'thumbnail[id]!'   => '',
				),
			)
		);

		$this->end_controls_section();

		$this->start_controls_section(
			'section_video_style',
			array(
				'label' => esc_html__( 'Video', 'ocean-elementor-widgets' ),
				'tab'   => Controls_Manager::TAB_STYLE,
			)
		);

		$this->add_control(
			'aspect_ratio',
			array(
				'label'   => esc_html__( 'Aspect Ratio', 'ocean-elementor-widgets' ),
				'type'    => Controls_Manager::SELECT,
				'default' => '16-9',
				'options' => array(
					'16-9' => '16:9',
					'21-9' => '21:9',
					'9-16' => '9:16',
					'4-3'  => '4:3',
					'3-2'  => '3:2',
					'1-1'  => '1:1',
				),
			)
		);

		$this->add_responsive_control(
			'width',
			array(
				'label'      => esc_html__( 'Width', 'ocean-elementor-widgets' ),
				'type'       => Controls_Manager::SLIDER,
				'size_units' => array( 'px', '%', 'custom' ),
				'selectors'  => array(
					'{{WRAPPER}} .oew-video-wrapper' => 'max-width: {{SIZE}}{{UNIT}};',
				),
				'range'      => array(
					'px' => array(
						'min' => 100,
						'max' => 2000,
					),
				),
			),
		);

		$this->add_responsive_control(
			'align',
			array(
				'label'                => esc_html__( 'Alignment', 'ocean-elementor-widgets' ),
				'type'                 => Controls_Manager::CHOOSE,
				'options'              => array(
					'left'   => array(
						'title' => esc_html__( 'Left', 'ocean-elementor-widgets' ),
						'icon'  => 'eicon-h-align-left',
					),
					'center' => array(
						'title' => esc_html__( 'Center', 'ocean-elementor-widgets' ),
						'icon'  => 'eicon-h-align-center',
					),
					'right'  => array(
						'title' => esc_html__( 'Right', 'ocean-elementor-widgets' ),
						'icon'  => 'eicon-h-align-right',
					),
				),
				'selectors_dictionary' => array(
					'left'   => 'margin-left: 0; margin-right: auto;',
					'center' => 'margin-left: auto; margin-right: auto;',
					'right'  => 'margin-left: auto; margin-right: 0;',
				),
				'selectors'            => array(
					'{{WRAPPER}} .oew-video-wrapper' => '{{VALUE}}',
				),
			),
		);

		$this->add_group_control(
			Group_Control_Border::get_type(),
			array(
				'name'     => 'video_border',
				'selector' => '{{WRAPPER}} .oew-video-wrapper',
			)
		);

		$this->add_control(
			'video_border_radius',
			array(
				'label'      => esc_html__( 'Border Radius', 'ocean-elementor-widgets' ),
				'type'       => Controls_Manager::DIMENSIONS,
				'size_units' => array( 'px', '%', 'custom' ),
				'selectors'  => array(
					'{{WRAPPER}} .oew-video-wrapper' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
				),
			)
		);

		$this->add_group_control(
			Group_Control_Box_Shadow::get_type(),
			array(
				'name'     => 'video_box_shadow',
				'selector' => '{{WRAPPER}} .oew-video-wrapper',
			)
		);

		$this->add_group_control(
			Group_Control_Css_Filter::get_type(),
			array(
				'name'     => 'video_css_filters',
				'selector' => '{{WRAPPER}} .oew-video-wrapper',
			)
		);
		$this->end_controls_section();

		$this->start_controls_section(
			'section_play_button_style',
			array(
				'label'     => esc_html__( 'Play Button', 'ocean-elementor-widgets' ),
				'tab'       => Controls_Manager::TAB_STYLE,
				'condition' => array(
					'show_play_button' => 'yes',
					'video_type'       => 'youtube',
				),
			)
		);

		$this->add_responsive_control(
			'play_button_size',
			array(
				'label'     => esc_html__( 'Icon Size', 'ocean-elementor-widgets' ),
				'type'      => Controls_Manager::SLIDER,
				'default'   => array(
					'size' => 48,
					'unit' => 'px',
				),
				'range'     => array(
					'px' => array(
						'min' => 10,
						'max' => 300,
					),
					'em' => array(
						'min' => 1,
						'max' => 10,
					),
				),
				'selectors' => array(
					'{{WRAPPER}} .oew-video-play-button i' => 'font-size: {{SIZE}}{{UNIT}};',
					'{{WRAPPER}} .oew-video-play-button svg' => 'width: {{SIZE}}{{UNIT}}; height: {{SIZE}}{{UNIT}};',
				),
			)
		);

		// Icon Color Control
		$this->add_control(
			'play_button_color',
			array(
				'label'     => esc_html__( 'Icon Color', 'ocean-elementor-widgets' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => '#ffffff',
				'selectors' => array(
					'{{WRAPPER}} .oew-video-play-button i' => 'color: {{VALUE}};',
					'{{WRAPPER}} .oew-video-play-button svg' => 'fill: {{VALUE}};',
				),
			)
		);

		// Icon Hover Color Control
		$this->add_control(
			'play_button_color_hover',
			array(
				'label'     => esc_html__( 'Icon Hover Color', 'ocean-elementor-widgets' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => '#ffffff',
				'selectors' => array(
					'{{WRAPPER}} .oew-video-play-button:hover i'   => 'color: {{VALUE}};',
					'{{WRAPPER}} .oew-video-play-button:hover svg' => 'fill: {{VALUE}};',
				),
			)
		);

		$this->add_control(
			'play_button_background_color',
			array(
				'label'     => esc_html__( 'Background Color', 'ocean-elementor-widgets' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => 'rgba(0, 0, 0, 0.6)',
				'selectors' => array(
					'{{WRAPPER}} .oew-video-play-button' => 'background-color: {{VALUE}};',
				),
			)
		);

		$this->add_control(
			'play_button_background_color_hover',
			array(
				'label'     => esc_html__( 'Background Hover Color', 'ocean-elementor-widgets' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => 'rgba(0, 0, 0, 0.8)',
				'selectors' => array(
					'{{WRAPPER}} .oew-video-play-button:hover' => 'background-color: {{VALUE}};',
				),
			)
		);

		$this->add_group_control(
			Group_Control_Box_Shadow::get_type(),
			array(
				'name'     => 'play_button_box_shadow',
				'label'    => esc_html__( 'Box Shadow', 'ocean-elementor-widgets' ),
				'selector' => '{{WRAPPER}} .oew-video-play-button',
			)
		);

		$this->add_control(
			'play_button_border_radius',
			array(
				'label'      => esc_html__( 'Border Radius', 'ocean-elementor-widgets' ),
				'type'       => Controls_Manager::DIMENSIONS,
				'size_units' => array( 'px', '%', 'em' ),
				'selectors'  => array(
					'{{WRAPPER}} .oew-video-play-button' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
				),
			)
		);

		$this->add_responsive_control(
			'play_button_padding',
			array(
				'label'      => esc_html__( 'Padding', 'ocean-elementor-widgets' ),
				'type'       => Controls_Manager::DIMENSIONS,
				'size_units' => array( 'px', '%', 'em' ),
				'selectors'  => array(
					'{{WRAPPER}} .oew-video-play-button' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
				),
			)
		);

		$this->add_responsive_control(
			'play_button_margin',
			array(
				'label'      => esc_html__( 'Margin', 'ocean-elementor-widgets' ),
				'type'       => Controls_Manager::DIMENSIONS,
				'size_units' => array( 'px', '%', 'em' ),
				'selectors'  => array(
					'{{WRAPPER}} .oew-video-play-button' => 'margin: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
				),
			)
		);

		$this->add_group_control(
			Group_Control_Border::get_type(),
			array(
				'name'     => 'play_button_border',
				'label'    => esc_html__( 'Border', 'ocean-elementor-widgets' ),
				'selector' => '{{WRAPPER}} .oew-video-play-button',
			)
		);

		$this->end_controls_section();
	}

	protected function render() {
		$settings  = $this->get_settings_for_display();
		$video_url = $settings['video_url'];

		if ( empty( $video_url ) ) {
			return;
		}

		$embed_params = array();

		if ( 'youtube' === $settings['video_type'] ) {
			if ( 'yes' === $settings['autoplay'] ) {
				$embed_params['autoplay'] = '1';
			}

			if ( 'yes' === $settings['mute'] ) {
				$embed_params['mute'] = '1';
			}

			if ( 'yes' !== $settings['controls'] ) {
				$embed_params['controls'] = '0';
			}

			if ( 'yes' === $settings['loop'] ) {
				$embed_params['loop']     = '1';
				$video_id                 = $this->get_youtube_id_from_url( $video_url );
				$embed_params['playlist'] = $video_id;
			}

			if ( ! empty( $settings['start_time'] ) ) {
				$embed_params['start'] = intval( $settings['start_time'] );
			}

			if ( ! empty( $settings['end_time'] ) ) {
				$embed_params['end'] = intval( $settings['end_time'] );
			}
		}

		$width_size = isset( $settings['width']['size'] ) ? $settings['width']['size'] : 500;
		$width_unit = isset( $settings['width']['unit'] ) ? $settings['width']['unit'] : 'px';
		$width      = $width_size . $width_unit;

		// Build the embed HTML
		$embed_html = $this->get_embed_html( $video_url, $embed_params, $settings['video_type'], $width );

		if ( ! $embed_html ) {
			echo esc_html__( 'This video provider is not supported or the URL is incorrect.', 'ocean-elementor-widgets' );
			return;
		}

		// Thumbnail and overlay handling
		$thumbnail_url = '';
		if ( ! empty( $settings['thumbnail']['url'] ) && 'youtube' === $settings['video_type'] ) {
			$thumbnail_url = Group_Control_Image_Size::get_attachment_image_src( $settings['thumbnail']['id'], 'thumbnail', $settings );
		}

		// Play button handling
		$play_button = '';
		if ( 'yes' === $settings['show_play_button'] && 'youtube' === $settings['video_type'] ) {
			// Start output buffering
			ob_start();
			Icons_Manager::render_icon(
				$settings['play_button_icon'],
				array(
					'aria-hidden' => 'true',
					'echo'        => true,
				)
			);
			$play_button_icon = ob_get_clean();

			if ( ! empty( $play_button_icon ) ) {
				$play_button  = '<div class="oew-video-play-button">';
				$play_button .= $play_button_icon;
				$play_button .= '<span class="elementor-screen-only">' . esc_html__( 'Play Video', 'ocean-elementor-widgets' ) . '</span>';
				$play_button .= '</div>';
			}
		}

		// Get the aspect ratio class.
		$aspect_ratio       = $settings['aspect_ratio'];
		$aspect_ratio_class = 'oew-aspect-ratio-' . $aspect_ratio;

		// Assign a unique ID to the widget instance.
		$widget_id = 'oew-video-' . $this->get_id();

		// Output the video embed code.
		echo '<div id="' . esc_attr( $widget_id ) . '" class="oew-video-wrapper ' . esc_attr( $aspect_ratio_class ) . '">';

		if ( $thumbnail_url ) {
			echo '<div class="oew-video-thumbnail" style="background-image: url(' . esc_url( $thumbnail_url ) . ');">';
			if ( $play_button ) {
				echo $play_button;
			}
			echo '</div>';
		}

		echo '<div class="oew-video-embed" style="display: ' . ( $thumbnail_url ? 'none' : 'block' ) . ';">';
		echo $embed_html; // Output the iframe HTML.
		echo '</div>';

		// Triggers the Facebook SDK to parse the embed when in editor mode.
		if ( \Elementor\Plugin::instance()->editor->is_edit_mode() ) {
			echo '<script>
            (function() {
                if ( typeof FB !== "undefined" && FB !== null ) {
                    // Delay the parsing to ensure the SDK has loaded
                    setTimeout(function() {
                        FB.XFBML.parse(document.getElementById("' . esc_js( $widget_id ) . '"));
                    }, 100);
                }
            })();
        </script>';
		}

		echo '</div>';
	}

	private function get_embed_html( $video_url, $embed_params, $video_type, $width ) {
		$embed_html = '';

		switch ( $video_type ) {
			case 'youtube':
				$embed_html = $this->get_youtube_embed_html( $video_url, $embed_params );
				if ( ! $embed_html ) {
					return false;
				}
				break;

			case 'instagram':
				$embed_html = $this->get_instagram_embed_html( $video_url, $width );
				if ( ! $embed_html ) {
					return false;
				}
				break;

			case 'facebook':
				$embed_html = $this->get_facebook_embed_html( $video_url, $width );
				if ( ! $embed_html ) {
					return false;
				}
				break;

			default:
				return false;
		}

		return $embed_html;
	}


	private function get_youtube_id_from_url( $url ) {
		preg_match( '/[\\?\\&]v=([^\\?\\&]+)/', $url, $matches );
		if ( ! isset( $matches[1] ) ) {
			preg_match( '/youtu\\.be\\/([^\\?\\&]+)/', $url, $matches );
			if ( ! isset( $matches[1] ) ) {
				return false;
			}
		}
		return $matches[1];
	}

	private function get_youtube_embed_html( $video_url, $embed_params ) {
		$video_id = $this->get_youtube_id_from_url( $video_url );
		if ( ! $video_id ) {
			return false;
		}

		$embed_url = 'https://www.youtube.com/embed/' . $video_id;
		if ( ! empty( $embed_params ) ) {
			$embed_url = add_query_arg( $embed_params, $embed_url );
		}
		$embed_html = '<iframe class="elementor-video" src="' . esc_url( $embed_url ) . '" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>';

		return $embed_html;
	}

	private function get_instagram_embed_html( $video_url, $width ) {
		$video_url       = strtok( $video_url, '?' );
		$video_url       = rtrim( $video_url, '/' );
		$path            = parse_url( $video_url, PHP_URL_PATH );
		$path_components = explode( '/', trim( $path, '/' ) );
		$shortcode       = array_pop( $path_components );

		if ( empty( $shortcode ) ) {
			return false;
		}

		$width_size = preg_replace( '/[^0-9]/', '', $width );

		$embed_url = 'https://www.instagram.com/p/' . $shortcode . '/embed/?maxwidth=' . $width_size;

		$embed_html = '<iframe src="' . esc_url( $embed_url ) . '" frameborder="0" scrolling="no" allowtransparency="true"></iframe>';

		return $embed_html;
	}

	private function get_facebook_embed_html( $video_url, $width ) {
		// Static variable to ensure the SDK is loaded only once.
		static $facebook_sdk_loaded = false;

		$embed_html = '';

		if ( ! $facebook_sdk_loaded ) {
			// Include the Facebook SDK script directly
			$embed_html         .= '<script async defer src="https://connect.facebook.net/en_US/sdk.js#xfbml=1&version=v3.2"></script>';
			$facebook_sdk_loaded = true;
		}

		$width = ! empty( $width ) ? $width : '500px';

		$embed_html .= '<div class="fb-video" data-href="' . esc_url( $video_url ) . '" data-width="' . esc_attr( $width ) . '" data-show-text="false"></div>';

		return $embed_html;
	}
}
