<?php
/**
 * Plugin Name: Turbo Templates Kit for Elementor
 * Description: Professional template import system with 300+ templates and AI builder - works with any theme
 * Version: 1.1.0
 * Author: Turbo Addons
 * Author URI: https://turbo-addons.com/
 * Text Domain: turbo-templates-library-for-elementor
 * Domain Path: /languages
 * Requires at least: 5.0
 * Requires Plugins: elementor
 * Tested up to: 7.0
 * Requires PHP: 7.4
 * Elementor tested up to: 4.1.3
 * Elementor Pro tested up to: 4.1.3
 * License: GPL v2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 */

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

// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedFunctionFound, WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound, WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Freemius SDK boilerplate, names are required by the SDK
if ( ! function_exists( 'ttlfe_fs' ) ) {
    // Create a helper function for easy SDK access.
    function ttlfe_fs() {
        global $ttlfe_fs;

        if ( ! isset( $ttlfe_fs ) ) {
            // Include Freemius SDK.
            require_once dirname( __FILE__ ) . '/vendor/freemius/start.php';

            $ttlfe_fs = fs_dynamic_init( array(
                'id'                  => '22920',
                'slug'                => 'turbo-templates-library-for-elementor',
                'type'                => 'plugin',
                'public_key'          => 'pk_21989df60b92b7a2f94184c98286d',
                'is_premium'          => false,
                'has_addons'          => false,
                'has_paid_plans'      => false,
                'menu'                => array(
                    'slug'           => 'turbo-starter-templates',
                    'first-path'     => 'admin.php?page=turbo-starter-templates',
                    'account'        => false,
                    'contact'        => false,
                    'support'        => false,
                ),
            ) );
        }

        return $ttlfe_fs;
    }

    // Init Freemius.
    ttlfe_fs();
    // Signal that SDK was initiated.
    do_action( 'ttlfe_fs_loaded' );
}
// phpcs:enable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedFunctionFound, WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound, WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound

// Security: Define plugin constants with prefix
define('TRSTEMP_VERSION', '1.1.0');
define('TRSTEMP_URI', plugin_dir_url(__FILE__));
define('TRSTEMP_DIR', plugin_dir_path(__FILE__));
define('TRSTEMP_NONCE_ACTION', 'trstemp_nonce_action');

// Backward compatibility constants
define('TRSTEMP_STARTER_VERSION', '1.1.0');
define('TRSTEMP_STARTER_URI', plugin_dir_url(__FILE__));
define('TRSTEMP_STARTER_DIR', plugin_dir_path(__FILE__));
define('TRSTEMP_ST_VERSION', '1.1.0');
define('TRSTEMP_ST_URL', plugin_dir_url(__FILE__));

class Trstemp_Starter_Templates {
    
    public function __construct() {

        // Load dependency helper
        require_once TRSTEMP_DIR . 'includes/class-trstemp-dependencies.php';

        // Load global helper functions (IMPORTANT)
        require_once TRSTEMP_DIR . 'includes/helper.php';

        // Show notice if missing (only in dashboard, don't prevent activation)
        add_action( 'admin_notices', [ 'Trstemp_Dependencies', 'admin_notice' ] );
        // add_action( 'admin_notices', [ $this, 'admin_notice' ] );

        // Always continue loading - don't stop for missing dependencies

        // Normal boot
        $this->trstemp_load_classes();
        add_action( 'init', array( $this, 'init' ) );
        register_activation_hook( __FILE__, array( $this, 'activation' ) );
    }

    
    private function trstemp_load_classes() {
        // Load core files
        $files_to_load = array(
            'template-importer.php',
            'activate-plugins.php'
        );
        
        foreach ($files_to_load as $file) {
            $file_path = TRSTEMP_DIR . $file;
            if (file_exists($file_path) && is_readable($file_path)) {
                require_once $file_path;
            }
        }
        
        // Load security classes first
        $security_files = array(
            'includes/Security.php',
            'includes/Migration.php'
        );
        
        foreach ($security_files as $file) {
            $file_path = TRSTEMP_DIR . $file;
            if (file_exists($file_path) && is_readable($file_path)) {
                require_once $file_path;
            }
        }
        
        // Load optional includes with security checks
        $optional_includes = array(
            'includes/WizardSession.php',
            'includes/PreviewListener.php'
        );
        
        foreach ($optional_includes as $include) {
            $include_path = TRSTEMP_DIR . $include;
            if (file_exists($include_path) && is_readable($include_path)) {
                require_once $include_path;
                if ($include === 'includes/PreviewListener.php' && class_exists('\Turbo\StarterTemplates\Trstemp_PreviewListener')) {
                    new \Turbo\StarterTemplates\Trstemp_PreviewListener();
                }
            }
        }
        
        // Load dashboard module
        $dashboard_file = TRSTEMP_DIR . 'dashboard/class-trstemp-dashboard.php';
        if (file_exists($dashboard_file) && is_readable($dashboard_file)) {
            require_once $dashboard_file;
        }
    }
    
    public function init() {
        // Text domain is automatically loaded by WordPress 4.6+
        
        // Security: Only load admin functionality for admin users
        if (is_admin()) {
            add_action('admin_menu', array($this, 'admin_menu'));
            add_action('admin_init', array($this, 'redirect_after_activation'));
            add_action('admin_enqueue_scripts', array($this, 'trstemp_enqueue_admin_assets'));
            
            // Initialize dashboard
            if (class_exists('Trstemp_Dashboard')) {
                new Trstemp_Dashboard();
            }
        }
        
        add_action('wp_enqueue_scripts', array($this, 'enqueue_custom_css'));
        add_action('wp_enqueue_scripts', array($this, 'enqueue_inline_scripts'));
        
        // AJAX actions with security checks
        add_action('wp_ajax_trstemp_import_template', array($this, 'trstemp_ajax_import_template'));
        add_action('wp_ajax_trstemp_dismiss_notice', array($this, 'trstemp_dismiss_notice'));
        add_action('wp_ajax_trstemp_activate_plugin', array($this, 'trstemp_ajax_activate_plugin'));
        // add_action('wp_ajax_trstemp_proxy_demo', array($this, 'trstemp_proxy_demo_url'));
        // add_action('wp_ajax_nopriv_trstemp_proxy_demo', array($this, 'trstemp_proxy_demo_url'));
        // License AJAX actions removed - all features are now free
        
        // Backward compatibility for existing AJAX calls
        // add_action('wp_ajax_trstemp_import_template', array($this, 'trstemp_ajax_import_template'));
        // add_action('wp_ajax_trstemp_dismiss_notice', array($this, 'trstemp_dismiss_notice'));
        // add_action('wp_ajax_trstemp_activate_plugin', array($this, 'trstemp_ajax_activate_plugin'));
        add_action( 'wp_ajax_trstemp_admin_proxy_demo', array( $this, 'trstemp_proxy_demo_url' ) );


        
        // Debug actions
        add_action('wp_ajax_trstemp_debug_import', array($this, 'trstemp_debug_import'));
        add_action('wp_ajax_trstemp_debug_pages', array($this, 'trstemp_debug_pages'));
        add_action('wp_ajax_trstemp_check_homepage_status', array($this, 'trstemp_check_homepage_status'));
        add_action('wp_ajax_trstemp_fix_homepage_display', array($this, 'trstemp_fix_homepage_display'));
        
        // Debug wizard session
        add_action('wp_ajax_trstemp_debug_wizard_session', array($this, 'trstemp_debug_wizard_session'));
        
        // Step data and preview AJAX actions
        add_action('wp_ajax_trstemp_save_step_data', array($this, 'trstemp_save_step_data'));
        add_action('wp_ajax_trstemp_get_step_data', array($this, 'trstemp_get_step_data'));
        add_action('wp_ajax_trstemp_get_preview_url', array($this, 'trstemp_get_preview_url'));
        add_action('wp_ajax_trstemp_get_wizard_summary', array($this, 'trstemp_get_wizard_summary'));
    }
    
    public function redirect_after_activation() {
        if (get_transient('trstemp_activation_redirect')) {
            delete_transient('trstemp_activation_redirect');
            wp_safe_redirect(admin_url('admin.php?page=turbo-starter-templates'));
            exit;
        }
        
        if (get_transient('trstemp_starter_redirect')) {
            delete_transient('trstemp_starter_redirect');
            wp_safe_redirect(admin_url('admin.php?page=turbo-starter-templates'));
            exit;
        }
    }
    
    public function activation() {
        set_transient('trstemp_activation_redirect', 'wizard', 30);
    }
    
    public function install_and_activate_plugin($slug, $file) {
        // This method is deprecated and no longer automatically activates plugins
        // Users must manually install and activate plugins
        return false;
    }
    
    public function admin_menu() {
        // Add main menu page
        add_menu_page(
            'Turbo Templates Library',
            'Turbo Templates',
            'manage_options',
            'turbo-starter-templates',
            array($this, 'main_page'),
            'dashicons-layout',
            22
        );
        
        // Add submenu pages
        add_submenu_page(
            'turbo-starter-templates',
            'Dashboard',
            'Dashboard',
            'manage_options',
            'turbo-starter-templates',
            array($this, 'main_page')
        );
        
        // License and pricing pages removed - all features are now free
    }
    

    

    
    public function main_page() {
        // phpcs:disable WordPress.Security.NonceVerification.Recommended -- Read-only GET parameter for page display
        // Security: Sanitize GET parameter
        $ci = isset($_GET['ci']) ? absint(wp_unslash($_GET['ci'])) : null;
        // phpcs:enable WordPress.Security.NonceVerification.Recommended
        
        // Show wizard if ci parameter is set, otherwise show dashboard
        if ($ci !== null) {
            // Enqueue wizard assets
            wp_enqueue_media();
            wp_enqueue_style('trstemp-plugin-wizard', esc_url(TRSTEMP_STARTER_URI . 'assets/wizard.css'), array(), TRSTEMP_STARTER_VERSION);
            wp_enqueue_script('trstemp-plugin-wizard', esc_url(TRSTEMP_STARTER_URI . 'assets/wizard.js'), array('jquery'), TRSTEMP_STARTER_VERSION, true);
            
            /**
             * ---------------------------------------------------------
             * STEP 0: Welcome Screen assets
             * Used in: steps/step-0.php
             * ---------------------------------------------------------
             */
            if ( $ci == 0 ) {

                // Load Step 0 CSS
                wp_enqueue_style(
                    'trstemp-step-0',
                    TRSTEMP_URI . 'assets/step-0.css',
                    array(),
                    TRSTEMP_VERSION
                );

                // Load Step 0 JS
                wp_enqueue_script(
                    'trstemp-step-0',
                    TRSTEMP_URI . 'assets/step-0.js',
                    array( 'jquery' ),
                    TRSTEMP_VERSION,
                    true
                );

                // Pass dynamic data (URL) from PHP → JS safely
                wp_localize_script(
                    'trstemp-step-0',
                    'trstempStep0',
                    array(
                        'next_url' => admin_url(
                            'admin.php?page=turbo-starter-templates&ci=1'
                        )
                    )
                );
            }

            /**
             * ---------------------------------------------------------
             * STEP 1: Website Type Selection
             * Used in: steps/step-1.php
             * ---------------------------------------------------------
             */
            if ( $ci == 1 ) {

                wp_enqueue_style(
                    'trstemp-step-1',
                    TRSTEMP_URI . 'assets/step-1.css',
                    array(),
                    TRSTEMP_VERSION
                );

                wp_enqueue_script(
                    'trstemp-step-1',
                    TRSTEMP_URI . 'assets/step-1.js',
                    array( 'jquery' ),
                    TRSTEMP_VERSION,
                    true
                );

                wp_localize_script(
                    'trstemp-step-1',
                    'trstempStep1',
                    array(
                        'ajaxurl' => admin_url( 'admin-ajax.php' ),
                        'step'    => 1,
                        'details' => array(
                            'business'  => array( __( 'About Us page with company story', 'turbo-templates-library-for-elementor' ) ),
                            'portfolio' => array( __( 'Project gallery with filtering', 'turbo-templates-library-for-elementor' ) ),
                            'ecommerce' => array( __( 'Product catalog with categories', 'turbo-templates-library-for-elementor' ) ),
                            'blog'      => array( __( 'Article listing and categories', 'turbo-templates-library-for-elementor' ) ),
                            'landing'   => array( __( 'Hero section with clear value prop', 'turbo-templates-library-for-elementor' ) ),
                            'nonprofit' => array( __( 'Mission and impact pages', 'turbo-templates-library-for-elementor' ) ),
                        ),
                    )
                );
            }


            
            // Enqueue step-specific assets with nonce
            if ( $ci == 2 ) {

                wp_enqueue_style(
                    'trstemp-step-2',
                    TRSTEMP_URI . 'assets/step-2.css',
                    array(),
                    TRSTEMP_VERSION
                );

                wp_enqueue_script(
                    'trstemp-step-2',
                    TRSTEMP_URI . 'assets/step-2.js',
                    array(),
                    TRSTEMP_VERSION,
                    true
                );

                wp_localize_script(
                    'trstemp-step-2',
                    'trstempStep2',
                    array(
                        'ajaxurl' => admin_url( 'admin-ajax.php' ),
                        'step'    => 2,
                        'nonce'   => wp_create_nonce( 'trstemp_wizard_nonce' ),
                    )
                );
            }

            if ( $ci == 3 ) {

                wp_enqueue_style(
                    'trstemp-step-3',
                    TRSTEMP_URI . 'assets/step-3.css',
                    array(),
                    TRSTEMP_VERSION
                );
            }

            if ( $ci == 4 ) {

                wp_enqueue_style(
                    'trstemp-step-4',
                    TRSTEMP_URI . 'assets/step-4.css',
                    array(),
                    TRSTEMP_VERSION
                );
            }

            if ( $ci == 5 ) {

                wp_enqueue_style(
                    'trstemp-step-5',
                    TRSTEMP_URI . 'assets/step-5.css',
                    array(),
                    TRSTEMP_VERSION
                );
            }

            /**
             * ---------------------------------------------------------
             * STEP 6: Import Process
             * Used in: steps/step-6.php
             * ---------------------------------------------------------
             */
            if ( $ci == 6 ) {

                wp_enqueue_style(
                    'trstemp-step-6',
                    TRSTEMP_URI . 'assets/step-6.css',
                    array(),
                    TRSTEMP_VERSION
                );

                /* ---------- JS ---------- */
                wp_enqueue_script(
                    'trstemp-step-6',
                    TRSTEMP_URI . 'assets/step-6.js',
                    array(),
                    TRSTEMP_VERSION,
                    true
                );

                /* ---------- Localized Data ---------- */
                wp_localize_script(
                    'trstemp-step-6',
                    'trstempWizard',
                    array(
                        'ajaxurl'   => admin_url( 'admin-ajax.php' ),
                        'nonce'     => wp_create_nonce( 'trstemp_nonce_action' ),
                        'adminUrl'  => admin_url(),
                        'homeUrl'   => home_url(),
                    )
                );
            }

            // Localize admin nonce for all wizard steps
            wp_localize_script('trstemp-plugin-wizard', 'trstemp_admin', array(
                'nonce' => wp_create_nonce('trstemp_admin_nonce'),
                'ajax_url' => admin_url('admin-ajax.php')
            ));
            
            // Show wizard
            include TRSTEMP_STARTER_DIR . 'wizard.php';
        } else {
            // Render dashboard using the dashboard class
            if (class_exists('Trstemp_Dashboard')) {
                $dashboard = new Trstemp_Dashboard();
                $dashboard->render();
            }
        }
    }
    
    // License and pricing pages removed - all features are now free
    
    // Dashboard functionality moved to dashboard/class-trstemp-dashboard.php
    
    public function trstemp_enqueue_admin_assets($hook) {
        if (strpos($hook, 'turbo-starter-templates') === false) {
            return;
        }
        
        // Enqueue admin styles and scripts
        wp_enqueue_style('trstemp-admin-styles', TRSTEMP_URI . 'assets/admin-styles.css', array(), TRSTEMP_VERSION);
        wp_enqueue_script('trstemp-admin-scripts', TRSTEMP_URI . 'assets/admin-scripts.js', array('jquery'), TRSTEMP_VERSION, true);
        
        // Dashboard assets are now loaded by Trstemp_Dashboard class
        // This keeps the admin assets separate from dashboard assets
        wp_localize_script('trstemp-admin-scripts', 'trstemp_admin', array(
            'nonce' => wp_create_nonce('trstemp_admin_nonce'),
            'ajax_url' => admin_url('admin-ajax.php'),
            'home_url' => home_url(),
            'admin_url' => admin_url()
        ));
    }
    
    public function trstemp_ajax_import_template() {
        // Security: Verify nonce and capabilities
        if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'] ?? '')), TRSTEMP_NONCE_ACTION)) {
            wp_send_json_error(esc_html__('Security verification failed', 'turbo-templates-library-for-elementor'));
        }
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(esc_html__('Insufficient permissions', 'turbo-templates-library-for-elementor'));
        }
        
        // Sanitize input data
        $template_id = isset($_POST['template_id']) ? absint($_POST['template_id']) : 0;
        $template_name = isset($_POST['template_name']) ? sanitize_text_field(wp_unslash($_POST['template_name'])) : '';
        
        // Debug logging to track template selection
        // error_log('TRSTEMP AJAX: Received template_id: ' . $template_id);
        // error_log('TRSTEMP AJAX: Received template_name: ' . $template_name);
        // error_log('TRSTEMP AJAX: POST data: ' . print_r($_POST, true));
        // phpcs:disable WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.MissingUnslash -- Custom sanitization via trstemp_sanitize_customization_data()
        $raw_customization = isset($_POST['customization']) ? wp_unslash($_POST['customization']) : '';
        if ( is_string( $raw_customization ) ) {
            $raw_customization = json_decode( $raw_customization, true );
        }
        $customization = is_array( $raw_customization ) ? $this->trstemp_sanitize_customization_data( $raw_customization ) : array();
        // phpcs:enable WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.MissingUnslash
        
        if (empty($template_id)) {
            wp_send_json_error(esc_html__('Invalid template ID', 'turbo-templates-library-for-elementor'));
        }
        
        // All templates are now free - no license checks needed
        

        
        try {
            if (!class_exists('Trstemp_Template_Importer')) {
                wp_send_json_error(esc_html__('Template importer not available', 'turbo-templates-library-for-elementor'));
            }
            
            // phpcs:disable WordPress.Security.NonceVerification.Missing -- Nonce verified above
            // Get keep_existing_data parameter
            $keep_existing_data = isset($_POST['keep_existing_data']) && $_POST['keep_existing_data'] === '1';
            // phpcs:enable WordPress.Security.NonceVerification.Missing
            
            // phpcs:disable WordPress.PHP.DevelopmentFunctions.error_log_error_log, WordPress.PHP.DevelopmentFunctions.error_log_print_r -- Debug logging
            error_log('TRSTEMP AJAX: Template ID: ' . $template_id);
            error_log('TRSTEMP AJAX: Template Name: ' . $template_name);
            error_log('TRSTEMP AJAX: Keep Existing Data: ' . ($keep_existing_data ? 'YES' : 'NO'));
            error_log('TRSTEMP AJAX: Customization: ' . print_r($customization, true));
            // phpcs:enable WordPress.PHP.DevelopmentFunctions.error_log_error_log, WordPress.PHP.DevelopmentFunctions.error_log_print_r
            
            $importer = new Trstemp_Template_Importer();
            $result = $importer->import_template($template_id, $customization, $keep_existing_data);
            
            if ($result && isset($result['success']) && $result['success']) {
                // Update options securely
                update_option('trstemp_setup_completed', true);
                update_option('trstemp_current_template', $template_id);
                update_option('trstemp_current_template_name', $template_name);
                
                // Backward compatibility
                update_option('trstemp_setup_completed', true);
                update_option('trstemp_current_template', $template_id);
                update_option('trstemp_current_template_name', $template_name);
                
                $result['homepage_url'] = esc_url(home_url());
                wp_send_json_success($result);
            } else {
                $error_message = isset($result['message']) ? sanitize_text_field($result['message']) : esc_html__('Import failed', 'turbo-templates-library-for-elementor');
                wp_send_json_error($error_message);
            }
        } catch (Exception $e) {
            // phpcs:disable WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Error logging
            error_log('TRSTEMP: Import error: ' . $e->getMessage());
            // phpcs:enable WordPress.PHP.DevelopmentFunctions.error_log_error_log
            $error_message = esc_html__('Import failed: ', 'turbo-templates-library-for-elementor') . esc_html($e->getMessage()); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Exception message is escaped with esc_html()
            wp_send_json_error($error_message);
        }
    }
    
    
    /**
     * Enqueue custom CSS for imported templates
     */

    
    public function enqueue_custom_css() {

        if ( ! is_page() ) {
            return;
        }

        global $post;

            $custom_css = get_post_meta( $post->ID, '_trstemp_custom_css', true );

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

        /**
         * Escape CSS LATE (output context)
         * Allow only safe CSS characters
         */
        $escaped_css = wp_kses(
            $custom_css,
            array() // No HTML allowed in CSS
        );

        wp_add_inline_style(
            'wp-block-library',
            $escaped_css
        );
    }

    /**
     * Enqueue inline scripts safely
     */
    public function enqueue_inline_scripts() {
        // Use wp_add_inline_script for JavaScript
        $inline_js = '
            window.trsTemp = window.trsTemp || {};
            window.trsTemp.ajaxUrl = "' . esc_js(admin_url('admin-ajax.php')) . '";
            window.trsTemp.nonce = "' . esc_js(wp_create_nonce('trstemp_admin_nonce')) . '";
        ';
        wp_add_inline_script('jquery', $inline_js);
    }
    
    /**
     * Sanitize customization data array
     */
    private function trstemp_sanitize_customization_data($data) {
        if (!is_array($data)) {
            return array();
        }
        
        $sanitized = array();
        foreach ($data as $key => $value) {
            $key = sanitize_key($key);
            if (is_array($value)) {
                $sanitized[$key] = $this->trstemp_sanitize_customization_data($value);
            } elseif (is_string($value)) {
                // Different sanitization based on key type
                if (strpos($key, 'color') !== false) {
                    $sanitized[$key] = sanitize_hex_color($value);
                } elseif ( $key === 'logo' ) {
                    // Logo may be a base64 data URL or a remote URL; preserve as-is
                    $sanitized[$key] = $value;
                } elseif (strpos($key, 'url') !== false) {
                    $sanitized[$key] = esc_url_raw($value);
                } else {
                    $sanitized[$key] = sanitize_text_field($value);
                }
            } else {
                $sanitized[$key] = $value; // For numeric values
            }
        }
        return $sanitized;
    }
    
    public function trstemp_dismiss_notice() {
        // Security: Verify nonce
        $nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '';
        if (!wp_verify_nonce($nonce, 'trstemp_dismiss')) {
            wp_die(esc_html__('Security verification failed', 'turbo-templates-library-for-elementor'));
        }
        
        set_transient('trstemp_notice_dismissed', true, WEEK_IN_SECONDS);
        set_transient('trstemp_starter_notice_dismissed', true, WEEK_IN_SECONDS);
        wp_die();
    }
    
    // Backward compatibility method
    public function dismiss_notice() {
        $this->trstemp_dismiss_notice();
    }
    
    public function trstemp_ajax_activate_plugin() {
        // This function is deprecated - plugins must be activated manually
        wp_send_json_error(esc_html__('Automatic plugin activation is not allowed. Please activate plugins manually from the Plugins page.', 'turbo-templates-library-for-elementor'));
    }
    
    // Backward compatibility
    public function ajax_activate_plugin() {
        $this->trstemp_ajax_activate_plugin();
    }
    
    public function trstemp_proxy_demo_url() {

        if (
            ! isset( $_GET['_wpnonce'] ) ||
            ! wp_verify_nonce(
                sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ),
                'trstemp_proxy_demo'
            )
        ) {
            wp_die(
                esc_html__( 'The link you followed has expired.', 'turbo-templates-library-for-elementor' ),
                403
            );
        }


        if ( ! current_user_can( 'manage_options' ) ) {
            wp_die(
                esc_html__( 'Insufficient permissions.', 'turbo-templates-library-for-elementor' ),
                403
            );
        }
        /* ---------------------------------------------
        * 2. DEMO URL SANITIZATION
        * --------------------------------------------- */
        $demo_url = isset( $_GET['demo_url'] )
            ? esc_url_raw( wp_unslash( $_GET['demo_url'] ) )
            : '';

        if ( empty( $demo_url ) ) {
            wp_die( esc_html__( 'Demo URL not provided.', 'turbo-templates-library-for-elementor' ), 400 );
        }

        /* ---------------------------------------------
        * 3. SSRF PROTECTION (HOST WHITELIST)
        * --------------------------------------------- */
        $parsed = wp_parse_url( $demo_url );
        $host   = isset( $parsed['host'] ) ? strtolower( $parsed['host'] ) : '';

        $allowed_hosts = array(
            'templates.wp-turbo.com',
            'wp-turbo.com',
            'demo.turbo-addons.com',
        );

        if ( empty( $host ) || ! in_array( $host, $allowed_hosts, true ) ) {
            wp_die( esc_html__( 'Demo host not allowed.', 'turbo-templates-library-for-elementor' ), 403 );
        }

        /* ---------------------------------------------
        * 4. SAFE REMOTE REQUEST
        * --------------------------------------------- */
        $response = wp_remote_get(
            $demo_url,
            array(
                'timeout'   => 20,
                'sslverify' => true,
                'headers'   => array(
                    'Accept' => 'text/html',
                ),
            )
        );

        if ( is_wp_error( $response ) ) {
            wp_die( esc_html__( 'Unable to load demo preview.', 'turbo-templates-library-for-elementor' ), 500 );
        }

        $trstemp_content = wp_remote_retrieve_body( $response );

        if ( empty( $trstemp_content ) ) {
            wp_die( esc_html__( 'Empty demo response.', 'turbo-templates-library-for-elementor' ), 500 );
        }

        /* ---------------------------------------------
        * 5. FIX RELATIVE URLS
        * --------------------------------------------- */
        $trstemp_base_url = esc_url(
            trailingslashit(
                $parsed['scheme'] . '://' . $parsed['host']
            )
        );

        $trstemp_content = str_replace(
            '<head>',
            '<head><base href="' . $trstemp_base_url . '">',
            $trstemp_content
        );

        /* ---------------------------------------------
        * 6. PREVIEW LISTENER (SECURE) - SIMPLE FIX
        * --------------------------------------------- */

        // Register script properly
        function trstemp_preview_listener_fix() {
            global $trstemp_base_url;
            
            if (empty($trstemp_base_url)) {
                return;
            }
            
            wp_register_script( 'trstemp-preview-handler', '', array(), '1.1.0', true );
            wp_enqueue_script( 'trstemp-preview-handler' );
            
            $script_content = '
            (function () {
                const allowedOrigin = "' . esc_js( $trstemp_base_url ) . '";

                window.addEventListener("message", function (event) {
                    if (!event.origin || event.origin.indexOf(allowedOrigin) !== 0) {
                        return;
                    }

                    if (!event.data || !event.data.type) {
                        return;
                    }

                    if (event.data.type === "INJECT_CSS") {
                        let style = document.getElementById("trstemp-preview-styles");
                        if (style) {
                            style.remove();
                        }
                        style = document.createElement("style");
                        style.id = "trstemp-preview-styles";
                        style.textContent = event.data.css || "";
                        document.head.appendChild(style);
                    }

                    if (event.data.type === "REMOVE_CSS") {
                        let style = document.getElementById("trstemp-preview-styles");
                        if (style) {
                            style.remove();
                        }
                    }
                });
            })();';
            
            wp_add_inline_script( 'trstemp-preview-handler', $script_content );
        }

        // Call this function where you were previously doing str_replace
        trstemp_preview_listener_fix();

        /* ---------------------------------------------
        * 7. OUTPUT
        * --------------------------------------------- */
        header( 'Content-Type: text/html; charset=UTF-8' );
        header( 'X-Frame-Options: SAMEORIGIN' );

        // phpcs:disable WordPress.Security.EscapeOutput.OutputNotEscaped
        echo $trstemp_content;
        // phpcs:enable WordPress.Security.EscapeOutput.OutputNotEscaped

        wp_die();
    }

    
    // License AJAX handlers removed - all features are now free
    
    public function trstemp_check_license_status() {
        // All features are now free - always return true
        return true;
    }
    
    public function trstemp_check_template_is_pro($template_id) {
        // All templates are now free - always return false
        return false;
    }
    
    // Backward compatibility methods
    public function proxy_demo_url() { $this->trstemp_proxy_demo_url(); }
    
    public function trstemp_debug_pages() {
        // Verify nonce for debug actions
        if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'] ?? '')), 'trstemp_admin_nonce')) {
            wp_send_json_error('Invalid nonce');
        }
        
        if (!current_user_can('manage_options')) {
            wp_die('Insufficient permissions');
        }
        
        // phpcs:disable WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug function
        error_log('=== DEBUG PAGES CHECK ===');
        
        $pages = get_pages();
        error_log('Total pages found: ' . count($pages));
        
        foreach ($pages as $page) {
            error_log('Page ID: ' . $page->ID . ' Title: ' . $page->post_title . ' Status: ' . $page->post_status);
            $elementor_data = get_post_meta($page->ID, '_elementor_data', true);
            error_log('  Has Elementor data: ' . (!empty($elementor_data) ? 'YES' : 'NO'));
        }
        
        $front_page = get_option('page_on_front');
        $show_on_front = get_option('show_on_front');
        error_log('Homepage settings - show_on_front: ' . $show_on_front . ', page_on_front: ' . $front_page);
        
        error_log('=== END DEBUG PAGES ===');
        // phpcs:enable WordPress.PHP.DevelopmentFunctions.error_log_error_log
        wp_die('Debug completed - check error log');
    }
    
    public function trstemp_check_homepage_status() {
        // Verify nonce
        if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'] ?? '')), 'trstemp_admin_nonce')) {
            wp_send_json_error('Invalid nonce');
        }
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions');
        }
        
        $front_page_id = get_option('page_on_front');
        $show_on_front = get_option('show_on_front');
        
        $status = array(
            'show_on_front' => $show_on_front,
            'homepage_id' => $front_page_id,
            'site_url' => home_url()
        );
        
        if ($front_page_id) {
            $page = get_post($front_page_id);
            if ($page) {
                $status['page_title'] = $page->post_title;
                $status['page_status'] = $page->post_status;
                
                $elementor_data = get_post_meta($front_page_id, '_elementor_data', true);
                $status['has_elementor_data'] = !empty($elementor_data);
                $status['elementor_data_length'] = strlen($elementor_data);
            } else {
                $status['error'] = 'Homepage page not found';
            }
        } else {
            $status['error'] = 'No homepage set';
        }
        
        wp_send_json_success($status);
    }
    
    public function trstemp_fix_homepage_display() {
        // Verify nonce
        if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'] ?? '')), 'trstemp_admin_nonce')) {
            wp_send_json_error('Invalid nonce');
        }
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions');
        }
        
        // Get the first page with Elementor data
        $pages = get_pages( array( 'meta_key' => '_elementor_edit_mode' ) ); // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key -- Required to find Elementor-edited pages; no alternative exists
        
        if (empty($pages)) {
            wp_send_json_error('No Elementor pages found');
        }
        
        $page = $pages[0];
        
        // Set as homepage
        update_option('show_on_front', 'page');
        update_option('page_on_front', $page->ID);
        
        // Clear caches
        wp_cache_flush();
        flush_rewrite_rules();
        
        wp_send_json_success('Homepage set to: ' . $page->post_title . ' (ID: ' . $page->ID . ')');
    }
    
    public function trstemp_debug_import() {
        // Verify nonce for debug actions
        if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'] ?? '')), 'trstemp_admin_nonce')) {
            wp_send_json_error('Invalid nonce');
        }
        
        if (!current_user_can('manage_options')) {
            wp_die('Insufficient permissions');
        }
        
        // phpcs:disable WordPress.PHP.DevelopmentFunctions.error_log_error_log, WordPress.PHP.DevelopmentFunctions.error_log_print_r -- Debug function
        error_log('=== MANUAL DEBUG IMPORT ===');
        
        try {
            if (!class_exists('Trstemp_Template_Importer')) {
                error_log('Template importer class not found');
                wp_die('Template importer not available');
            }
            
            $importer = new Trstemp_Template_Importer();
            $result = $importer->import_template(2, array(), false);
            
            error_log('Debug import result: ' . print_r($result, true));
            
            wp_die('Debug import completed - check error log and pages');
        } catch ( Exception $e ) {
            error_log( 'Debug import exception: ' . $e->getMessage() );

            wp_die(
                sprintf(
                    'Debug import failed: %s',
                    esc_html( $e->getMessage() )
                )
            );
        }

        // phpcs:enable WordPress.PHP.DevelopmentFunctions.error_log_error_log, WordPress.PHP.DevelopmentFunctions.error_log_print_r
    }
    
    public function trstemp_debug_wizard_session() {
        // Verify nonce for GET requests
        if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['nonce'] ?? '')), 'trstemp_admin_nonce')) {
            wp_die('Invalid nonce');
        }
        
        if (!current_user_can('manage_options')) {
            wp_die('Insufficient permissions');
        }
        
        if (!class_exists('Trstemp_WizardSession')) {
            wp_die('WizardSession class not found');
        }
        
        // phpcs:disable WordPress.PHP.DevelopmentFunctions.error_log_print_r, WordPress.Security.EscapeOutput.OutputNotEscaped -- Debug function
        echo '<h2>Wizard Session Debug</h2>';
        
        $session_data = Trstemp_WizardSession::get_session_data();
        echo '<h3>Raw Session Data:</h3>';
        echo '<pre>' . esc_html( print_r( $session_data, true ) ) . '</pre>';
        
        echo '<h3>Summary Data:</h3>';
        $summary = Trstemp_WizardSession::get_summary();
        echo '<pre>' . esc_html( print_r($summary, true) ) . '</pre>';
        
        echo '<h3>Individual Steps:</h3>';
        for ($i = 1; $i <= 5; $i++) {
            $step_data = Trstemp_WizardSession::get_step_data($i);
            echo '<h4>Step ' . $i . ':</h4>';
            echo '<pre>' . esc_html( print_r($step_data, true) ) . '</pre>';
        }
        // phpcs:enable WordPress.PHP.DevelopmentFunctions.error_log_print_r, WordPress.Security.EscapeOutput.OutputNotEscaped
        
        wp_die();
    }
    
    public function trstemp_save_step_data() {
        // Verify nonce
        if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'] ?? '')), 'trstemp_admin_nonce')) {
            wp_send_json_error('Invalid nonce');
        }
        
        // Check permissions
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions');
        }
        
        $step = isset($_POST['step']) ? absint($_POST['step']) : 0;
        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- JSON string containing base64 logo; sanitized field-by-field after json_decode below
        $raw_data = isset($_POST['data']) ? wp_unslash($_POST['data']) : '';
        
        if ($step && $raw_data) {
            $decoded_data = json_decode($raw_data, true);
            if ($decoded_data) {
                // Sanitize safe scalar fields; leave logo untouched
                if ( isset( $decoded_data['site_title'] ) ) {
                    $decoded_data['site_title'] = sanitize_text_field( $decoded_data['site_title'] );
                }
                if ( isset( $decoded_data['site_tagline'] ) ) {
                    $decoded_data['site_tagline'] = sanitize_text_field( $decoded_data['site_tagline'] );
                }
                if ( isset( $decoded_data['font_pair'] ) ) {
                    $decoded_data['font_pair'] = sanitize_key( $decoded_data['font_pair'] );
                }
                if ( isset( $decoded_data['color_palette'] ) ) {
                    $decoded_data['color_palette'] = sanitize_key( $decoded_data['color_palette'] );
                }
                update_option('trstemp_step_' . $step . '_data', $decoded_data);
                wp_send_json_success('Step data saved');
            }
        }
        
        wp_send_json_error('Invalid data');
    }
    
    public function trstemp_get_step_data() {
        // Verify nonce
        if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'] ?? '')), 'trstemp_admin_nonce')) {
            wp_send_json_error('Invalid nonce');
        }
        
        // Check permissions
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions');
        }
        
        $step = isset($_POST['step']) ? absint($_POST['step']) : 0;
        
        if ($step) {
            $data = get_option('trstemp_step_' . $step . '_data', array());
            wp_send_json_success($data);
        }
        
        wp_send_json_error('Invalid step');
    }
    
    public function trstemp_get_preview_url() {
        // Verify nonce
        if (
            ! wp_verify_nonce(
                sanitize_text_field( wp_unslash( $_POST['nonce'] ?? '' ) ),
                'trstemp_admin_nonce'
            )
        ) {
            wp_send_json_error( 'Invalid nonce' );
        }
        
        // Check permissions
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions');
        }
        
        $template_id = isset($_POST['template_id']) ? absint($_POST['template_id']) : 0;
        
        if (!$template_id) {
            wp_send_json_error('Invalid template ID');
        }
        
        // Get demo URL from API
        $api_base = 'https://templates.wp-turbo.com/api/v1';
        $demo_url = '';
        
        // Try template packs first
        $response = wp_remote_get($api_base . '/template-packs/' . $template_id, array(
            'timeout' => 10,
            'headers' => array('Accept' => 'application/json')
        ));
        
        if (!is_wp_error($response)) {
            $body = wp_remote_retrieve_body($response);
            $data = json_decode($body, true);
            if (isset($data['data']['demo_url'])) {
                $demo_url = esc_url_raw($data['data']['demo_url']);
            }
        }
        
        // Try single templates if not found
        if (empty($demo_url)) {
            $response = wp_remote_get($api_base . '/templates/' . $template_id, array(
                'timeout' => 10,
                'headers' => array('Accept' => 'application/json')
            ));
            
            if (!is_wp_error($response)) {
                $body = wp_remote_retrieve_body($response);
                $data = json_decode($body, true);
                if (isset($data['data']['demo_url'])) {
                    $demo_url = esc_url_raw($data['data']['demo_url']);
                }
            }
        }
        
        if ( $demo_url ) {

            $proxy_url = wp_nonce_url(
                add_query_arg(
                    array(
                        'action'   => 'trstemp_admin_proxy_demo', // ✅ CORRECT action
                        'demo_url' => $demo_url,                  // ❌ NO urlencode
                        't'        => time(),                     // cache bust
                    ),
                    admin_url( 'admin-ajax.php' )
                ),
                'trstemp_proxy_demo'
            );

            wp_send_json_success(
                array(
                    'demo_url'  => $demo_url,
                    'proxy_url' => $proxy_url,
                )
            );
        }

        
        wp_send_json_error('Demo URL not found');
    }
    
    public function trstemp_get_wizard_summary() {
        // Verify nonce
        if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'] ?? '')), 'trstemp_admin_nonce')) {
            wp_send_json_error('Invalid nonce');
        }
        
        // Check permissions
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions');
        }
        
        $summary = array();
        
        // Get data from all steps
        for ($i = 1; $i <= 5; $i++) {
            $step_data = get_option('trstemp_step_' . $i . '_data', array());
            if (!empty($step_data)) {
                $summary = array_merge($summary, $step_data);
            }
        }
        
        wp_send_json_success($summary);
    }
}

// Initialize the plugin
if (!function_exists('trstemp_init_plugin')) {
    function trstemp_init_plugin() {
        new Trstemp_Starter_Templates();
    }
}
trstemp_init_plugin();

