<?php
/**
 * Plugin Name: ExploreXR Premium
 * Plugin URI: https://expoxr.com/explorexr/
 * Description: Premium 3D model viewer for WordPress with advanced features, licensing, and addon support
 * Version: 1.1.2
 * Author: Ayal Othman
 * Author URI: https://expoxr.com
 * Text Domain: explorexr-premium
 * Domain Path: /languages
 * Requires at least: 5.8
 * Requires PHP: 7.4
 * License: GPL v2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 */

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

// Define plugin constants
define('EXPLOREXR_PREMIUM_VERSION', '1.1.2');
define('EXPLOREXR_PREMIUM_PLUGIN_FILE', __FILE__);
define('EXPLOREXR_PREMIUM_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('EXPLOREXR_PREMIUM_PLUGIN_URL', plugin_dir_url(__FILE__));
define('EXPLOREXR_PREMIUM_PLUGIN_BASENAME', plugin_basename(__FILE__));

// Define models directory
if (!defined('EXPLOREXR_MODELS_DIR')) {
    // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Local variable, not global
    $upload_dir = wp_upload_dir();
    define('EXPLOREXR_MODELS_DIR', $upload_dir['basedir'] . '/explorexr-models/');
}

// Define models URL
if (!defined('EXPLOREXR_MODELS_URL')) {
    // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Local variable, not global
    $upload_dir = wp_upload_dir();
    define('EXPLOREXR_MODELS_URL', $upload_dir['baseurl'] . '/explorexr-models/');
}

// Backward compatibility constants (many addons/integrations expect these)
if (!defined('EXPLOREXR_PLUGIN_DIR')) {
    define('EXPLOREXR_PLUGIN_DIR', EXPLOREXR_PREMIUM_PLUGIN_DIR);
}
if (!defined('EXPLOREXR_PLUGIN_URL')) {
    define('EXPLOREXR_PLUGIN_URL', EXPLOREXR_PREMIUM_PLUGIN_URL);
}
if (!defined('EXPLOREXR_VERSION')) {
    define('EXPLOREXR_VERSION', EXPLOREXR_PREMIUM_VERSION);
}

// Premium flag - used throughout codebase to check if premium features should be available
if (!defined('EXPLOREXR_IS_PREMIUM')) {
    define('EXPLOREXR_IS_PREMIUM', true);
}
if (!defined('EXPLOREXR_IS_FREE')) {
    define('EXPLOREXR_IS_FREE', false);
}

/**
 * Check if free version is active and deactivate it to prevent conflicts
 */
function explorexr_premium_check_free_version() {
    if (defined('EXPLOREXR_IS_FREE') && EXPLOREXR_IS_FREE === true) {
        // Free version is loaded, deactivate it
        if (is_admin() && current_user_can('activate_plugins')) {
            add_action('admin_notices', function() {
                ?>
                <div class="notice notice-warning is-dismissible">
                    <p><?php esc_html_e('ExploreXR Premium is now active. The free version has been deactivated to prevent conflicts.', 'explorexr-premium'); ?></p>
                </div>
                <?php
            });
            
            // Deactivate free version
            deactivate_plugins('explorexr/explorexr.php');
        }
    }
}
add_action('plugins_loaded', 'explorexr_premium_check_free_version', 1);

/**
 * Migrate CDN option to local for WordPress.org compliance
 * Runs only once in admin to avoid DB writes during render
 */
function explorexr_premium_migrate_cdn_option() {
    if (get_option('explorexr_cdn_source') === 'cdn') {
        update_option('explorexr_cdn_source', 'local');
        add_settings_error(
            'explorexr_settings',
            'cdn_disabled',
            __('CDN mode has been automatically disabled for WordPress.org compliance. All scripts are now loaded locally.', 'explorexr-premium'),
            'warning'
        );
    }
}
add_action('admin_init', 'explorexr_premium_migrate_cdn_option', 1);

/**
 * Register assets for page builders (Elementor, Beaver Builder, Divi)
 * Ensures scripts are available in builder preview contexts
 */
function explorexr_premium_register_frontend_assets() {
    // Register model loader if not already registered
    if (!wp_script_is('explorexr-model-loader', 'registered')) {
        wp_register_script(
            'explorexr-model-loader',
            EXPLOREXR_PLUGIN_URL . 'assets/js/model-loader.js',
            array('jquery'),
            EXPLOREXR_VERSION,
            true
        );
    }
    
    // Register model viewer styles if not already registered
    if (!wp_style_is('explorexr-model-viewer', 'registered')) {
        wp_register_style(
            'explorexr-model-viewer',
            EXPLOREXR_PLUGIN_URL . 'assets/css/model-viewer.css',
            array(),
            EXPLOREXR_VERSION
        );
    }
}

// Hook into page builder contexts
add_action('wp_enqueue_scripts', 'explorexr_premium_register_frontend_assets', 5); // Early registration
add_action('elementor/frontend/after_register_scripts', 'explorexr_premium_register_frontend_assets');
add_action('elementor/frontend/after_register_styles', 'explorexr_premium_register_frontend_assets');
add_action('fl_builder_before_render_shortcodes', 'explorexr_premium_register_frontend_assets'); // Beaver Builder
add_action('et_builder_ready', 'explorexr_premium_register_frontend_assets'); // Divi

/**
 * Main plugin initialization
 */
function explorexr_premium_init() {
    // Load text domain for translations
    // Note: WordPress.org automatically handles translations for plugins.
    // This is kept for backward compatibility with non-WordPress.org installations.
    // load_plugin_textdomain('explorexr-premium', false, dirname(EXPLOREXR_PREMIUM_PLUGIN_BASENAME) . '/languages');
    
    // Load helper functions first - addons depend on these
    if (file_exists(EXPLOREXR_PREMIUM_PLUGIN_DIR . 'includes/core/helper-functions.php')) {
        require_once EXPLOREXR_PREMIUM_PLUGIN_DIR . 'includes/core/helper-functions.php';
    }
        
    // Core functionality (from free version)
    require_once EXPLOREXR_PREMIUM_PLUGIN_DIR . 'includes/core/post-types.php';
    require_once EXPLOREXR_PREMIUM_PLUGIN_DIR . 'includes/core/shortcodes.php';
    require_once EXPLOREXR_PREMIUM_PLUGIN_DIR . 'includes/core/model-validator.php';
    
    // Model handling
    if (file_exists(EXPLOREXR_PREMIUM_PLUGIN_DIR . 'includes/models/file-handler.php')) {
        require_once EXPLOREXR_PREMIUM_PLUGIN_DIR . 'includes/models/file-handler.php';
    }
    if (file_exists(EXPLOREXR_PREMIUM_PLUGIN_DIR . 'includes/models/model-handler.php')) {
        require_once EXPLOREXR_PREMIUM_PLUGIN_DIR . 'includes/models/model-handler.php';
    }
    if (file_exists(EXPLOREXR_PREMIUM_PLUGIN_DIR . 'includes/models/model-uploader.php')) {
        require_once EXPLOREXR_PREMIUM_PLUGIN_DIR . 'includes/models/model-uploader.php';
    }
    if (file_exists(EXPLOREXR_PREMIUM_PLUGIN_DIR . 'includes/models/model-helper.php')) {
        require_once EXPLOREXR_PREMIUM_PLUGIN_DIR . 'includes/models/model-helper.php';
    }
    
    // UI components
    if (file_exists(EXPLOREXR_PREMIUM_PLUGIN_DIR . 'includes/ui/notifications.php')) {
        require_once EXPLOREXR_PREMIUM_PLUGIN_DIR . 'includes/ui/notifications.php';
    }
    if (file_exists(EXPLOREXR_PREMIUM_PLUGIN_DIR . 'includes/ui/model-viewer-renderer.php')) {
        require_once EXPLOREXR_PREMIUM_PLUGIN_DIR . 'includes/ui/model-viewer-renderer.php';
    }
    
    // Utilities
    if (file_exists(EXPLOREXR_PREMIUM_PLUGIN_DIR . 'includes/utils/file-utils.php')) {
        require_once EXPLOREXR_PREMIUM_PLUGIN_DIR . 'includes/utils/file-utils.php';
    }
    if (file_exists(EXPLOREXR_PREMIUM_PLUGIN_DIR . 'includes/utils/security-utils.php')) {
        require_once EXPLOREXR_PREMIUM_PLUGIN_DIR . 'includes/utils/security-utils.php';
    }
    
    // Security - file upload sanitizer
    if (file_exists(EXPLOREXR_PREMIUM_PLUGIN_DIR . 'includes/security/security-handler.php')) {
        require_once EXPLOREXR_PREMIUM_PLUGIN_DIR . 'includes/security/security-handler.php';
    }
    if (file_exists(EXPLOREXR_PREMIUM_PLUGIN_DIR . 'includes/security/file-upload-sanitizer.php')) {
        require_once EXPLOREXR_PREMIUM_PLUGIN_DIR . 'includes/security/file-upload-sanitizer.php';
    }
    
    // Admin functionality
    if (is_admin()) {
        // Admin notices manager - Load early for centralized notice system
        require_once EXPLOREXR_PREMIUM_PLUGIN_DIR . 'includes/admin/class-admin-notices.php';
        
        // Core admin
        require_once EXPLOREXR_PREMIUM_PLUGIN_DIR . 'admin/core/admin-menu.php';
        require_once EXPLOREXR_PREMIUM_PLUGIN_DIR . 'admin/core/admin-pages.php';
        require_once EXPLOREXR_PREMIUM_PLUGIN_DIR . 'admin/core/admin-ui.php';
        
        if (file_exists(EXPLOREXR_PREMIUM_PLUGIN_DIR . 'admin/core/edit-redirector.php')) {
            require_once EXPLOREXR_PREMIUM_PLUGIN_DIR . 'admin/core/edit-redirector.php';
        }
        if (file_exists(EXPLOREXR_PREMIUM_PLUGIN_DIR . 'admin/core/functions.php')) {
            require_once EXPLOREXR_PREMIUM_PLUGIN_DIR . 'admin/core/functions.php';
        }
        
        // Settings
        if (file_exists(EXPLOREXR_PREMIUM_PLUGIN_DIR . 'admin/settings/settings-callbacks.php')) {
            require_once EXPLOREXR_PREMIUM_PLUGIN_DIR . 'admin/settings/settings-callbacks.php';
        }
        if (file_exists(EXPLOREXR_PREMIUM_PLUGIN_DIR . 'admin/settings/import-export.php')) {
            require_once EXPLOREXR_PREMIUM_PLUGIN_DIR . 'admin/settings/import-export.php';
        }
        if (file_exists(EXPLOREXR_PREMIUM_PLUGIN_DIR . 'admin/settings/loading-options.php')) {
            require_once EXPLOREXR_PREMIUM_PLUGIN_DIR . 'admin/settings/loading-options.php';
        }
        
        // AJAX handlers
        if (file_exists(EXPLOREXR_PREMIUM_PLUGIN_DIR . 'admin/ajax/ajax-handlers.php')) {
            require_once EXPLOREXR_PREMIUM_PLUGIN_DIR . 'admin/ajax/ajax-handlers.php';
        }
        if (file_exists(EXPLOREXR_PREMIUM_PLUGIN_DIR . 'admin/ajax/render-model-ajax.php')) {
            require_once EXPLOREXR_PREMIUM_PLUGIN_DIR . 'admin/ajax/render-model-ajax.php';
        }
    }
    
    // Premium features - Licensing System (load integration before handler)
    if (file_exists(EXPLOREXR_PREMIUM_PLUGIN_DIR . 'includes/security/licensing/license-config.php')) {
        require_once EXPLOREXR_PREMIUM_PLUGIN_DIR . 'includes/security/licensing/license-config.php';
    }
    if (file_exists(EXPLOREXR_PREMIUM_PLUGIN_DIR . 'includes/security/licensing/license-integration.php')) {
        require_once EXPLOREXR_PREMIUM_PLUGIN_DIR . 'includes/security/licensing/license-integration.php';
    }
    if (file_exists(EXPLOREXR_PREMIUM_PLUGIN_DIR . 'includes/security/licensing/license-handler.php')) {
        require_once EXPLOREXR_PREMIUM_PLUGIN_DIR . 'includes/security/licensing/license-handler.php';
    }
    if (file_exists(EXPLOREXR_PREMIUM_PLUGIN_DIR . 'includes/security/licensing/license-expiration-handler.php')) {
        require_once EXPLOREXR_PREMIUM_PLUGIN_DIR . 'includes/security/licensing/license-expiration-handler.php';
    }
    
    // Premium features - Addon System
    if (file_exists(EXPLOREXR_PREMIUM_PLUGIN_DIR . 'includes/addons/addon-cleanup.php')) {
        require_once EXPLOREXR_PREMIUM_PLUGIN_DIR . 'includes/addons/addon-cleanup.php';
    }
    if (file_exists(EXPLOREXR_PREMIUM_PLUGIN_DIR . 'includes/addons/addon-manager.php')) {
        require_once EXPLOREXR_PREMIUM_PLUGIN_DIR . 'includes/addons/addon-manager.php';
    }
    
    // Initialize premium license system
    if (class_exists('ExploreXR_License_Handler')) {
        ExploreXR_License_Handler::instance();
    }
    
    // Initialize addon manager
    if (class_exists('ExploreXR_Addon_Manager')) {
        $addon_manager = ExploreXR_Addon_Manager::get_instance();
        $addon_manager->init();
    }

    // Page builder integrations (Elementor, Divi, Beaver Builder, WPBakery/Avada, Gutenberg)
    if (file_exists(EXPLOREXR_PREMIUM_PLUGIN_DIR . 'includes/integrations/class-page-builder-loader.php')) {
        require_once EXPLOREXR_PREMIUM_PLUGIN_DIR . 'includes/integrations/class-page-builder-loader.php';
        ExploreXR_Page_Builder_Loader::init();
    }
}
add_action('plugins_loaded', 'explorexr_premium_init', 5); // Priority 5 to load helper functions before addons check license (default priority 10)

/**
 * Initialize automatic updates
 * 
 * Loads the update checker to enable automatic updates from update.expoxr.com
 */
function explorexr_premium_init_updater() {
    // Only run in admin
    if (!is_admin()) {
        return;
    }
    
    // Load updater class
    if (file_exists(EXPLOREXR_PREMIUM_PLUGIN_DIR . 'includes/updates/class-explorexr-updater.php')) {
        require_once EXPLOREXR_PREMIUM_PLUGIN_DIR . 'includes/updates/class-explorexr-updater.php';
        
        // Initialize updater
        new ExploreXR_Updater(
            __FILE__,
            'https://update.expoxr.com/explorexr/premium/main/explorexr-premium.json',
            'explorexr-premium'
        );
    }
}
add_action('plugins_loaded', 'explorexr_premium_init_updater', 20);

/**
 * Enqueue frontend scripts and styles
 */
function explorexr_premium_enqueue_scripts() {
    // Note: Model Viewer script is loaded via template-parts/model-viewer-script.php
    // This is done through shortcodes to ensure proper configuration and prevent duplicates
    
    // Frontend styles
    if (file_exists(EXPLOREXR_PREMIUM_PLUGIN_DIR . 'assets/css/frontend.css')) {
        wp_enqueue_style(
            'explorexr-frontend',
            EXPLOREXR_PREMIUM_PLUGIN_URL . 'assets/css/frontend.css',
            array(),
            EXPLOREXR_PREMIUM_VERSION
        );
    }
    
    // Frontend JavaScript
    if (file_exists(EXPLOREXR_PREMIUM_PLUGIN_DIR . 'assets/js/frontend.js')) {
        wp_enqueue_script(
            'explorexr-frontend',
            EXPLOREXR_PREMIUM_PLUGIN_URL . 'assets/js/frontend.js',
            array('jquery'),
            EXPLOREXR_PREMIUM_VERSION,
            true
        );
    }
}
add_action('wp_enqueue_scripts', 'explorexr_premium_enqueue_scripts');

/**
 * Enqueue admin scripts and styles
 */
function explorexr_premium_admin_enqueue_scripts($hook) {
    // Define ExploreXR admin pages
    $explorexr_pages = array(
        'explorexr_page_explorexr-settings',
        'explorexr_page_explorexr-addons',
        'explorexr_page_explorexr-license',
        'explorexr-premium_page_explorexr-edit-model',
        'explorexr-premium_page_explorexr-create-model',
        'explorexr-premium_page_explorexr-browse-models',
        'toplevel_page_explorexr-premium',
        'admin_page_explorexr-edit-model'
    );
    
    // Check if we're on an ExploreXR page or editing a 3D model
    $is_explorexr_page = in_array($hook, $explorexr_pages, true);
    
    // Check if editing a 3D model post type
    global $post_type;
    $is_model_edit = ($post_type === 'explorexr_model' || $post_type === 'explorexr_premium_model');
    
    // Check if on edit-model page by URL parameter
    $page = isset($_GET['page']) ? sanitize_key(wp_unslash($_GET['page'])) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Page parameter for admin UI only
    $is_edit_model_page = ($page === 'explorexr-edit-model');    
    if ($is_explorexr_page || $is_model_edit || $is_edit_model_page) {
        // Note: model-viewer script is loaded via template-parts/model-viewer-script.php
        // to avoid duplicate loading and ensure proper configuration
        
        // Admin styles
        wp_enqueue_style(
            'explorexr-admin',
            EXPLOREXR_PREMIUM_PLUGIN_URL . 'admin/css/admin-ui.css',
            array(),
            EXPLOREXR_PREMIUM_VERSION
        );
        
        // Admin JavaScript
        wp_enqueue_script(
            'explorexr-admin',
            EXPLOREXR_PREMIUM_PLUGIN_URL . 'admin/js/admin-ui.js',
            array('jquery'),
            EXPLOREXR_PREMIUM_VERSION,
            true
        );
        
        // Localize script with admin data
        wp_localize_script('explorexr-admin', 'explorexrAdmin', array(
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('explorexr_admin_nonce'),
            'isPremium' => true,
            'version' => EXPLOREXR_PREMIUM_VERSION
        ));
        
        // Add ExploreXRAdminVars for backward compatibility
        wp_localize_script('explorexr-admin', 'ExploreXRAdminVars', array(
            'pluginUrl' => EXPLOREXR_PREMIUM_PLUGIN_URL,
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('explorexr_admin_nonce')
        ));
    }
}
add_action('admin_enqueue_scripts', 'explorexr_premium_admin_enqueue_scripts');

/**
 * Plugin activation
 */
function explorexr_premium_activate() {
    // Create custom post type
    if (function_exists('explorexr_register_post_types')) {
        explorexr_register_post_types();
    }
    
    // Flush rewrite rules
    flush_rewrite_rules();
    
    // Set default options
    if (!get_option('explorexr_premium_version')) {
        update_option('explorexr_premium_version', EXPLOREXR_PREMIUM_VERSION);
    }
    
    // Initialize license check
    if (class_exists('ExploreXR_License_Handler')) {
        ExploreXR_License_Handler::init();
    }
}
register_activation_hook(__FILE__, 'explorexr_premium_activate');

/**
 * Plugin deactivation
 */
function explorexr_premium_deactivate() {
    // Flush rewrite rules
    flush_rewrite_rules();
}
register_deactivation_hook(__FILE__, 'explorexr_premium_deactivate');
