<?php

namespace Unlockafe_addons\Widgets;

use Unlockafe_addons\Traits\Utils as UnlockafeUtils;
use Unlockafe_addons\Traits\Widget_helper;
use Elementor\Widget_Base;
use Elementor\Controls_Manager;
use Elementor\Group_Control_Typography;
use Elementor\Group_Control_Border;
use Elementor\Group_Control_Box_Shadow;
use Elementor\Group_Control_Background;
use Elementor\Utils;

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

/**
 * 360 Degree Photo Viewer Widget
 *
 * @since 1.0.0
 */
class Photo_Viewer_360 extends Widget_Base
{
    use Widget_helper, UnlockafeUtils;

    /**
     * Retrieve the widget name.
     */
    public function get_name()
    {
        return 'unlockafe-photo-viewer-360';
    }

    /**
     * Retrieve the widget title.
     */
    public function get_title()
    {
        return __('360° Photo Viewer', 'unlock-addons-for-elementor');
    }

    /**
     * Retrieve the widget icon.
     */
    public function get_icon()
    {
        return 'eicon-image-rollover ulicon';
    }

    /**
     * Retrieve the list of categories.
     */
    public function get_categories()
    {
        return ['unlockafe-addons'];
    }

    /**
     * Retrieve the list of keywords.
     */
    public function get_keywords()
    {
        return ['360', 'panorama', 'viewer', 'photo', 'interactive', 'vr', 'virtual'];
    }

    /**
     * Retrieve the list of scripts.
     */
    public function get_script_depends()
    {
        return ['unlockafe-photo-viewer-360-scripts'];
    }

    /**
     * Retrieve the list of styles.
     */
    public function get_style_depends()
    {
        return ['unlockafe-photo-viewer-360-style'];
    }

    /**
     * Register widget controls.
     */
    protected function register_controls()
    {
        $this->register_content_controls();
        $this->register_style_controls();
    }

    /**
     * Register content controls.
     */
    protected function register_content_controls()
    {
        // Image Section
        $this->start_controls_section(
            'image_section',
            [
                'label' => __('360° Image', 'unlock-addons-for-elementor'),
                'tab' => Controls_Manager::TAB_CONTENT,
            ]
        );

        $this->add_control(
            'viewer_image',
            [
                'label' => __('360° Panoramic Image', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::MEDIA,
                'default' => [
                    'url' => Utils::get_placeholder_image_src(),
                ],
                'description' => __('Upload a 360-degree panoramic/equirectangular image', 'unlock-addons-for-elementor'),
            ]
        );

        $this->add_control(
            'viewer_style',
            [
                'label' => __('Viewer Style', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SELECT,
                'options' => [
                    'style-1' => __('Style 1 - Standard', 'unlock-addons-for-elementor'),
                    'style-2' => __('Style 2 - Fullscreen', 'unlock-addons-for-elementor'),
                    'style-3' => __('Style 3 - Minimal', 'unlock-addons-for-elementor'),
                ],
                'default' => 'style-1',
            ]
        );

        $this->add_responsive_control(
            'viewer_width',
            [
                'label' => __('Viewer Width', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SLIDER,
                'size_units' => ['px', '%', 'vw'],
                'range' => [
                    'px' => [
                        'min' => 200,
                        'max' => 2000,
                        'step' => 10,
                    ],
                    '%' => [
                        'min' => 10,
                        'max' => 100,
                        'step' => 1,
                    ],
                    'vw' => [
                        'min' => 10,
                        'max' => 100,
                        'step' => 1,
                    ],
                ],
                'default' => [
                    'unit' => '%',
                    'size' => 100,
                ],
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-360-viewer' => 'width: {{SIZE}}{{UNIT}} !important; max-width: {{SIZE}}{{UNIT}} !important;',
                ],
            ]
        );

        $this->add_responsive_control(
            'viewer_height',
            [
                'label' => __('Viewer Height', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SLIDER,
                'size_units' => ['px', 'vh', 'em'],
                'range' => [
                    'px' => [
                        'min' => 200,
                        'max' => 1000,
                        'step' => 10,
                    ],
                    'vh' => [
                        'min' => 30,
                        'max' => 100,
                        'step' => 1,
                    ],
                    'em' => [
                        'min' => 10,
                        'max' => 50,
                        'step' => 0.1,
                    ],
                ],
                'default' => [
                    'unit' => 'px',
                    'size' => 500,
                ],
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-360-viewer' => 'height: {{SIZE}}{{UNIT}} !important;',
                ],
            ]
        );

        $this->end_controls_section();

        // Controls Section
        $this->start_controls_section(
            'controls_section',
            [
                'label' => __('Controls', 'unlock-addons-for-elementor'),
                'tab' => Controls_Manager::TAB_CONTENT,
            ]
        );

        $this->add_control(
            'show_controls',
            [
                'label' => __('Show Controls', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SWITCHER,
                'label_on' => __('Yes', 'unlock-addons-for-elementor'),
                'label_off' => __('No', 'unlock-addons-for-elementor'),
                'return_value' => 'yes',
                'default' => 'yes',
            ]
        );

        $this->add_control(
            'auto_rotate',
            [
                'label' => __('Auto Rotate', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SWITCHER,
                'label_on' => __('Yes', 'unlock-addons-for-elementor'),
                'label_off' => __('No', 'unlock-addons-for-elementor'),
                'return_value' => 'yes',
                'default' => 'no',
            ]
        );

        $this->add_control(
            'auto_rotate_speed',
            [
                'label' => __('Auto Rotate Speed', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SLIDER,
                'size_units' => ['rpm'],
                'range' => [
                    'rpm' => [
                        'min' => 0.1,
                        'max' => 5,
                        'step' => 0.1,
                    ],
                ],
                'default' => [
                    'unit' => 'rpm',
                    'size' => 1,
                ],
                'condition' => [
                    'auto_rotate' => 'yes',
                ],
            ]
        );

        $this->add_control(
            'enable_zoom',
            [
                'label' => __('Enable Zoom', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SWITCHER,
                'label_on' => __('Yes', 'unlock-addons-for-elementor'),
                'label_off' => __('No', 'unlock-addons-for-elementor'),
                'return_value' => 'yes',
                'default' => 'yes',
            ]
        );

        $this->add_control(
            'min_zoom',
            [
                'label' => __('Min Zoom', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SLIDER,
                'size_units' => [''],
                'range' => [
                    '' => [
                        'min' => 30,
                        'max' => 100,
                        'step' => 5,
                    ],
                ],
                'default' => [
                    'size' => 50,
                ],
                'condition' => [
                    'enable_zoom' => 'yes',
                ],
            ]
        );

        $this->add_control(
            'max_zoom',
            [
                'label' => __('Max Zoom', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SLIDER,
                'size_units' => [''],
                'range' => [
                    '' => [
                        'min' => 100,
                        'max' => 200,
                        'step' => 5,
                    ],
                ],
                'default' => [
                    'size' => 120,
                ],
                'condition' => [
                    'enable_zoom' => 'yes',
                ],
            ]
        );

        $this->add_control(
            'initial_zoom',
            [
                'label' => __('Initial Zoom', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SLIDER,
                'size_units' => [''],
                'range' => [
                    '' => [
                        'min' => 30,
                        'max' => 200,
                        'step' => 5,
                    ],
                ],
                'default' => [
                    'size' => 100,
                ],
                'condition' => [
                    'enable_zoom' => 'yes',
                ],
            ]
        );

        $this->end_controls_section();

        // Loading Section
        $this->start_controls_section(
            'loading_section',
            [
                'label' => __('Loading & Placeholder', 'unlock-addons-for-elementor'),
                'tab' => Controls_Manager::TAB_CONTENT,
            ]
        );

        $this->add_control(
            'loading_text',
            [
                'label' => __('Loading Text', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::TEXT,
                'default' => __('Loading 360° Viewer...', 'unlock-addons-for-elementor'),
                'placeholder' => __('Enter loading text', 'unlock-addons-for-elementor'),
            ]
        );

        $this->add_control(
            'placeholder_image',
            [
                'label' => __('Placeholder Image', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::MEDIA,
                'description' => __('Image shown while 360° image is loading', 'unlock-addons-for-elementor'),
            ]
        );

        $this->end_controls_section();
    }

    /**
     * Register style controls.
     */
    protected function register_style_controls()
    {
        // Container Style
        $this->start_controls_section(
            'container_style_section',
            [
                'label' => __('Container', 'unlock-addons-for-elementor'),
                'tab' => Controls_Manager::TAB_STYLE,
            ]
        );

        $this->add_group_control(
            Group_Control_Background::get_type(),
            [
                'name' => 'container_background',
                'label' => __('Background', 'unlock-addons-for-elementor'),
                'types' => ['classic', 'gradient'],
                'selector' => '{{WRAPPER}} .unlockafe-360-viewer',
            ]
        );

        $this->add_group_control(
            Group_Control_Border::get_type(),
            [
                'name' => 'container_border',
                'selector' => '{{WRAPPER}} .unlockafe-360-viewer',
            ]
        );

        $this->add_control(
            'container_border_radius',
            [
                'label' => __('Border Radius', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::DIMENSIONS,
                'size_units' => ['px', '%'],
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-360-viewer' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );

        $this->add_group_control(
            Group_Control_Box_Shadow::get_type(),
            [
                'name' => 'container_box_shadow',
                'selector' => '{{WRAPPER}} .unlockafe-360-viewer',
            ]
        );

        $this->end_controls_section();

        // Controls Style
        $this->start_controls_section(
            'controls_style_section',
            [
                'label' => __('Controls', 'unlock-addons-for-elementor'),
                'tab' => Controls_Manager::TAB_STYLE,
                'condition' => [
                    'show_controls' => 'yes',
                ],
            ]
        );

        $this->add_control(
            'controls_background',
            [
                'label' => __('Background Color', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'default' => 'rgba(0, 0, 0, 0.5)',
                'selectors' => [
                    '{{WRAPPER}} .viewer-controls' => 'background-color: {{VALUE}};',
                ],
            ]
        );

        $this->add_control(
            'controls_color',
            [
                'label' => __('Icon Color', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'default' => '#ffffff',
                'selectors' => [
                    '{{WRAPPER}} .viewer-controls button' => 'color: {{VALUE}};',
                ],
            ]
        );

        $this->add_control(
            'controls_size',
            [
                'label' => __('Control Size', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SLIDER,
                'size_units' => ['px'],
                'range' => [
                    'px' => [
                        'min' => 20,
                        'max' => 60,
                        'step' => 2,
                    ],
                ],
                'default' => [
                    'unit' => 'px',
                    'size' => 40,
                ],
                'selectors' => [
                    '{{WRAPPER}} .viewer-controls button' => 'width: {{SIZE}}{{UNIT}}; height: {{SIZE}}{{UNIT}}; font-size: {{SIZE}}{{UNIT}};',
                ],
            ]
        );

        $this->end_controls_section();

        // Loading Style
        $this->start_controls_section(
            'loading_style_section',
            [
                'label' => __('Loading', 'unlock-addons-for-elementor'),
                'tab' => Controls_Manager::TAB_STYLE,
            ]
        );

        $this->add_control(
            'loading_text_color',
            [
                'label' => __('Text Color', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'default' => '#ffffff',
                'selectors' => [
                    '{{WRAPPER}} .viewer-loading' => 'color: {{VALUE}};',
                ],
            ]
        );

        $this->add_group_control(
            Group_Control_Typography::get_type(),
            [
                'name' => 'loading_typography',
                'selector' => '{{WRAPPER}} .viewer-loading',
            ]
        );

        $this->end_controls_section();
    }

    /**
     * Render widget output on the frontend.
     */
    protected function render()
    {
        $settings = $this->get_settings_for_display();
        $viewer_style = $settings['viewer_style'];
        $image_url = !empty($settings['viewer_image']['url']) ? esc_url($settings['viewer_image']['url']) : '';
        $placeholder_url = !empty($settings['placeholder_image']['url']) ? esc_url($settings['placeholder_image']['url']) : '';
        $loading_text = !empty($settings['loading_text']) ? esc_html($settings['loading_text']) : __('Loading 360° Viewer...', 'unlock-addons-for-elementor');
        $show_controls = $settings['show_controls'] === 'yes';
        $auto_rotate = $settings['auto_rotate'] === 'yes';
        $auto_rotate_speed = !empty($settings['auto_rotate_speed']['size']) ? floatval($settings['auto_rotate_speed']['size']) : 1;
        $enable_zoom = $settings['enable_zoom'] === 'yes';
        $min_zoom = !empty($settings['min_zoom']['size']) ? intval($settings['min_zoom']['size']) : 50;
        $max_zoom = !empty($settings['max_zoom']['size']) ? intval($settings['max_zoom']['size']) : 120;
        $initial_zoom = !empty($settings['initial_zoom']['size']) ? intval($settings['initial_zoom']['size']) : 100;

        if (empty($image_url)) {
            echo '<div class="elementor-alert elementor-alert-warning">' . esc_html__('Please upload a 360° panoramic image.', 'unlock-addons-for-elementor') . '</div>';
            return;
        }

        $viewer_class = 'unlockafe-360-viewer';
        $viewer_class .= ' viewer-' . esc_attr($viewer_style);
        if (!$show_controls) {
            $viewer_class .= ' no-controls';
        }

        ?>
        <div class="<?php echo esc_attr($viewer_class); ?> elementor-widget-unlockafe-photo-viewer-360"
             data-image-url="<?php echo esc_attr($image_url); ?>"
             data-placeholder="<?php echo esc_attr($placeholder_url); ?>"
             data-auto-rotate="<?php echo esc_attr($auto_rotate ? 'true' : 'false'); ?>"
             data-auto-rotate-speed="<?php echo esc_attr($auto_rotate_speed); ?>"
             data-enable-zoom="<?php echo esc_attr($enable_zoom ? 'true' : 'false'); ?>"
             data-min-zoom="<?php echo esc_attr($min_zoom); ?>"
             data-max-zoom="<?php echo esc_attr($max_zoom); ?>"
             data-initial-zoom="<?php echo esc_attr($initial_zoom); ?>"
             data-show-controls="<?php echo esc_attr($show_controls ? 'true' : 'false'); ?>"
             data-widget-id="<?php echo esc_attr($this->get_id()); ?>">
            
            <div class="viewer-container">
                <?php if ($placeholder_url): ?>
                    <img src="<?php echo esc_url($placeholder_url); ?>" alt="360° Viewer Placeholder" class="viewer-placeholder">
                <?php endif; ?>
                
                <div class="viewer-loading">
                    <div class="loading-spinner"></div>
                    <p><?php echo $loading_text; ?></p>
                </div>
                
                <canvas class="viewer-canvas"></canvas>
                
                <?php if ($show_controls): ?>
                    <div class="viewer-controls">
                        <button class="viewer-btn-zoom-in" title="<?php esc_attr_e('Zoom In', 'unlock-addons-for-elementor'); ?>">
                            <i class="fas fa-plus"></i>
                        </button>
                        <button class="viewer-btn-zoom-out" title="<?php esc_attr_e('Zoom Out', 'unlock-addons-for-elementor'); ?>">
                            <i class="fas fa-minus"></i>
                        </button>
                        <button class="viewer-btn-rotate" title="<?php esc_attr_e('Toggle Auto Rotate', 'unlock-addons-for-elementor'); ?>">
                            <i class="fas fa-sync-alt"></i>
                        </button>
                        <button class="viewer-btn-fullscreen" title="<?php esc_attr_e('Fullscreen', 'unlock-addons-for-elementor'); ?>">
                            <i class="fas fa-expand"></i>
                        </button>
                    </div>
                <?php endif; ?>
            </div>
        </div>
        <script>
        (function() {
            var widgetId = '<?php echo esc_js($this->get_id()); ?>';
            var $viewer = jQuery('.elementor-element-' + widgetId + ' .unlockafe-360-viewer');
            
            if ($viewer.length === 0) {
                return;
            }

            // Force initialization in editor mode
            function forceInit() {
                if (typeof initPhotoViewer360 === 'function') {
                    var $scope = jQuery('.elementor-element-' + widgetId);
                    initPhotoViewer360($scope);
                } else if (typeof jQuery !== 'undefined') {
                    // Wait for script to load
                    var attempts = 0;
                    var maxAttempts = 20;
                    var checkInit = setInterval(function() {
                        attempts++;
                        if (typeof initPhotoViewer360 === 'function') {
                            clearInterval(checkInit);
                            var $scope = jQuery('.elementor-element-' + widgetId);
                            initPhotoViewer360($scope);
                        } else if (attempts >= maxAttempts) {
                            clearInterval(checkInit);
                        }
                    }, 100);
                }
            }

            // Initialize immediately
            if (document.readyState === 'loading') {
                document.addEventListener('DOMContentLoaded', forceInit);
            } else {
                setTimeout(forceInit, 100);
            }

            // Also try after a delay for editor mode
            if (typeof elementorFrontend !== 'undefined' && elementorFrontend.isEditMode) {
                setTimeout(forceInit, 500);
                setTimeout(forceInit, 1000);
            }
        })();
        </script>
        <?php
    }
}


