<?php
use Elementor\Widget_Base;
use Elementor\Controls_Manager;
use Elementor\Group_Control_Border;
use Elementor\Group_Control_Box_Shadow;
use Elementor\Group_Control_Text_Shadow;
use Elementor\Group_Control_Typography;
use Elementor\Group_Control_Background;
use Elementor\Core\Kits\Documents\Tabs\Global_Colors;
use Elementor\Core\Kits\Documents\Tabs\Global_Typography;
use Elementor\Repeater;
use Elementor\Group_Control_Image_Size;
use CrtAddons\Classes\Utilities;

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

class CRT_Video_Playlist extends Widget_Base {

	public function get_name() {
		return 'crt-video-playlist';
	}

	public function get_title() {
		return esc_html__( 'Video Playlist', 'crt-manage' );
	}

	public function get_icon() {
		return 'crt-icon eicon-video-playlist';
	}

	public function get_categories() {
        return [ 'crt_manage_theme'];
    }

    public function get_script_depends() {
        return [ 'crt-video-playlist' ];
    }

	public function get_keywords() {
		return [ 'royal', 'video playlist' ];
	}

	public function has_widget_inner_wrapper(): bool {
		return ! \Elementor\Plugin::$instance->experiments->is_feature_active( 'e_optimized_markup' );
	}

	public function get_custom_help_url() {
		if ( empty(get_option('crt_wl_plugin_links')) )
        // return 'https://royal-elementor-addons.com/contact/?ref=rea-plugin-panel-video-playlist-help-btn';
    		return 'https://crthemes.com/contact';
    }

	public function is_reload_preview_required() {
		return true;
	}
	
	protected function register_controls() {

		$this->start_controls_section(
			'settings_section',
			[
				'label' => esc_html__( 'Settings', 'crt-manage' ),
				'tab' => \Elementor\Controls_Manager::TAB_CONTENT,
			]
		);

        $this->add_control(
            'query_group_title',
            [
                'label' => esc_html__( 'Query', 'crt-manage' ),
                'type' => \Elementor\Controls_Manager::HEADING,
                'separator' => 'before',
            ]
        );

		$this->add_control(
			'playlist_query',
			[
				'label' => esc_html__( 'Playlist Query', 'crt-manage' ),
				'type' => \Elementor\Controls_Manager::SELECT,
				'default' => 'custom',
				'options' => [
					'custom' => esc_html__( 'Custom URLs', 'crt-manage' ),
					'playlist' => esc_html__( 'YouTube Playlist', 'crt-manage' ),
				],
			]
		);

		$this->add_control(
			'youtube_api_key',
			[
				'label' => esc_html__( 'YouTube API Key', 'crt-manage' ),
				'type' => \Elementor\Controls_Manager::TEXT,
				'default' => '',
				'description' => 'To get your <strong>Youtube API Key</strong> please watch this <strong><a href="https://youtu.be/LLAZUTbc97I" target="_blank">Video Tutorial</a></strong>.',
				'condition' => [
					'playlist_query' => 'playlist',
				],
			]
		);

		$this->add_control(
			'youtube_playlist_id',
			[
				'label' => esc_html__( 'YouTube Playlist ID', 'crt-manage' ),
				'type' => \Elementor\Controls_Manager::TEXT,
				'default' => '',
				'description' => 'To get your <strong>Youtube Playlist ID</strong> go to YouTube Channel, select Playlist and find E.g: <strong>list=PLjFiZESrp9558M7Rghnk5s4sMq6m3RyOb</strong> in the URL and copy the ID.',
                'condition' => [
                    'playlist_query' => 'playlist',
                ],
			]
		);
        $this->add_control(
            'title_group_title',
            [
                'label' => esc_html__( 'Title', 'crt-manage' ),
                'type' => \Elementor\Controls_Manager::HEADING,
                'separator' => 'before',
            ]
        );
    
        $this->add_control(
            'title_tag',
            [
                'label' => esc_html__( 'HTML Tag', 'crt-manage' ),
                'type' => \Elementor\Controls_Manager::SELECT,
                'default' => 'h6',
                'options' => [
                    'h1' => 'H1',
                    'h2' => 'H2',
                    'h3' => 'H3',
                    'h4' => 'H4',
                    'h5' => 'H5',
                    'h6' => 'H6',
                    'div' => 'div',
                    'span' => 'span',
                    'P' => 'p'
                ]
            ]
        );
    
        $this->add_control(
            'playlist_title',
            [
                'label' => esc_html__( 'Playlist Title', 'crt-manage' ),
                'type' => \Elementor\Controls_Manager::TEXT,
                'default' => esc_html__( 'Now Playing', 'crt-manage' ),
            ]
        );
    
        $this->add_control(
            'urls_group_title',
            [
                'label' => esc_html__( 'Custom Video URLs', 'crt-manage' ),
                'type' => \Elementor\Controls_Manager::HEADING,
                'separator' => 'before',
            ]
        );

        $repeater = new \Elementor\Repeater();
    
        $repeater->add_control(
            'video_url',
            [
                'label' => esc_html__( 'Video URL', 'crt-manage' ),
                'type' => \Elementor\Controls_Manager::URL,
                'default' => [
                    'url' => 'https://youtu.be/OrtzJs-wzlw',
                ],
                'label_block' => true,
            ]
        );
    
        $this->add_control(
            'video_urls',
            [
                'label' => esc_html__( 'Video URLs', 'crt-manage' ),
                'type' => \Elementor\Controls_Manager::REPEATER,
                'fields' => $repeater->get_controls(),
                'default' => [
                    [ 'video_url' => [ 'url' => 'https://youtu.be/1MbYFFXg7-M' ] ],
                    [ 'video_url' => [ 'url' => 'https://youtu.be/zbcIZKpBZRU' ] ],
                    [ 'video_url' => [ 'url' => 'https://youtu.be/RK3MQe6TnaE' ] ],
                    [ 'video_url' => [ 'url' => 'https://youtu.be/PXvDJ-IBtHk' ] ],
                    [ 'video_url' => [ 'url' => 'https://youtu.be/UyiMxkuvuQI' ] ],
                    [ 'video_url' => [ 'url' => 'https://youtu.be/9qJH__RF--I' ] ],
                ],
                'title_field' => '{{ video_url.url }}',
                'condition' => [
                    'playlist_query' => 'custom',
                ],
            ]
        );

        $this->add_control(
            'controller_icons_heading',
            [
                'label' => esc_html__( 'Controller Icons', 'crt-manage' ),
                'type' => \Elementor\Controls_Manager::HEADING,
                'separator' => 'before',
            ]
        );

        $this->add_control(
            'play_icon',
            [
                'label' => esc_html__( 'Play Icon', 'crt-manage' ),
                'type' => \Elementor\Controls_Manager::ICONS,
                'default' => [
                    'value' => 'fas fa-play',
                    'library' => 'fa-solid',
                ],
            ]
        );

        $this->add_control(
            'pause_icon',
            [
                'label' => esc_html__( 'Pause Icon', 'crt-manage' ),
                'type' => \Elementor\Controls_Manager::ICONS,
                'default' => [
                    'value' => 'fas fa-pause',
                    'library' => 'fa-solid',
                ],
            ]
        );

		$this->end_controls_section();

		$this->start_controls_section(
			'general_section',
			[
				'label' => esc_html__( 'General', 'crt-manage' ),
				'tab' => \Elementor\Controls_Manager::TAB_STYLE,
			]
		);

		$this->add_control(
			'wrap_background_color',
			[
				'label' => esc_html__( 'Background Color', 'crt-manage' ),
				'type' => \Elementor\Controls_Manager::COLOR,
				'selectors' => [
					'{{WRAPPER}} .crt-vplaylist-wrap' => 'background-color: {{VALUE}};',
				],
			]
		);

		$this->add_control(
			'widget_accent_color',
			[
				'label' => esc_html__( 'Accent Color', 'crt-manage' ),
				'type' => \Elementor\Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .crt-vplaylist-controller' => 'background-color: {{VALUE}};',
                ],
				'default' => '#f84643',
			]
		);

		$this->add_control(
			'controller_icon_color',
			[
				'label' => esc_html__( 'Icon Color', 'crt-manage' ),
				'type' => \Elementor\Controls_Manager::COLOR,
				'selectors' => [
					'{{WRAPPER}} .crt-vplaylist-controller svg' => 'fill: {{VALUE}}; color: {{VALUE}};',
					'{{WRAPPER}} .crt-vplaylist-controller i' => 'color: {{VALUE}};',
				],
			]
		);

		$this->add_control(
			'controller_icon_size',
			[
				'label' => esc_html__( 'Icon Size', 'crt-manage' ),
				'type' => \Elementor\Controls_Manager::SLIDER,
				'size_units' => [ 'px', '%', 'em', 'rem', 'vw', 'custom' ],
				'selectors' => [
					'{{WRAPPER}} .crt-vplaylist-controller svg' => 'width: {{SIZE}}{{UNIT}}; height: {{SIZE}}{{UNIT}};',
					'{{WRAPPER}} .crt-vplaylist-controller i' => 'font-size: {{SIZE}}{{UNIT}};',
				],
			]
		);

        $this->add_control(
            'title_color',
            [
                'label' => esc_html__( 'Title Color', 'crt-manage' ),
                'type' => \Elementor\Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .crt-vplaylist-heading, {{WRAPPER}} .crt-vplaylist-info-title' => 'color: {{VALUE}};',
                ],
            ]
        );

        $this->add_group_control(
            \Elementor\Group_Control_Typography::get_type(),
            [
                'name' => 'title_typography',
                'label' => esc_html__( 'Title Typography', 'crt-manage' ),
                'selector' => '{{WRAPPER}} .crt-vplaylist-heading, {{WRAPPER}} .crt-vplaylist-info-title',
				'fields_options' => [
					'typography' => [
						'default' => 'custom',
					],
					'font_size' => [
						'default' => [
							'size' => '15',
							'unit' => 'px'
						]
					]
				]
            ]
        );

        $this->add_control(
            'heading_span_color',
            [
                'label' => esc_html__( 'Playlist Title Color', 'crt-manage' ),
                'type' => \Elementor\Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .crt-vplaylist-heading span' => 'color: {{VALUE}};',
                ],
            ]
        );

        $this->add_group_control(
            \Elementor\Group_Control_Typography::get_type(),
            [
                'name' => 'heading_span_typography',
                'label' => esc_html__( 'Playlist Title Typography', 'crt-manage' ),
                'selector' => '{{WRAPPER}} .crt-vplaylist-heading span',
            ]
        );

        $this->add_control(
            'current_title_color',
            [
                'label' => esc_html__( 'Current Title Color', 'crt-manage' ),
                'type' => \Elementor\Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .crt-vplaylist-heading .crt-vplaylist-current-title' => 'color: {{VALUE}};',
                ],
            ]
        );

        $this->add_group_control(
            \Elementor\Group_Control_Typography::get_type(),
            [
                'name' => 'current_title_typography',
                'label' => esc_html__( 'Current Title Typography', 'crt-manage' ),
                'selector' => '{{WRAPPER}} .crt-vplaylist-heading .crt-vplaylist-current-title',
            ]
        );

		$this->end_controls_section();

		// Add more sections and controls as needed
	}
    
    private function get_youtube_playlist_videos($playlist_id, $api_key) {
        $videos = [];
    
        if ( empty($api_key) ) {
            return $videos;
        }
    
        $api_url = sprintf(
            'https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId=%s&key=%s',
            urlencode($playlist_id),
            urlencode($api_key)
        );
    
        $response = wp_remote_get($api_url);
    
        if ( is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200 ) {
            return $videos;
        }
    
        $body = json_decode(wp_remote_retrieve_body($response), true);
    
        if ( !empty($body['items']) ) {
            foreach ( $body['items'] as $item ) {
                if ( !empty($item['snippet']['resourceId']['videoId']) ) {
                    $videos[] = 'https://youtu.be/' . sanitize_text_field($item['snippet']['resourceId']['videoId']);
                }
            }
        }
    
        return $videos;
    }

    public function crt_get_svg_icon( $icon ) {
        static $icons_array = null;
    
        if ( is_null( $icons_array ) ) {
            $url = trailingslashit( CRT_MANAGE_URI ) . 'assets/img/svg/svg-icons.json';
    
            $response = wp_remote_get( $url );
    
            if ( is_wp_error( $response ) ) {
                $icons_array = [];
            } else {
                $body = wp_remote_retrieve_body( $response );
                $icons_array = json_decode( $body, true );
            }
        }
    
        $output  = '<span class="crt-svg-icon crt-inline-flex">';
        $output .= isset( $icons_array[ $icon ] ) ? $icons_array[ $icon ] : '';
        $output .= '</span>';
    
        return $output;
    }    
    
    protected function render() {
        $settings = $this->get_settings_for_display();

        $title_tag       = !empty($settings['title_tag']) ? $settings['title_tag'] : 'h6';
        $playlist_title  = !empty($settings['playlist_title']) ? $settings['playlist_title'] : esc_html__('Now Playing', 'crt-manage');
        $playlist_query  = !empty($settings['playlist_query']) ? $settings['playlist_query'] : 'custom';

        $video_urls = [];

        if ( 'playlist' === $playlist_query && !empty($settings['youtube_playlist_id']) ) {
            $video_urls = $this->get_youtube_playlist_videos($settings['youtube_playlist_id'], $settings['youtube_api_key']);
        } elseif ( !empty($settings['video_urls']) && is_array($settings['video_urls']) ) {
            foreach ( $settings['video_urls'] as $video_item ) {
                if ( !empty($video_item['video_url']['url']) ) {
                    $video_urls[] = esc_url($video_item['video_url']['url']);
                }
            }
        }

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

        echo '<div class="crt-vplaylist-wrap">';

            // Video Player
            echo '<div class="video-player-wrap">';
                echo '<div class="video-player">';
                    echo '<div class="crt-vplaylist-main"></div>';
                echo '</div>';
            echo '</div>';

            // Playlist Panel
            echo '<div class="crt-vplaylist-thumbs-wrap">';

                echo '<div class="crt-vplaylist-highlight">';
                    echo '<div class="crt-vplaylist-heading">';
                        echo '<span>' . esc_html($playlist_title) . '</span>';
                        echo '<' . esc_attr($title_tag) . ' class="crt-vplaylist-current-title"></' . esc_attr($title_tag) . '>';
                    echo '</div>';

                    echo '<div class="crt-vplaylist-controller">';
                        echo '<div class="crt-play">';
                        if ( ! empty( $settings['play_icon']['value'] ) ) {
                            \Elementor\Icons_Manager::render_icon( $settings['play_icon'], [ 'aria-hidden' => 'true' ] );
                        } else {
                            echo $this->crt_get_svg_icon('play'); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                        }
                        echo '</div>';
                        echo '<div class="crt-pause">';
                        if ( ! empty( $settings['pause_icon']['value'] ) ) {
                            \Elementor\Icons_Manager::render_icon( $settings['pause_icon'], [ 'aria-hidden' => 'true' ] );
                        } else {
                            echo $this->crt_get_svg_icon('pause'); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                        }
                        echo '</div>';
                    echo '</div>';
                echo '</div>';

                echo '<div class="crt-vplaylist-thumbs" data-urls=\'' . esc_attr(wp_json_encode($video_urls)) . '\'>';
                    echo '<ul></ul>';
                echo '</div>';

            echo '</div>';

        echo '</div>';
    }

}
