<?php

namespace PhotoSphereViewer\Includes;

use Elementor\Controls_Manager;
use Elementor\Widget_Base;
use Elementor\Group_Control_Typography;
use Elementor\Modules\Promotions\Controls\Promotion_Control;

class Video_360_Viewer extends Widget_Base {

    private function is_pro_activated(): bool {
        return ProStatus::is_active();
    }

    public function get_name() {
        return 'psv-video-360';
    }

    public function get_title() {
        return __('360° Video Player', 'photo-sphere-viewer');
    }

    public function get_icon() {
        return 'psv-widget-icon psv-widget-icon-video';
    }

    public function get_categories() {
        return ['photo-sphere-viewer'];
    }

    public function get_keywords() {
        return [
            '360 video',
            '360',
            'video',
            'psv',
            'photo sphere viewer',
            'panorama video',
            'equirectangular video',
            'immersive video',
            'vr video',
            'mp4',
            'spherical video',
            'player',
            'youtube 360',
        ];
    }

    public function get_script_depends() {
        return ['psv-main'];
    }

    public function get_style_depends() {
        return ['psv-style'];
    }

    protected function register_controls() {

        /**
         * Content Section
         */
        $this->start_controls_section(
            '_content_section',
            [
                'label' => __('Video', 'photo-sphere-viewer'),
                'tab'   => Controls_Manager::TAB_CONTENT,
            ]
        );

        $this->add_control(
            'video_source_type',
            [
                'label'   => __('Video Source', 'photo-sphere-viewer'),
                'type'    => Controls_Manager::SELECT,
                'default' => 'url',
                'options' => [
                    'url'    => __('URL', 'photo-sphere-viewer'),
                    'upload' => __('Media Library', 'photo-sphere-viewer'),
                ],
            ]
        );

        $this->add_control(
            'video_url',
            [
                'label'       => __('Video URL', 'photo-sphere-viewer'),
                'type'        => Controls_Manager::URL,
                'placeholder' => __('https://example.com/360-video.mp4', 'photo-sphere-viewer'),
                'default'     => ['url' => PSV_ASSETS_URL . 'videos/photo-sphere-viewer.mp4'],
                'condition'   => ['video_source_type' => 'url'],
                'label_block' => true,
            ]
        );

        $this->add_control(
            'video_upload',
            [
                'label'      => __('Upload Video', 'photo-sphere-viewer'),
                'type'       => Controls_Manager::MEDIA,
                'media_types' => ['video'],
                'default'    => ['url' => ''],
                'condition'  => ['video_source_type' => 'upload'],
            ]
        );

        $this->add_control(
            'video_caption',
            [
                'label'       => __('Caption', 'photo-sphere-viewer'),
                'type'        => Controls_Manager::TEXT,
                'default'     => __('360° Video Demo', 'photo-sphere-viewer'),
                'label_block' => true,
            ]
        );

        $this->end_controls_section();

        /**
         * Layout Section
         */
        $this->start_controls_section(
            '_layout_section',
            [
                'label' => __('Layout', 'photo-sphere-viewer'),
                'tab'   => Controls_Manager::TAB_CONTENT,
            ]
        );

        $this->add_control(
            'viewer_width',
            [
                'label'      => __('Width', 'photo-sphere-viewer'),
                'type'       => Controls_Manager::SLIDER,
                'size_units' => ['px', '%', 'vw'],
                'range'      => [
                    'px' => ['min' => 300, 'max' => 3000, 'step' => 5],
                    '%'  => ['min' => 0, 'max' => 100],
                ],
                'default'    => ['unit' => '%', 'size' => 100],
                'selectors'  => [
                    '{{WRAPPER}} .photo-sphere-viewer' => 'width: {{SIZE}}{{UNIT}};',
                ],
            ]
        );

        $this->add_control(
            'viewer_height',
            [
                'label'       => __('Height', 'photo-sphere-viewer'),
                'type'        => Controls_Manager::SLIDER,
                'size_units'  => ['px', '%', 'vh'],
                'default'     => ['unit' => 'vh', 'size' => 70],
                'selectors'   => [
                    '{{WRAPPER}} .photo-sphere-viewer' => 'height: {{SIZE}}{{UNIT}};',
                ],
                'render_type' => 'template',
            ]
        );

        $this->end_controls_section();

        /**
         * Playback Section
         */
        $this->start_controls_section(
            '_playback_section',
            [
                'label' => __('Playback', 'photo-sphere-viewer'),
                'tab'   => Controls_Manager::TAB_CONTENT,
            ]
        );

        $this->add_control(
            'video_autoplay',
            [
                'label'        => __('Autoplay', 'photo-sphere-viewer'),
                'type'         => $this->is_pro_activated() ? Controls_Manager::SWITCHER : Promotion_Control::TYPE,
                'label_on'     => __('Yes', 'photo-sphere-viewer'),
                'label_off'    => __('No', 'photo-sphere-viewer'),
                'return_value' => 'yes',
                'default'      => '',
                'description'  => !$this->is_pro_activated() ? __('Available in Pro version', 'photo-sphere-viewer') : __('Browsers may block autoplay without mute.', 'photo-sphere-viewer'),
            ]
        );

        $this->add_control(
            'video_muted',
            [
                'label'        => __('Muted', 'photo-sphere-viewer'),
                'type'         => Controls_Manager::SWITCHER,
                'label_on'     => __('Yes', 'photo-sphere-viewer'),
                'label_off'    => __('No', 'photo-sphere-viewer'),
                'return_value' => 'yes',
                'default'      => 'yes',
            ]
        );

        $this->add_control(
            'video_loop',
            [
                'label'        => __('Loop', 'photo-sphere-viewer'),
                'type'         => $this->is_pro_activated() ? Controls_Manager::SWITCHER : Promotion_Control::TYPE,
                'label_on'     => __('Yes', 'photo-sphere-viewer'),
                'label_off'    => __('No', 'photo-sphere-viewer'),
                'return_value' => 'yes',
                'default'      => '',
                'description'  => !$this->is_pro_activated() ? __('Available in Pro version', 'photo-sphere-viewer') : '',
            ]
        );

        $this->end_controls_section();

        /**
         * Controls Section
         */
        $this->start_controls_section(
            '_controls_section',
            [
                'label' => __('Controls', 'photo-sphere-viewer'),
                'tab'   => Controls_Manager::TAB_CONTENT,
            ]
        );

        $this->add_control(
            'show_navbar',
            [
                'label'        => __('Show Navbar', 'photo-sphere-viewer'),
                'type'         => Controls_Manager::SWITCHER,
                'label_on'     => __('Yes', 'photo-sphere-viewer'),
                'label_off'    => __('No', 'photo-sphere-viewer'),
                'return_value' => 'yes',
                'default'      => 'yes',
            ]
        );

        $this->add_control(
            'show_zoom',
            [
                'label'        => __('Zoom Controls', 'photo-sphere-viewer'),
                'type'         => $this->is_pro_activated() ? Controls_Manager::SWITCHER : Promotion_Control::TYPE,
                'return_value' => 'yes',
                'default'      => $this->is_pro_activated() ? 'yes' : '',
                'condition'    => ['show_navbar' => 'yes'],
                'description'  => !$this->is_pro_activated() ? __('Available in Pro version', 'photo-sphere-viewer') : '',
            ]
        );

        $this->add_control(
            'show_caption',
            [
                'label'        => __('Caption', 'photo-sphere-viewer'),
                'type'         => Controls_Manager::SWITCHER,
                'return_value' => 'yes',
                'default'      => 'yes',
                'condition'    => ['show_navbar' => 'yes'],
            ]
        );

        $this->add_control(
            'show_fullscreen',
            [
                'label'        => __('Fullscreen', 'photo-sphere-viewer'),
                'type'         => $this->is_pro_activated() ? Controls_Manager::SWITCHER : Promotion_Control::TYPE,
                'return_value' => 'yes',
                'default'      => $this->is_pro_activated() ? 'yes' : '',
                'condition'    => ['show_navbar' => 'yes'],
                'description'  => !$this->is_pro_activated() ? __('Available in Pro version', 'photo-sphere-viewer') : '',
            ]
        );

        $this->add_control(
            'show_download',
            [
                'label'        => __('Download', 'photo-sphere-viewer'),
                'type'         => $this->is_pro_activated() ? Controls_Manager::SWITCHER : Promotion_Control::TYPE,
                'return_value' => 'yes',
                'default'      => '',
                'condition'    => ['show_navbar' => 'yes'],
                'description'  => !$this->is_pro_activated() ? __('Available in Pro version', 'photo-sphere-viewer') : '',
            ]
        );

        $this->end_controls_section();

        /**
         * Style Section
         */
        $this->start_controls_section(
            '_style_section',
            [
                'label' => __('Navbar', 'photo-sphere-viewer'),
                'tab'   => Controls_Manager::TAB_STYLE,
            ]
        );

        $this->add_control(
            'navbar_background',
            [
                'label'     => __('Background', 'photo-sphere-viewer'),
                'type'      => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .psv-navbar' => 'background: {{VALUE}}',
                ],
            ]
        );

        $this->add_control(
            'title_color',
            [
                'label'     => __('Caption Color', 'photo-sphere-viewer'),
                'type'      => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .psv-caption-content' => 'color: {{VALUE}}',
                ],
            ]
        );

        $this->add_group_control(
            Group_Control_Typography::get_type(),
            [
                'name'     => 'title_typography',
                'label'    => __('Typography', 'photo-sphere-viewer'),
                'selector' => '{{WRAPPER}} .psv-caption-content',
            ]
        );

        $this->end_controls_section();
    }

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

        // Resolve video URL
        $video_url = '';
        if ($settings['video_source_type'] === 'upload' && !empty($settings['video_upload']['url'])) {
            $video_url = $settings['video_upload']['url'];
        } elseif (!empty($settings['video_url']['url'])) {
            $video_url = $settings['video_url']['url'];
        }

        if (empty($video_url)) {
            echo '<div style="padding: 20px; text-align: center; color: #999;">' . esc_html__('Please provide a 360° video source.', 'photo-sphere-viewer') . '</div>';
            return;
        }

        // Build navbar — Pro features gated
        $navbar_enabled = ['videoPlay', 'videoTime'];
        if ($is_pro && isset($settings['show_zoom']) && $settings['show_zoom'] === 'yes') $navbar_enabled[] = 'zoom';
        if (isset($settings['show_caption']) && $settings['show_caption'] === 'yes') $navbar_enabled[] = 'caption';
        if ($is_pro && isset($settings['show_download']) && $settings['show_download'] === 'yes') $navbar_enabled[] = 'download';
        if ($is_pro && isset($settings['show_fullscreen']) && $settings['show_fullscreen'] === 'yes') $navbar_enabled[] = 'fullscreen';
        $navbar_enabled[] = 'videoVolume';

        $navbar_options = isset($settings['show_navbar']) && $settings['show_navbar'] === 'yes'
            ? implode(',', $navbar_enabled)
            : false;

        $id = wp_unique_id('psv-video-');

        $this->add_render_attribute('viewer', 'class', 'photo-sphere-viewer viewer');

        $data = array_filter([
            'container'        => sanitize_key($id),
            'caption'          => $settings['video_caption'] ?? '',
            'navbar'           => $navbar_options,
            'canvasBackground' => '#000',
            'isVideo'          => true,
            'videoSource'      => $video_url,
            'videoPlugin'      => [
                'autoplay' => $is_pro && isset($settings['video_autoplay']) && $settings['video_autoplay'] === 'yes',
                'muted'    => isset($settings['video_muted']) && $settings['video_muted'] === 'yes',
                'loop'     => $is_pro && isset($settings['video_loop']) && $settings['video_loop'] === 'yes',
            ],
        ]);

        $this->add_render_attribute('viewer', 'data-settings', wp_json_encode($data));

        printf(
            '<div id="%1$s" %2$s></div>',
            esc_attr($id),
            $this->get_render_attribute_string('viewer')
        );
    }
}
