<?php

/**
 * Plugin Name: Photo Sphere Viewer
 * Plugin URI: https://wpxero.com/plugins/photo-sphere-viewer/
 * Description: Photo Sphere Viewer renders 360° panoramas shots with Photo Sphere, the new camera mode of Android 4.2 Jelly Bean and above. It also supports cube panoramas.
 * Version: 2.2.3
 * Author: WPXERO
 * Author URI: https://wpxero.com/
 * Text Domain: photo-sphere-viewer
 * License: GPL3
 * Domain Path: /languages/
 * Elementor requires at least: 3.0.0
 * Elementor tested up to: 4.0.9
 */



namespace PhotoSphereViewer;

use PhotoSphereViewer\Includes;
use Elementor;

if (!defined('ABSPATH')) {
    exit;
}



// Some pre define value for easy use const  as ;
define('PSV_VER', '2.2.3');
define('PSV__FILE__', __FILE__);
define('PSV_URL', plugins_url('/', PSV__FILE__));
define('PSV_ASSETS_URL', PSV_URL . 'assets/');
define('PSV_PATH', plugin_dir_path(PSV__FILE__));


final class PhotoSphereViewerPlugin {

    const VERSION                   = PSV_VER;
    const MINIMUM_ELEMENTOR_VERSION = '3.0.0';
    const MINIMUM_PHP_VERSION       = '7.4';

    private static $_instance = null;

    public static function instance() {

        if (is_null(self::$_instance)) {
            self::$_instance = new self();
        }

        return self::$_instance;
    }

    public function __construct() {
        add_action('plugins_loaded', [$this, 'init']);
    }

    public function init() {
        // Load shared helpers early so every render path can use them.
        require_once(dirname(__FILE__) . '/includes/ProStatus.php');
        require_once(dirname(__FILE__) . '/includes/ImageResolver.php');

        $this->init_admin_page();
        $this->setup_freemius_sdk();
        $this->init_shortcodes();
        $this->init_widget_settings();

        // load assets
        add_action('wp_enqueue_scripts', [$this, 'assets_enqueue']);
        add_action('wp_enqueue_scripts', [$this, 'register_ar_scripts']);
        add_action('elementor/widgets/register', [$this, 'init_widgets']);
        add_action('elementor/elements/categories_registered', [$this, 'register_new_category']);
        add_action('elementor/editor/after_enqueue_scripts', [$this, 'inject_elementor_promotion_control_data']);

        // Custom widget icons in the Elementor panel
        add_action('elementor/editor/after_enqueue_styles', [$this, 'enqueue_widget_icons_css']);
        add_action('elementor/preview/enqueue_styles', [$this, 'enqueue_widget_icons_css']);

        // Ensure model-viewer gets type="module" when output by WordPress
        add_filter('script_loader_tag', [$this, 'add_ar_script_module_type'], 10, 2);
    }

    public function init_admin_page() {
        require_once(dirname(__FILE__) . '/includes/Admin.php');
        new Includes\Admin();
    }

    private function setup_freemius_sdk() {
        if (! function_exists('psv_fs')) {
            // Create a helper function for easy SDK access.
            function psv_fs() {
                global $photo_sphere_viewer_fs;

                if (! isset($photo_sphere_viewer_fs)) {
                    // Activate multisite network integration.
                    if (! defined('WP_FS__PRODUCT_21893_MULTISITE')) {
                        define('WP_FS__PRODUCT_21893_MULTISITE', true);
                    }

                    // Include Freemius SDK.
                    require_once dirname(__FILE__) . '/vendor/freemius/wordpress-sdk/start.php';

                    $photo_sphere_viewer_fs = fs_dynamic_init(array(
                        'id'                  => '21893',
                        'slug'                => 'photo-sphere-viewer',
                        'premium_slug'        => 'photo-sphere-viewer-pro',
                        'type'                => 'plugin',
                        'public_key'          => 'pk_98a0a11f5f3c65e9220ac306acb0f',
                        'is_premium'          => false,
                        'is_premium_only'     => false,
                        'has_paid_plans'      => true,
                        'is_live'             => true,
                        'is_org_compliant'    => true,
                        'parallel_activation' => array(
                            'enabled'                  => true,
                            'premium_version_basename' => 'photo-sphere-viewer-pro/photo-sphere-viewer-pro.php',
                        ),
                        'menu'                => array(
                            'slug'        => 'photo-sphere-viewer',
                            'first-path'  => 'admin.php?page=photo-sphere-viewer',
                            'support'     => false,
                            'contact'     => false,
                            'pricing'     => true,
                        ),
                    ));
                }

                return $photo_sphere_viewer_fs;
            }

            // Init Freemius.
            psv_fs();
            // Signal that SDK was initiated.
            do_action('photo_sphere_viewer_fs_loaded');
        }
    }

    /**
     * !Register Categories
     */
    public function register_new_category($elements_manager) {
        $elements_manager->add_category(
            'photo-sphere-viewer',
            [
                'title' => __('Photo Sphere Viewer', 'photo-sphere-viewer'),
            ]
        );

        // Reorder categories so "Photo Sphere Viewer" appears right after "General".
        try {
            $reflection = new \ReflectionClass($elements_manager);
            if (! $reflection->hasProperty('categories')) {
                return;
            }

            $property = $reflection->getProperty('categories');
            $property->setAccessible(true);

            $categories = $property->getValue($elements_manager);
            if (! is_array($categories) || ! isset($categories['photo-sphere-viewer']) || ! isset($categories['general'])) {
                return;
            }

            $psv_category = $categories['photo-sphere-viewer'];
            unset($categories['photo-sphere-viewer']);

            $reordered = [];
            foreach ($categories as $key => $value) {
                $reordered[$key] = $value;
                if ($key === 'general') {
                    $reordered['photo-sphere-viewer'] = $psv_category;
                }
            }

            $property->setValue($elements_manager, $reordered);
        } catch (\ReflectionException $e) {
            // Fail silently — keep default ordering.
        }
    }

    /**
     * !enqueue assets
     */
    public function assets_enqueue() {
        // Include Vite assets helper
        require_once(dirname(__FILE__) . '/includes/ViteAssets.php');

        $vite = new Includes\ViteAssets(
            dirname(__FILE__),
            plugin_dir_url(__FILE__)
        );

        $vite->enqueue_assets('psv');
    }

    /**
     * Enqueue custom widget icon styles in the Elementor editor & preview.
     *
     * Provides our `.psv-widget-icon` mask-image classes used by each
     * widget's get_icon() return value.
     */
    public function enqueue_widget_icons_css() {
        wp_enqueue_style(
            'psv-widget-icons',
            plugin_dir_url(__FILE__) . 'assets/css/widget-icons.css',
            [],
            PSV_VER
        );
    }

    /**
     * Provide promotion payloads for our custom Promotion_Control IDs so
     * Elementor's native promotion modal renders correctly.
     */
    public function inject_elementor_promotion_control_data() {
        if (!wp_script_is('e-react-promotions', 'enqueued')) {
            return;
        }

        $upgrade_url = esc_url('https://wpxero.com/plugins/photo-sphere-viewer/pricing/');
        $image       = defined('ELEMENTOR_ASSETS_URL') ? esc_url(ELEMENTOR_ASSETS_URL . 'images/go-pro.svg') : '';

        $promotion_payload = [
            'show_move' => [
                'title'        => __('Navigation Move', 'photo-sphere-viewer'),
                'description'  => [__('Enable advanced move controls in navbar with Photo Sphere Viewer Pro.', 'photo-sphere-viewer')],
                'image'        => $image,
                'image_alt'    => __('Upgrade', 'photo-sphere-viewer'),
                'upgrade_text' => __('Upgrade Now', 'photo-sphere-viewer'),
                'upgrade_url'  => $upgrade_url,
            ],
            'show_description' => [
                'title'        => __('Description Panel', 'photo-sphere-viewer'),
                'description'  => [__('Unlock description panel support in navbar with Photo Sphere Viewer Pro.', 'photo-sphere-viewer')],
                'image'        => $image,
                'image_alt'    => __('Upgrade', 'photo-sphere-viewer'),
                'upgrade_text' => __('Upgrade Now', 'photo-sphere-viewer'),
                'upgrade_url'  => $upgrade_url,
            ],
            'show_zoom' => [
                'title'        => __('Zoom Controls', 'photo-sphere-viewer'),
                'description'  => [__('Unlock zoom controls for this viewer with Photo Sphere Viewer Pro.', 'photo-sphere-viewer')],
                'image'        => $image,
                'image_alt'    => __('Upgrade', 'photo-sphere-viewer'),
                'upgrade_text' => __('Upgrade Now', 'photo-sphere-viewer'),
                'upgrade_url'  => $upgrade_url,
            ],
            'show_fullscreen' => [
                'title'        => __('Fullscreen Control', 'photo-sphere-viewer'),
                'description'  => [__('Unlock fullscreen control for this viewer with Photo Sphere Viewer Pro.', 'photo-sphere-viewer')],
                'image'        => $image,
                'image_alt'    => __('Upgrade', 'photo-sphere-viewer'),
                'upgrade_text' => __('Upgrade Now', 'photo-sphere-viewer'),
                'upgrade_url'  => $upgrade_url,
            ],
            'show_autorotate' => [
                'title'        => __('Autorotate Control', 'photo-sphere-viewer'),
                'description'  => [__('Unlock autorotate control in navbar with Photo Sphere Viewer Pro.', 'photo-sphere-viewer')],
                'image'        => $image,
                'image_alt'    => __('Upgrade', 'photo-sphere-viewer'),
                'upgrade_text' => __('Upgrade Now', 'photo-sphere-viewer'),
                'upgrade_url'  => $upgrade_url,
            ],
            'show_download' => [
                'title'        => __('Download Control', 'photo-sphere-viewer'),
                'description'  => [__('Unlock download control in navbar with Photo Sphere Viewer Pro.', 'photo-sphere-viewer')],
                'image'        => $image,
                'image_alt'    => __('Upgrade', 'photo-sphere-viewer'),
                'upgrade_text' => __('Upgrade Now', 'photo-sphere-viewer'),
                'upgrade_url'  => $upgrade_url,
            ],
            'enable_compass' => [
                'title'        => __('Compass Overlay', 'photo-sphere-viewer'),
                'description'  => [__('Unlock compass overlay with Photo Sphere Viewer Pro.', 'photo-sphere-viewer')],
                'image'        => $image,
                'image_alt'    => __('Upgrade', 'photo-sphere-viewer'),
                'upgrade_text' => __('Upgrade Now', 'photo-sphere-viewer'),
                'upgrade_url'  => $upgrade_url,
            ],
            'enable_gyroscope' => [
                'title'        => __('Gyroscope', 'photo-sphere-viewer'),
                'description'  => [__('Unlock gyroscope support on mobile with Photo Sphere Viewer Pro.', 'photo-sphere-viewer')],
                'image'        => $image,
                'image_alt'    => __('Upgrade', 'photo-sphere-viewer'),
                'upgrade_text' => __('Upgrade Now', 'photo-sphere-viewer'),
                'upgrade_url'  => $upgrade_url,
            ],
            'enable_visible_range' => [
                'title'        => __('Restrict Viewing Angle', 'photo-sphere-viewer'),
                'description'  => [__('Unlock visible range limits with Photo Sphere Viewer Pro.', 'photo-sphere-viewer')],
                'image'        => $image,
                'image_alt'    => __('Upgrade', 'photo-sphere-viewer'),
                'upgrade_text' => __('Upgrade Now', 'photo-sphere-viewer'),
                'upgrade_url'  => $upgrade_url,
            ],
            // 'render_mode' => [
            //     'title'        => __('Link Render Mode', 'photo-sphere-viewer'),
            //     'description'  => [__('Unlock marker-based tour links with Photo Sphere Viewer Pro.', 'photo-sphere-viewer')],
            //     'image'        => $image,
            //     'image_alt'    => __('Upgrade', 'photo-sphere-viewer'),
            //     'upgrade_text' => __('Upgrade Now', 'photo-sphere-viewer'),
            //     'upgrade_url'  => $upgrade_url,
            // ],
            'enable_tour_gallery' => [
                'title'        => __('Tour Gallery', 'photo-sphere-viewer'),
                'description'  => [__('Unlock scene gallery navigation with Photo Sphere Viewer Pro.', 'photo-sphere-viewer')],
                'image'        => $image,
                'image_alt'    => __('Upgrade', 'photo-sphere-viewer'),
                'upgrade_text' => __('Upgrade Now', 'photo-sphere-viewer'),
                'upgrade_url'  => $upgrade_url,
            ],
            'enable_tour_compass' => [
                'title'        => __('Tour Compass', 'photo-sphere-viewer'),
                'description'  => [__('Unlock compass support in virtual tours with Photo Sphere Viewer Pro.', 'photo-sphere-viewer')],
                'image'        => $image,
                'image_alt'    => __('Upgrade', 'photo-sphere-viewer'),
                'upgrade_text' => __('Upgrade Now', 'photo-sphere-viewer'),
                'upgrade_url'  => $upgrade_url,
            ],
            'video_autoplay' => [
                'title'        => __('Video Autoplay', 'photo-sphere-viewer'),
                'description'  => [__('Unlock autoplay for 360° videos with Photo Sphere Viewer Pro.', 'photo-sphere-viewer')],
                'image'        => $image,
                'image_alt'    => __('Upgrade', 'photo-sphere-viewer'),
                'upgrade_text' => __('Upgrade Now', 'photo-sphere-viewer'),
                'upgrade_url'  => $upgrade_url,
            ],
            'video_loop' => [
                'title'        => __('Video Loop', 'photo-sphere-viewer'),
                'description'  => [__('Unlock loop playback for 360° videos with Photo Sphere Viewer Pro.', 'photo-sphere-viewer')],
                'image'        => $image,
                'image_alt'    => __('Upgrade', 'photo-sphere-viewer'),
                'upgrade_text' => __('Upgrade Now', 'photo-sphere-viewer'),
                'upgrade_url'  => $upgrade_url,
            ],
            'enable_gallery' => [
                'title'        => __('Gallery', 'photo-sphere-viewer'),
                'description'  => [__('Unlock gallery functionality with Photo Sphere Viewer Pro.', 'photo-sphere-viewer')],
                'image'        => $image,
                'image_alt'    => __('Upgrade', 'photo-sphere-viewer'),
                'upgrade_text' => __('Upgrade Now', 'photo-sphere-viewer'),
                'upgrade_url'  => $upgrade_url,
            ],
            'use_original_image' => [
                'title'        => __('Full-Resolution Original Image', 'photo-sphere-viewer'),
                'description'  => [__('Load the un-scaled original upload (e.g. DJI Matrice panoramas) instead of WordPress\'s auto-generated scaled copy. Required for true 360° detail. Unlocks with Photo Sphere Viewer Pro.', 'photo-sphere-viewer')],
                'image'        => $image,
                'image_alt'    => __('Upgrade', 'photo-sphere-viewer'),
                'upgrade_text' => __('Upgrade Now', 'photo-sphere-viewer'),
                'upgrade_url'  => $upgrade_url,
            ],
            // AR 3D Viewer Pro controls
            'ar_camera_orbit' => [
                'title'        => __('AR Camera Orbit', 'photo-sphere-viewer'),
                'description'  => [__('Set a custom initial camera angle for AR 3D models with Photo Sphere Viewer Pro.', 'photo-sphere-viewer')],
                'image'        => $image,
                'image_alt'    => __('Upgrade', 'photo-sphere-viewer'),
                'upgrade_text' => __('Upgrade Now', 'photo-sphere-viewer'),
                'upgrade_url'  => $upgrade_url,
            ],
            'ar_disable_zoom' => [
                'title'        => __('AR Disable Zoom', 'photo-sphere-viewer'),
                'description'  => [__('Prevent users from zooming in 3D models with Photo Sphere Viewer Pro.', 'photo-sphere-viewer')],
                'image'        => $image,
                'image_alt'    => __('Upgrade', 'photo-sphere-viewer'),
                'upgrade_text' => __('Upgrade Now', 'photo-sphere-viewer'),
                'upgrade_url'  => $upgrade_url,
            ],
            'ar_disable_tap' => [
                'title'        => __('AR Disable Tap to Rotate', 'photo-sphere-viewer'),
                'description'  => [__('Disable tap-to-rotate gesture on 3D models with Photo Sphere Viewer Pro.', 'photo-sphere-viewer')],
                'image'        => $image,
                'image_alt'    => __('Upgrade', 'photo-sphere-viewer'),
                'upgrade_text' => __('Upgrade Now', 'photo-sphere-viewer'),
                'upgrade_url'  => $upgrade_url,
            ],
            'ar_env_source_type' => [
                'title'        => __('AR Environment Image', 'photo-sphere-viewer'),
                'description'  => [__('Add HDR environment image for realistic 3D model lighting with Photo Sphere Viewer Pro.', 'photo-sphere-viewer')],
                'image'        => $image,
                'image_alt'    => __('Upgrade', 'photo-sphere-viewer'),
                'upgrade_text' => __('Upgrade Now', 'photo-sphere-viewer'),
                'upgrade_url'  => $upgrade_url,
            ],
            'ar_skybox_source_type' => [
                'title'        => __('AR Skybox Image', 'photo-sphere-viewer'),
                'description'  => [__('Set a custom skybox background for 3D model scenes with Photo Sphere Viewer Pro.', 'photo-sphere-viewer')],
                'image'        => $image,
                'image_alt'    => __('Upgrade', 'photo-sphere-viewer'),
                'upgrade_text' => __('Upgrade Now', 'photo-sphere-viewer'),
                'upgrade_url'  => $upgrade_url,
            ],
        ];

        $inline = 'window.elementorPromotionsData = window.elementorPromotionsData || {};'
            . 'Object.assign(window.elementorPromotionsData, ' . wp_json_encode($promotion_payload) . ');';

        wp_add_inline_script('e-react-promotions', $inline, 'after');
    }

    /**
     * Initialize shortcodes
     */
    public function init_shortcodes() {
        require_once(dirname(__FILE__) . '/includes/Shortcode.php');
        require_once(dirname(__FILE__) . '/includes/ShortcodeManager.php');
        new Includes\PhotoSphereViewerShortcode();
        new Includes\ShortcodeManager();
    }

    /**
     * Initialize widget enable/disable settings manager.
     *
     * Registers AJAX endpoints consumed by the admin React UI so users can
     * toggle individual Elementor widgets on or off from the dashboard.
     */
    public function init_widget_settings() {
        require_once(dirname(__FILE__) . '/includes/WidgetSettings.php');
        new Includes\WidgetSettings();
    }

    /**
     * Register the model-viewer script for the AR 3D Viewer feature.
     * Uses the Google CDN to avoid bundling a large binary into the plugin.
     * Skips registration if another plugin (e.g. AR Viewer) has already done it.
     */
    public function register_ar_scripts() {
        if (!wp_script_is('psv-ar-model-viewer', 'registered')) {
            wp_register_script(
                'psv-ar-model-viewer',
                'https://ajax.googleapis.com/ajax/libs/model-viewer/3.4.0/model-viewer.min.js',
                [],
                '3.4.0',
                true
            );
        }
    }

    /**
     * Add type="module" to the model-viewer script tag so the ES module
     * web component loads correctly in all modern browsers.
     */
    public function add_ar_script_module_type($tag, $handle) {
        if ('psv-ar-model-viewer' === $handle) {
            $tag = str_replace('<script ', '<script type="module" ', $tag);
        }
        return $tag;
    }

    /**
     * ! Widgets Init
     */
    public function init_widgets($widgets_manager) {
        require_once(dirname(__FILE__) . '/includes/Widget.php');
        require_once(dirname(__FILE__) . '/includes/VirtualTourWidget.php');
        require_once(dirname(__FILE__) . '/includes/VideoWidget.php');
        require_once(dirname(__FILE__) . '/includes/ARViewerWidget.php');

        // Register each widget only if the user hasn't disabled it in the dashboard.
        if (Includes\WidgetSettings::is_widget_enabled('photo-sphere-viewer')) {
            $widgets_manager->register(new Includes\Photo_Sphere_Viewer());
        }
        if (Includes\WidgetSettings::is_widget_enabled('psv-virtual-tour')) {
            $widgets_manager->register(new Includes\Virtual_Tour_Viewer());
        }
        if (Includes\WidgetSettings::is_widget_enabled('psv-video-360')) {
            $widgets_manager->register(new Includes\Video_360_Viewer());
        }
        if (Includes\WidgetSettings::is_widget_enabled('psv-ar-3d-viewer')) {
            $widgets_manager->register(new Includes\AR_3D_Viewer());
        }
    }

    public function xero_photo_sphere_viewer_activate() {
        // Activation code here
    }
    public function xero_photo_sphere_viewer_deactivate() {
        // Deactivation code here

    }
}


PhotoSphereViewerPlugin::instance();
// Include the SDK
// activate and deactivate
register_activation_hook(__FILE__, array(PhotoSphereViewerPlugin::instance(), 'xero_photo_sphere_viewer_activate'));
register_deactivation_hook(__FILE__, array(PhotoSphereViewerPlugin::instance(), 'xero_photo_sphere_viewer_deactivate'));
