<?php

namespace Aventa;

use Elementor\Widget_Base;
use Elementor\Controls_Manager;
use Elementor\Utils;


if ( !defined( "ABSPATH" ) ) exit; 


class Rad_Video_Widget extends Widget_Base{

  public function get_name() {
    return "rad-video";
  }

  public function get_title() {
    return esc_html__("Video", "aventa");
  }

  public function get_keywords() {
		return [ "aventa" ];
	}

  public function get_icon() {
    return "eicon-video-playlist";
  }

  public function get_categories() {
    return [ Rad_Helpers::WIDGETS_CATEGORY ];
  }

  protected function register_controls() {

		// Widget content
    $this->start_controls_section(
			"section_title",
			[
				"label" => esc_html__( "Video", "aventa" ),
			]
		);

    $this->add_control(
      "video_source",
      [
        "label" => esc_html__( "Source", "aventa" ),
        "type" => Controls_Manager::SELECT,
        "options" => [
          "local_video"           => esc_html__( "Local", "aventa" ),
          "embeded_video_youtube" => esc_html__( "YouTube", "aventa" ),
          "embeded_video_vimeo"   => esc_html__( "Vimeo", "aventa" )
        ],
        "default" => "local_video"
      ]
    );

    $this->add_control(
      "video_url_webm",
      [
        "label" => esc_html__( ".WEBM Video", "aventa" ),
        "type" => Controls_Manager::TEXT,
        "placeholder" => "https://example.com/video.webm",
        "condition" => [
          "video_source" => "local_video"
        ]
      ]
    );

    $this->add_control(
      "video_url_mp4",
      [
        "label" => esc_html__( ".MP4 Video", "aventa" ),
        "type" => Controls_Manager::TEXT,
        "placeholder" => "https://example.com/video.mp4",
        "condition" => [
          "video_source" => "local_video"
        ]
      ]
    );

    $this->add_control(
      "video_url_ogv",
      [
        "label" => esc_html__( ".OGV Video", "aventa" ),
        "type" => Controls_Manager::TEXT,
        "placeholder" => "https://example.com/video.ogv",
        "condition" => [
          "video_source" => "local_video"
        ]
      ]
    );

    $this->add_control(
      "video_url",
      [
        "label" => esc_html__( "Video URL", "aventa" ),
        "type" => Controls_Manager::TEXT,
        "placeholder" => "https://example.com/video",
        "condition" => [
          "video_source!" => "local_video"
        ]
      ]
    );

    $this->add_control(
      "video_aspect_ratio",
      [
        "label" => esc_html__( "Aspect Ratio", "aventa" ),
        "type" => Controls_Manager::SELECT,
        "options" => [
          "169"      => esc_html__( "16:9", "aventa" ),
          "43"       => esc_html__( "4:3", "aventa" ),
          "235"      => esc_html__( "2.35:1", "aventa" )
        ],
        "default" => "169",
        "condition" => [ 
          "video_source!" => "local_video",
          "video_popup" => ""
        ]
      ]
    );

    $this->add_control(
      "video_popup",
      [
        "label" => esc_html__( "Pop-up", "aventa" ),
        "type" => Controls_Manager::SWITCHER,
        "label_on" => esc_html__( "Yes", "aventa" ),
        "label_off" => esc_html__( "No", "aventa" ),
        "return_value" => "true"
      ]
    );

    $this->add_control(
			"video_cover",
			[
				"label" => esc_html__( "Cover Image", "aventa" ),
				"type" => Controls_Manager::MEDIA,
				"default" => [
					"url" => Utils::get_placeholder_image_src(),
        ],
        "condition" => [
          "video_popup" => "true"
        ]
			]
		); 

    $this->add_control(
			"video_poster",
			[
				"label" => esc_html__( "Cover Image", "aventa" ),
				"type" => Controls_Manager::MEDIA,
				"default" => [
					"url" => Utils::get_placeholder_image_src(),
        ],
        "conditions" => [
          "terms" => [
            [
              "name" => "video_popup",
              "operator" => "==",
              "value" => ""
            ],
            [
              "name" => "video_source",
              "operator" => "==",
              "value" => "local_video"
            ] 
          ]
        ]
			]
		); 

    $this->add_control(
      "video_autoplay",
      [
        "label" => esc_html__( "Autoplay", "aventa" ),
        "type" => Controls_Manager::SWITCHER,
        "label_on" => esc_html__( "On", "aventa" ),
        "label_off" => esc_html__( "Off", "aventa" ),
        "return_value" => "true",
        "default" => "true",
        "separator" => "before"
      ]
    );

    $this->add_control(
      "video_loop",
      [
        "label" => esc_html__( "Loop", "aventa" ),
        "type" => Controls_Manager::SWITCHER,
        "label_on" => esc_html__( "On", "aventa" ),
        "label_off" => esc_html__( "Off", "aventa" ),
        "return_value" => "true",
        "condition" => [
          "video_source" => "local_video"
        ]
      ]
    );

		$this->end_controls_section();

    // General style
    $this->start_controls_section(
			"section_general_style",
			[
				"label" => esc_html__( "General", "aventa" ),
				"tab" => Controls_Manager::TAB_STYLE,
			]
		);

    Rad_Helpers::alignment( 
      $this, 
      "video_play_button_align", 
      [ "video_popup" => "true" ], 
      [], 
      "center", 
      false 
    );

    $this->add_control(
      "video_play_button_style",
      [
        "label" => esc_html__( "Play Button Style", "aventa" ),
        "type" => Controls_Manager::CHOOSE,
        "options" => [
          "light" => [
            "title" => esc_html__( "Light", "aventa" ),
            "icon" => "fas fa-sun"
          ],
          "dark" => [
            "title" => esc_html__( "Dark", "aventa" ),
            "icon" => "fas fa-moon"
          ]
        ],
        "default" => "dark"
      ]
    );

		$this->end_controls_section();

  }

  protected function render() {
    $settings = $this->get_settings_for_display();

		if ( 
      "" === $settings["video_url"]       && 
      "" === $settings["video_url_webm"]  && 
      "" === $settings["video_url_mp4"]   && 
      "" === $settings["video_url_ogv"]
      ) {
			return;
		}

    $video_webm             = esc_url( $settings[ "video_url_webm" ] );
    $video_mp4              = esc_url( $settings[ "video_url_mp4" ] );
    $video_ogv              = esc_url( $settings[ "video_url_ogv" ] );
    $video_display_type     = esc_html( $settings[ "video_source" ] );
    $alignment              = esc_attr( $settings[ "video_play_button_align" ] );
    $video_url              = esc_url( $settings[ "video_url" ] );
    $video_popup            = $settings[ "video_popup" ];
    $video_background_image = esc_attr( $settings[ "video_cover" ][ "id" ] );
    $video_poster_image     = "";

    if($video_popup == "" && $video_source == "local_video" || $video_popup == "popup" && $video_source == "local_video")
    {
      $video_poster_image     = esc_attr( $settings[ "video_poster" ][ "id" ] );
    }
    
    $video_play_button_color= esc_attr( $settings[ "video_play_button_style" ] );
    $loop                   = esc_attr( $settings[ "video_loop" ] );
    $video_autoplay         = esc_attr( $settings[ "video_autoplay" ] );
    $el_aspect              = esc_attr( $settings[ "video_aspect_ratio" ] );
    $video_vimeo_id = $video_display_type == "embeded_video_vimeo" 
      ? $video_url
      : "";
    $video_youtube_id = $video_display_type == "embeded_video_youtube"
      ? $video_url
      : "";

    if ( $video_popup ) {
      $video_display_type .= "_popup";
    }

    if ($video_display_type == "local_video" || $video_display_type == "local_video_popup") {
        if ($video_webm == "" && $video_mp4 == "" && $video_ogv == "") {
          return;
        }
    } elseif ($video_display_type == "embeded_video_vimeo" || $video_display_type == "embeded_video_vimeo_popup") {
        if ($video_vimeo_id == "") {
          return;
        }
    } elseif ($video_display_type == "embeded_video_youtube" || $video_display_type == "embeded_video_youtube_popup") {
        if ($video_youtube_id == "") {
          return;
        }
    }

    /* Video ID extractor*/
    $vimeoURL = $video_vimeo_id;
    $vimeoId  = preg_replace("/[^0-9]/", "", $vimeoURL);

    // detect youtube id form url
    $youtubeURL = $video_youtube_id;
    
    if ($youtubeURL && ($video_display_type == "embeded_video_youtube_popup" || $video_display_type == "embeded_video_youtube")) {

        $pattern = '#^(?:https?://)?';    # Optional URL scheme. Either http or https.
        $pattern .= '(?:www\.)?';         #  Optional www subdomain.
        $pattern .= '(?:';                #  Group host alternatives:
        $pattern .=   'youtu\.be/';       #    Either youtu.be,
        $pattern .=   '|youtube\.com';    #    or youtube.com
        $pattern .=   '(?:';              #    Group path alternatives:
        $pattern .=     '/embed/';        #      Either /embed/,
        $pattern .=     '|/v/';           #      or /v/,
        $pattern .=     '|/watch\?v=';    #      or /watch?v=,    
        $pattern .=     '|/watch\?.+&v='; #      or /watch?other_param&v=
        $pattern .=   ')';                #    End path alternatives.
        $pattern .= ')';                  #  End host alternatives.
        $pattern .= '([\w-]{11})';        # 11 characters (Length of Youtube video ids).
        $pattern .= '(?:.+)?$#x';         # Optional other ending URL parameters.
        preg_match($pattern, $youtubeURL, $matches);
        $youtubeId = (isset($matches[1])) ? $matches[1] : false;

        if($youtubeId == false)
        {
          echo "<p>". esc_html__("The video URL cannot be parsed" , "aventa") ."</p>";
        }
    }

    if ( is_numeric($video_background_image) ) {
      $video_background_image = rad_get_image_url($video_background_image, "full");
    }

    if ( is_numeric($video_poster_image) ) {
      $video_poster_image = rad_get_image_url($video_poster_image, "full");
    }

    $id = rad_element_id("vd");

    ob_start();

    $attributes = "";
    if ($video_display_type == "local_video_popup") {
      $attributes = " preload=\"none\"";
    } elseif ($video_display_type == "local_video") {
      $attributes = " preload=\"auto\"";
    }

    if ($video_poster_image) {
      $attributes .= " poster=\"" . esc_url($video_poster_image) . "\"";
    }

    if ($loop == "true") {
      $attributes .= " loop";
    }

    if ($video_autoplay == "true" && $video_display_type == "local_video") {
      $attributes .= " autoplay muted";
    }

    ?>

    <?php if ($video_display_type == "local_video_popup") {?>

        <!-- Hidden video div -->
        <div style="display:none;" id="video<?php echo esc_attr($id); ?>">
            <video class="lg-video-object lg-html5 video-js vjs-default-skin"<?php echo " " . $attributes; //validated before echo   ?>>

                <?php if (esc_url($video_webm)) {?>
                    <source src="<?php echo esc_url($video_webm); ?>" type="video/webm">
                <?php }?>

                <?php if (esc_url($video_mp4)) {?>
                    <source src="<?php echo esc_url($video_mp4); ?>" type="video/mp4">
                <?php }?>

                <?php if (esc_url($video_ogv)) {?>
                    <source src="<?php echo esc_url($video_ogv); ?>" type="video/ogv">
                <?php }?>

            </video>
        </div>

    <?php }?>

    <?php if ($video_display_type == "local_video_popup" || $video_display_type == "embeded_video_youtube_popup" || $video_display_type == "embeded_video_vimeo_popup") {
        ?>

        <div id="<?php echo esc_attr($id); ?>" class="video_embed_container">

            <?php if ($video_display_type == "local_video_popup") {
            ?>


                <!-- data-src should not be provided when you use html5 videos -->
                <a data-html="#video<?php echo esc_attr($id); ?>">
                  <?php if (esc_url($video_background_image)) {?>
                      <img src="<?php echo esc_url($video_background_image); ?>" alt="<?php echo esc_attr__("Video", "aventa"); ?>" />
                  <?php }?>
                  <div class="play-button 
                    <?php 
                      echo esc_attr($video_play_button_color); 
                      echo " $alignment"; 
                    ?>
                    "
                  >
                    <?php echo \rad_Icon_Manager::get_icon("caret-right", "light"); ?>
                  </div>
                </a>

            <?php } else if ($video_display_type == "embeded_video_youtube_popup") {
            ?>

                <!-- Youtube popUp -->
                <a class="image" href="https://youtu.be/<?php echo str_replace("http://",'', esc_url($youtubeId)); ?>">

                    <?php if (esc_url($video_background_image)) {?>
                        <img src="<?php echo esc_url($video_background_image); ?>" alt="<?php echo esc_attr__("Video", "aventa"); ?>" />
                    <?php }?>

                     <div class="play-button <?php echo esc_attr($video_play_button_color); echo " $alignment";  ?>">
                        <?php echo \rad_Icon_Manager::get_icon("caret-right", "light"); ?>
                    </div>
                </a>

            <?php } else if ($video_display_type == "embeded_video_vimeo_popup") {
            ?>

                <!-- Vimeo popUp -->
                <a class="image" href="https://vimeo.com/<?php echo esc_url($vimeoId); ?>" >

                    <?php if (esc_url($video_background_image)) {?>
                        <img src="<?php echo esc_url($video_background_image); ?>" alt="<?php echo esc_attr__("Video", "aventa"); ?>" />
                    <?php }?>

                     <div class="play-button <?php echo esc_attr($video_play_button_color); echo " $alignment";  ?>">
                        <?php echo \rad_Icon_Manager::get_icon("caret-right", "light"); ?>
                    </div>
                </a>

            <?php }?>

        </div>

        <?php }?>

        <?php
        if ($video_display_type == "local_video") {?>

        <!-- HTML5 Video popUp -->
        <div class="inline_video video_embed_container">
            <video id="<?php echo esc_attr($id); ?>-player" class="video" width="320" height="240"<?php echo " " . $attributes; //validated   ?>>

                <?php if (esc_url($video_webm)) {?>
                    <source src="<?php echo esc_url($video_webm); ?>" type="video/webm">
                <?php }?>

                <?php if (esc_url($video_mp4)) {?>
                    <source src="<?php echo esc_url($video_mp4); ?>" type="video/mp4">
                <?php }?>

                <?php if (esc_url($video_ogv)) {?>
                    <source src="<?php echo esc_url($video_ogv); ?>" type="video/ogv">
                <?php }?>

                <object width="320" height="240" type="application/x-shockwave-flash" data="<?php echo RAD_THEME_ASSETS_URI; ?>/js/flashmediaelement.swf">
                    <param name="movie" value="<?php echo RAD_THEME_ASSETS_URI; ?>/js/flashmediaelement.swf" />
                    <param name="flashvars" value="controls=true&file="<?php echo esc_url($video_mp4); ?>" />

                    <?php if ($video_poster_image) {?>

                        <img src="<?php echo esc_url($video_poster_image); ?>" width="1920" height="800" title="<?php esc_attr_e("No video playback capabilities", "aventa")?>" alt="<?php esc_attr_e("Video thumb", "aventa")?>" />

                    <?php }?>

                </object>
            </video>

            <?php if (esc_attr($video_poster_image)) {?>

                <div class="play-button <?php echo esc_attr($video_play_button_color); echo " $alignment"; ?>">
                    <?php echo \rad_Icon_Manager::get_icon("caret-right", "solid"); ?>
                </div>

            <?php }?>


        </div>

        <?php
        } else if ($video_display_type == "embeded_video_vimeo") {
        ?>

        <div id="<?php echo esc_attr($id); ?>">

            <?php
        $video_w   = 500;
        $video_h   = 310; //1.61 golden ratio
        $link      = "https://vimeo.com/" . $vimeoId;
        $el_aspect = "vc_video-aspect-ratio-" . $el_aspect;
        global $wp_embed;

        $embed = $wp_embed->run_shortcode("[embed  width=\"" . esc_attr($video_w) . "\" height=\"" . esc_attr($video_h) . "\"]" . $link . "[/embed]");
        ?>

            <div class="wpb_video_widget wpb_content_element vc_clearfix <?php echo esc_attr($el_aspect); ?>">
                <div class="wpb_wrapper">
                    <div class="wpb_video_wrapper"> <?php echo "" . $embed; //validated   ?> </div>
                </div>
            </div>
        </div>

        <?php } else if ($video_display_type == "embeded_video_youtube") {
        ?>

        <div id="<?php echo esc_attr($id); ?>">

            <?php
        $el_aspect = "vc_video-aspect-ratio-169";
        ?>

            <div class="wpb_video_widget wpb_content_element vc_clearfix <?php echo esc_attr($el_aspect); ?>">
                <div class="wpb_wrapper">
                    <div class="wpb_video_wrapper">
                        <iframe title="<?php esc_attr_e("YouTube video player", "aventa")?>" src="https://www.youtube.com/embed/<?php echo str_replace("http://",'', esc_url($youtubeId)); ?>" allowfullscreen></iframe>
                    </div>
                </div>
            </div>
        </div>

        <?php }

    echo ob_get_clean();
    
  }

}