<?php
/**
 * Template Importer for Laravel API
 * 
 * phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery
 * phpcs:disable WordPress.DB.DirectDatabaseQuery.NoCaching
 * phpcs:disable WordPress.DB.SlowDBQuery.slow_db_query_meta_key
 * phpcs:disable WordPress.PHP.DevelopmentFunctions.error_log_error_log
 * phpcs:disable WordPress.PHP.DevelopmentFunctions.error_log_print_r
 */
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

class Trstemp_Template_Importer {
    
    private $api_base = 'https://templates.wp-turbo.com/api/v1';
    
    public function import_template($template_id, $customization = array(), $keep_existing_data = true) {
        // Security: Sanitize input parameters
        $template_id = absint($template_id);
        $customization = is_array($customization) ? $customization : array();
        $keep_existing_data = (bool) $keep_existing_data;
        // error_log('=== STARTING TEMPLATE IMPORT ===');
        // error_log('Template ID: ' . $template_id);
        // error_log('Keep existing data: ' . ($keep_existing_data ? 'YES' : 'NO'));
        // error_log('Customization: ' . print_r($customization, true));
        
        // Check required plugins but don't auto-install
        $this->check_required_plugins($template_id);
        
        // Get template from Laravel API
        $template_data = $this->fetch_template_from_laravel($template_id);
        
        if (!$template_data) {
            // error_log('Template data not found for ID: ' . $template_id);
            return array('success' => false, 'message' => 'Template not found');
        }
        
        // error_log('Template data found: ' . $template_data['name']);
        
        // Clean existing pages based on user choice
        if (!$keep_existing_data) {
            // error_log('User chose to replace existing content - cleaning pages');
            $this->clean_pages();
        } else {
            // error_log('User chose to keep existing content - preserving pages');
        }
        
        // Create page with actual template design
        $page_id = $this->create_template_page($template_data, $customization);
        
        if ($page_id) {
            // error_log('Page created successfully with ID: ' . $page_id);
            
            // Apply customizations if provided - both global and to the specific page
            if (!empty($customization)) {
                $this->apply_customization($customization);
                $this->apply_customizations_to_page($page_id, $customization);
                // error_log('Customizations applied to page and globally');
            }
            
            // Set as homepage with multiple methods to ensure it works
            $this->set_as_homepage($page_id);
            
            // Force Elementor to recognize the page
            $this->force_elementor_recognition(array($page_id));
            
            // Regenerate Elementor CSS
            $this->regenerate_elementor_css();
            
            // Store template info
            update_option('trstemp_current_template', $template_id);
            update_option('trstemp_current_template_name', $template_data['name']);
            
            // Final verification
            $this->verify_final_setup($page_id);
            
            // error_log('=== TEMPLATE IMPORT COMPLETED SUCCESSFULLY ===');
            return array('success' => true, 'message' => 'Template imported successfully', 'page_id' => $page_id);
        }
        
        // error_log('=== TEMPLATE IMPORT FAILED ===');
        return array('success' => false, 'message' => 'Failed to create page');
    }
    
    private function check_required_plugins($template_id) {
        // Get template data to determine type
        $template_data = $this->fetch_template_from_laravel($template_id);
        $is_template_pack = isset($template_data['pack_type']) && $template_data['pack_type'] === 'full-site';
        
        // Base required plugins for all templates
        $required_plugins = array(
            'elementor' => array(
                'name' => 'Elementor',
                'file' => 'elementor/elementor.php',
                'slug' => 'elementor'
            ),
            'turbo-addons-elementor' => array(
                'name' => 'Turbo Addons Elementor',
                'file' => 'turbo-addons-elementor/turbo-addons-elementor.php',
                'slug' => 'turbo-addons-elementor'
            )
        );
        
        // Additional plugins for template packs (full-site)
        if ($is_template_pack) {
            $required_plugins['header-footer-builder-for-elementor'] = array(
                'name' => 'Header Footer Builder for Elementor',
                'file' => 'header-footer-builder-for-elementor/header-footer-builder-for-elementor.php',
                'slug' => 'header-footer-builder-for-elementor'
            );
            // error_log('Template pack detected - additional plugins recommended for full-site templates');
        } else {
            // error_log('Single template detected - basic plugins recommended');
        }
        
        $missing_plugins = array();
        
        foreach ($required_plugins as $plugin_slug => $plugin_data) {
            if (!$this->is_plugin_installed($plugin_data['file'])) {
                $missing_plugins[] = $plugin_data['name'] . ' (not installed)';
                // error_log('Missing plugin: ' . $plugin_data['name']);
            } elseif (!$this->is_plugin_active($plugin_data['file'])) {
                $missing_plugins[] = $plugin_data['name'] . ' (not activated)';
                // error_log('Inactive plugin: ' . $plugin_data['name']);
            }
        }
        
        if (!empty($missing_plugins)) {
            // error_log('Required plugins missing or inactive: ' . implode(', ', $missing_plugins));
            // error_log('Please install and activate these plugins manually for best results.');
        } else {
            // error_log('All required plugins are active');
        }
    }
    
    private function is_plugin_installed($plugin_file) {
        return file_exists(WP_PLUGIN_DIR . '/' . $plugin_file);
    }
    
    private function is_plugin_active($plugin_file) {
        return is_plugin_active($plugin_file);
    }
    
    // These methods are deprecated and no longer automatically install/activate plugins
    private function install_plugin_from_wordpress_org($plugin_slug) {
        // error_log('Plugin installation suggestion: ' . $plugin_slug . ' - Please install manually from WordPress.org');
        return false;
    }
    
    private function activate_plugin($plugin_file) {
        // error_log('Plugin activation suggestion: ' . $plugin_file . ' - Please activate manually from Plugins page');
        return false;
    }
    
    private function fetch_template_from_laravel($template_id) {
        // error_log('=== FETCHING TEMPLATE ID: ' . $template_id . ' ===');
        
        // Try template-packs first (full-site templates)
        $pack_url = 'https://templates.wp-turbo.com/api/v1/template-packs/' . $template_id;
        // error_log('Trying template pack URL: ' . $pack_url);
        
        $response = wp_remote_get($pack_url, array('timeout' => 10));
        
        if (!is_wp_error($response) && wp_remote_retrieve_response_code($response) === 200) {
            $body = wp_remote_retrieve_body($response);
            $data = json_decode($body, true);
            
            if (isset($data['data']) && isset($data['data']['pack_type']) && $data['data']['pack_type'] === 'full-site') {
                // error_log('Found template pack (full-site): ' . $data['data']['name']);
                return $data['data'];
            }
        }
        
        // Try single templates (page type)
        $template_url = 'https://templates.wp-turbo.com/api/v1/templates/' . $template_id;
        // error_log('Trying single template URL: ' . $template_url);
        
        $response = wp_remote_get($template_url, array('timeout' => 10));
        
        if (!is_wp_error($response) && wp_remote_retrieve_response_code($response) === 200) {
            $body = wp_remote_retrieve_body($response);
            $data = json_decode($body, true);
            
            if (isset($data['data']) && isset($data['data']['type']) && $data['data']['type'] === 'page') {
                // error_log('Found single template (page): ' . $data['data']['name']);
                // Convert single template to pack format for consistent processing
                return $this->convert_single_template_to_pack($data['data']);
            }
        }
        
        // error_log('No template found for ID: ' . $template_id);
        return false;
    }
    
    private function get_fallback_template_data($template_id) {
        // Create a professional template based on ID
        $templates = array(
            11 => array(
                'id' => 11,
                'name' => 'AGRO TEMPLATE 2025',
                'description' => 'Professional agriculture and farming website template'
            ),
            10 => array(
                'id' => 10,
                'name' => 'Industrial Manufacturing',
                'description' => 'Modern industrial and manufacturing business template'
            ),
            2 => array(
                'id' => 2,
                'name' => 'Creative Portfolio',
                'description' => 'Creative portfolio and agency template'
            )
        );
        
        $template = isset($templates[$template_id]) ? $templates[$template_id] : $templates[11];
        
        // error_log('Using fallback template: ' . $template['name']);
        return $template;
    }
    
    private function clean_pages() {
        $pages = get_pages(array('post_status' => 'publish'));
        // error_log('Found ' . count($pages) . ' existing pages to clean');
        
        foreach ($pages as $page) {
            wp_delete_post($page->ID, true);
            // error_log('Deleted page: ' . $page->post_title . ' (ID: ' . $page->ID . ')');
        }
        
        // Reset homepage settings
        update_option('page_on_front', 0);
        update_option('show_on_front', 'posts');
        
        // error_log('Cleaned ' . count($pages) . ' existing pages and reset homepage');
    }
    
    private function create_template_page($template_data, $customization) {
        $template_name = $template_data['name'];
        // error_log('Creating template page: ' . $template_name);
        
        // Try to get JSON from Laravel API first
        if (isset($template_data['json_file'])) {
            $json_url = 'https://templates.wp-turbo.com/storage/' . $template_data['json_file'];
            // error_log('Fetching JSON from: ' . $json_url);
            
            $json_response = wp_remote_get($json_url, array('timeout' => 30));
            
            if (!is_wp_error($json_response) && wp_remote_retrieve_response_code($json_response) === 200) {
                $json_content = wp_remote_retrieve_body($json_response);
                // error_log('JSON content length: ' . strlen($json_content));
                
                $elementor_data = json_decode($json_content, true);
                
                if ($elementor_data) {
                    // Extract content if nested
                    if (isset($elementor_data['content'])) {
                        $elementor_data = $elementor_data['content'];
                        // error_log('Extracted nested content');
                    }
                    
                    // Validate Elementor structure
                    if ($this->is_valid_elementor_structure($elementor_data)) {
                        // error_log('Valid Elementor structure found, creating page');
                        return $this->create_elementor_page($template_name, $elementor_data);
                    } else {
                        // error_log('Invalid Elementor structure, creating fallback');
                    }
                } else {
                    // error_log('Failed to decode JSON content');
                }
            } else {
                // error_log('Failed to fetch JSON from Laravel API');
            }
        }
        
        // Check if template has templates array (template pack or single template)
        if (isset($template_data['templates']) && is_array($template_data['templates'])) {
            $pack_type = isset($template_data['pack_type']) ? $template_data['pack_type'] : 'unknown';
            // error_log('Processing template with pack_type: ' . $pack_type . ' (' . count($template_data['templates']) . ' templates)');
            
            $pages_created = array();
            $is_first_page = true;
            
            foreach ($template_data['templates'] as $template) {
                // First try embedded JSON data, then fallback to file URLs
                if (isset($template['json_data']) && !empty($template['json_data'])) {
                    // error_log('Using embedded JSON data for: ' . (isset($template['name']) ? $template['name'] : 'Unknown'));
                    
                    $elementor_data = is_string($template['json_data']) ? json_decode($template['json_data'], true) : $template['json_data'];
                    
                    if ($elementor_data && $this->is_valid_elementor_structure($elementor_data)) {
                        $template_name = isset($template['name']) ? $template['name'] : 'Page ' . (count($pages_created) + 1);
                        // error_log('Creating page from embedded JSON: ' . $template_name);
                        $page_id = $this->create_elementor_page($template_name, $elementor_data);
                        if ($page_id) {
                            $pages_created[] = $page_id;
                            if ($is_first_page) {
                                $this->set_as_homepage($page_id);
                                $is_first_page = false;
                            }
                        }
                    }
                } elseif (isset($template['json_file'])) {
                    // Try multiple URL patterns for JSON files
                    $json_urls = array(
                        'https://templates.wp-turbo.com/storage/' . $template['json_file'],
                        'https://templates.wp-turbo.com/storage/app/public/' . $template['json_file'],
                        'https://templates.wp-turbo.com/' . $template['json_file']
                    );
                    
                    $json_content = null;
                    $successful_url = null;
                    
                    foreach ($json_urls as $json_url) {
                        // error_log('Fetching pack template JSON: ' . $json_url);
                        
                        // Try with authentication headers to bypass Laravel middleware
                        $json_response = wp_remote_get($json_url, array(
                            'timeout' => 30,
                            'headers' => array(
                                'User-Agent' => 'WordPress/TurboTemplates',
                                'Accept' => 'application/json,text/plain,*/*',
                                'Authorization' => 'Bearer turbo-templates-public-access',
                                'X-API-Key' => 'turbo-public-key-2024',
                                'X-Requested-With' => 'XMLHttpRequest',
                                'Referer' => 'https://templates.wp-turbo.com',
                                'Origin' => 'https://templates.wp-turbo.com'
                            )
                        ));
                        
                        if (is_wp_error($json_response)) {
                            // error_log('JSON fetch error for ' . $json_url . ': ' . $json_response->get_error_message());
                            continue;
                        }
                        
                        $response_code = wp_remote_retrieve_response_code($json_response);
                        if ($response_code === 200) {
                            $json_content = wp_remote_retrieve_body($json_response);
                            if (!empty($json_content)) {
                                $successful_url = $json_url;
                                // error_log('Successfully fetched JSON from: ' . $json_url);
                                break;
                            }
                        } else {
                            // error_log('JSON fetch failed with status: ' . $response_code);
                            
                            // Try alternative authentication method
                            if ($response_code === 404 || $response_code === 403) {
                                // error_log('Trying alternative auth for: ' . $json_url);
                                $alt_response = wp_remote_get($json_url, array(
                                    'timeout' => 30,
                                    'headers' => array(
                                        'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
                                        'Accept' => '*/*',
                                        'Cache-Control' => 'no-cache',
                                        'Pragma' => 'no-cache'
                                    )
                                ));
                                
                                if (!is_wp_error($alt_response) && wp_remote_retrieve_response_code($alt_response) === 200) {
                                    $json_content = wp_remote_retrieve_body($alt_response);
                                    if (!empty($json_content)) {
                                        $successful_url = $json_url;
                                        // error_log('Successfully fetched JSON with alternative auth from: ' . $json_url);
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    
                    if (!$json_content) {
                        // error_log('All JSON URLs failed for template: ' . (isset($template['name']) ? $template['name'] : 'Unknown'));
                        // error_log('Tried URLs: ' . implode(', ', $json_urls));
                        
                        // Try to scrape JSON from demo site as last resort
                        // error_log('Trying to extract JSON from demo site');
                        $demo_url = 'https://demo.turbo-addons.com/portfolio-home/';
                        $demo_response = wp_remote_get($demo_url, array(
                            'timeout' => 30,
                            'headers' => array(
                                'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
                            )
                        ));
                        
                        if (!is_wp_error($demo_response) && wp_remote_retrieve_response_code($demo_response) === 200) {
                            $demo_html = wp_remote_retrieve_body($demo_response);
                            // Extract Elementor data from the demo page
                            if (preg_match('/var elementorFrontendConfig = ({.*?});/s', $demo_html, $matches)) {
                                $config = json_decode($matches[1], true);
                                if (isset($config['elements']['data'])) {
                                    $json_content = json_encode($config['elements']['data']);
                                    // error_log('Successfully extracted JSON from demo site');
                                }
                            }
                        }
                        
                        if (!$json_content) {
                            continue;
                        }
                    } else {
                        // error_log('Successfully loaded JSON from: ' . $successful_url . ' (length: ' . strlen($json_content) . ')');
                    }
                    
                    // Check if content is CSV data or invalid JSON
                    if (strpos($json_content, 'PassengerId') !== false || strpos($json_content, 'Survived') !== false || strpos($json_content, '"Name":"Braund') !== false) {
                        // error_log('Detected CSV/invalid data, skipping template: ' . (isset($template['name']) ? $template['name'] : 'Unknown'));
                        // If this is the Home template with bad data, create a fallback
                        if (isset($template['page_type']) && $template['page_type'] === 'home') {
                            // error_log('Home template has invalid JSON, will use About as Home');
                        }
                        continue;
                    }
                    
                    // Log JSON preview for debugging
                    // error_log('JSON preview: ' . substr($json_content, 0, 200));
                    
                    $elementor_data = json_decode($json_content, true);
                    
                    if (!$elementor_data) {
                        // error_log('JSON decode failed: ' . json_last_error_msg());
                        continue;
                    }
                    
                    // Handle different JSON structures
                    if (isset($elementor_data['content'])) {
                        $elementor_data = $elementor_data['content'];
                        // error_log('Extracted nested content');
                    }
                    
                    if ($this->is_valid_elementor_structure($elementor_data)) {
                        // If Home template failed and this is About, make it Home
                        $template_name = isset($template['name']) ? $template['name'] : 'Page ' . (count($pages_created) + 1);
                        if (isset($template['page_type']) && $template['page_type'] === 'about' && empty($pages_created)) {
                            $template_name = 'Home';
                            // error_log('Converting About to Home page due to invalid Home JSON');
                        }
                        
                        // error_log('Creating page for pack template: ' . $template_name);
                        $page_id = $this->create_elementor_page($template_name, $elementor_data);
                        if ($page_id) {
                            $pages_created[] = $page_id;
                            if ($is_first_page) {
                                $this->set_as_homepage($page_id);
                                $is_first_page = false;
                            }
                        }
                    } else {
                        // error_log('Invalid Elementor structure for: ' . (isset($template['name']) ? $template['name'] : 'Unknown template'));
                    }
                }
            }
            
            if (!empty($pages_created)) {
                // Create navigation menu for the imported pages
                $this->create_navigation_menu_from_pages($pages_created);
                // error_log('Template pack import completed with ' . count($pages_created) . ' pages');
                return $pages_created[0]; // Return first page ID for compatibility
            }
        }
        
        // No valid JSON found, creating fallback page
        // error_log('No valid JSON found, creating fallback page for: ' . $template_name);
        return $this->create_fallback_page($template_name, sanitize_title($template_name), true);
    }
    
    private function create_elementor_page($title, $elementor_data) {
        // error_log('Creating Elementor page: ' . $title);
        // error_log('Elementor data elements: ' . (is_array($elementor_data) ? count($elementor_data) : 0));
        
        // Create the page with proper title and slug
        $page_slug = sanitize_title($title);
        $page_id = wp_insert_post(array(
            'post_title' => sanitize_text_field($title),
            'post_content' => '',
            'post_status' => 'publish',
            'post_type' => 'page',
            'post_name' => $page_slug,
            'post_author' => get_current_user_id()
        ));
        
        if (is_wp_error($page_id)) {
            // error_log('Error creating page: ' . $page_id->get_error_message());
            return false;
        }
        
        if (!$page_id) {
            // error_log('Page creation returned false');
            return false;
        }
        
        // error_log('Page created with ID: ' . $page_id);
        
        // Import images and replace demo URLs with local URLs in Elementor data
        // error_log('Starting image import for page: ' . $title);
        $elementor_data = $this->import_elementor_images($elementor_data);
        $elementor_data = $this->replace_demo_urls_in_elementor_data($elementor_data);
        
        // Apply customizations to Elementor data BEFORE saving
        if (!empty($customization)) {
            // error_log('Applying customizations to Elementor data for: ' . $title);
            $elementor_data = $this->apply_customizations_to_elementor_data($elementor_data, $customization);
        }
        
        // error_log('Completed image import and customization for page: ' . $title);
        
        // Save Elementor data properly
        $json_data = wp_json_encode($elementor_data);
        update_post_meta($page_id, '_elementor_data', wp_slash($json_data));
        update_post_meta($page_id, '_elementor_edit_mode', 'builder');
        update_post_meta($page_id, '_elementor_template_type', 'wp-page');
        update_post_meta($page_id, '_elementor_version', '3.18.0');
        
        // Set page template for Hello Elementor theme
        update_post_meta($page_id, '_wp_page_template', 'default');
        update_post_meta($page_id, '_hide_title', 'yes');
        update_post_meta($page_id, '_page_template', 'default');
        update_post_meta($page_id, '_elementor_page_template', 'default');
        
        // Force proper array meta fields (not JSON strings)
        update_post_meta($page_id, '_elementor_page_settings', array( 'hide_title' => 'yes' ));
        update_post_meta($page_id, '_elementor_page_assets', array());
        update_post_meta($page_id, '_elementor_controls_usage', array());
        
        // Force Elementor to recognize this page
        if (class_exists('\Elementor\Plugin')) {
            try {
                \Elementor\Plugin::$instance->db->set_is_elementor_page($page_id, true);
                \Elementor\Core\Files\CSS\Post::create($page_id)->update();
                // error_log('Elementor recognition forced for page: ' . $page_id);
            } catch (Exception $e) {
                // error_log('Elementor recognition failed: ' . $e->getMessage());
            }
        }
        
        // error_log('Elementor page setup completed for: ' . $page_id);
        return $page_id;
    }
    
    private function create_professional_page($title, $template_data) {
        // error_log('Creating professional fallback page: ' . $title);
        
        // Create professional Elementor page structure
        $professional_data = array(
            array(
                'id' => 'hero-section',
                'elType' => 'section',
                'settings' => array(
                    'background_background' => 'gradient',
                    'background_color' => '#667eea',
                    'background_color_b' => '#764ba2',
                    'padding' => array('top' => '100', 'bottom' => '100')
                ),
                'elements' => array(
                    array(
                        'id' => 'hero-column',
                        'elType' => 'column',
                        'settings' => array('_column_size' => 100),
                        'elements' => array(
                            array(
                                'id' => 'hero-heading',
                                'elType' => 'widget',
                                'widgetType' => 'heading',
                                'settings' => array(
                                    'title' => $title,
                                    'size' => 'xl',
                                    'color' => '#ffffff',
                                    'align' => 'center'
                                )
                            ),
                            array(
                                'id' => 'hero-text',
                                'elType' => 'widget',
                                'widgetType' => 'text-editor',
                                'settings' => array(
                                    'editor' => '<p style="text-align: center; color: #ffffff; font-size: 18px;">' . esc_html($template_data['description'] ?? 'Professional website template ready for customization') . '</p>'
                                )
                            ),
                            array(
                                'id' => 'hero-button',
                                'elType' => 'widget',
                                'widgetType' => 'button',
                                'settings' => array(
                                    'text' => 'Get Started',
                                    'align' => 'center',
                                    'background_color' => '#FF6B35'
                                )
                            )
                        )
                    )
                )
            )
        );
        
        return $this->create_elementor_page($title, $professional_data);
    }
    
    private function create_simple_pages() {
        $pages_created = array();
        
        // Delete existing pages
        $this->cleanup_existing_pages();
        
        // Create simple pages
        $pages = array(
            array('title' => 'Home', 'slug' => 'home', 'is_front' => true),
            array('title' => 'About Us', 'slug' => 'about'),
            array('title' => 'Services', 'slug' => 'services'),
            array('title' => 'Contact', 'slug' => 'contact')
        );
        
        foreach ($pages as $page_data) {
            $page_id = wp_insert_post(array(
                'post_title' => $page_data['title'],
                'post_content' => '',
                'post_status' => 'publish',
                'post_type' => 'page',
                'post_name' => $page_data['slug'],
                'post_author' => get_current_user_id()
            ));
            
            if ($page_id && !is_wp_error($page_id)) {
                // Add basic Elementor data
                $elementor_data = array(
                    array(
                        'id' => 'section-' . $page_data['slug'],
                        'elType' => 'section',
                        'elements' => array(
                            array(
                                'id' => 'column-' . $page_data['slug'],
                                'elType' => 'column',
                                'settings' => array('_column_size' => 100),
                                'elements' => array(
                                    array(
                                        'id' => 'heading-' . $page_data['slug'],
                                        'elType' => 'widget',
                                        'widgetType' => 'heading',
                                        'settings' => array('title' => $page_data['title'])
                                    )
                                )
                            )
                        )
                    )
                );
                
                update_post_meta($page_id, '_elementor_data', wp_slash(wp_json_encode($elementor_data)));
                update_post_meta($page_id, '_elementor_edit_mode', 'builder');
                update_post_meta($page_id, '_elementor_template_type', 'wp-page');
                update_post_meta($page_id, '_elementor_version', '3.18.0');
                update_post_meta($page_id, '_wp_page_template', 'default');
                update_post_meta($page_id, '_hide_title', 'yes');
                update_post_meta($page_id, '_page_template', 'default');
                
                if (isset($page_data['is_front'])) {
                    update_option('page_on_front', $page_id);
                    update_option('show_on_front', 'page');
                }
                
                $pages_created[] = $page_id;
                // error_log('Created page: ' . $page_data['title'] . ' (ID: ' . $page_id . ')');
            }
        }
        
        return $pages_created;
    }
    
    private function test_page_creation() {
        // error_log('Testing basic page creation...');
        
        $test_page = array(
            'post_title' => 'Test Page ' . time(),
            'post_content' => 'This is a test page',
            'post_status' => 'publish',
            'post_type' => 'page'
        );
        
        $page_id = wp_insert_post($test_page);
        
        if (is_wp_error($page_id)) {
            // error_log('Test page creation failed: ' . $page_id->get_error_message());
            return false;
        }
        
        if (!$page_id || $page_id === 0) {
            // error_log('Test page creation returned 0 or false');
            return false;
        }
        
        // error_log('Test page created successfully with ID: ' . $page_id);
        
        // Clean up test page
        wp_delete_post($page_id, true);
        
        return true;
    }
    
    private function get_template_data($template_id) {
        // error_log('Getting template data for ID: ' . $template_id);
        
        // Try single templates first
        $response = wp_remote_get($this->api_base . '/templates/' . $template_id, array(
            'timeout' => 10,
            'headers' => array('Accept' => 'application/json')
        ));
        
        if (!is_wp_error($response) && wp_remote_retrieve_response_code($response) === 200) {
            $data = json_decode(wp_remote_retrieve_body($response), true);
            if (isset($data['data'])) {
                // error_log('Found single template: ' . $data['data']['name']);
                return $this->convert_single_template_to_pack($data['data']);
            }
        }
        
        // Try template-packs
        $response = wp_remote_get($this->api_base . '/template-packs/' . $template_id, array(
            'timeout' => 10,
            'headers' => array('Accept' => 'application/json')
        ));
        
        if (!is_wp_error($response) && wp_remote_retrieve_response_code($response) === 200) {
            $data = json_decode(wp_remote_retrieve_body($response), true);
            if (isset($data['data'])) {
                // error_log('Found template pack: ' . $data['data']['name']);
                return $data['data'];
            }
        }
        
        // error_log('Laravel API failed, template not found');
        return false;
    }
    
    private function detect_template_type($template_id) {
        // Check template-packs first
        $response = wp_remote_get($this->api_base . '/template-packs/' . $template_id, array(
            'timeout' => 10,
            'headers' => array('Accept' => 'application/json')
        ));
        
        if (!is_wp_error($response) && wp_remote_retrieve_response_code($response) === 200) {
            return 'pack';
        }
        
        // Check templates
        $response = wp_remote_get($this->api_base . '/templates/' . $template_id, array(
            'timeout' => 10,
            'headers' => array('Accept' => 'application/json')
        ));
        
        if (!is_wp_error($response) && wp_remote_retrieve_response_code($response) === 200) {
            return 'single';
        }
        
        return 'unknown';
    }
    
    private function create_pages($template_data, $keep_existing_data = true) {
        $pages_created = array();
        
        // Only delete existing pages if user chose to replace content
        if (!$keep_existing_data) {
            $this->cleanup_existing_pages();
            // error_log('Deleted existing pages as requested by user');
        } else {
            // error_log('Keeping existing pages as requested by user');
        }
        
        // Always create template pages regardless of keep_existing_data setting
        // error_log('Creating template pages...');
        
        // Handle Laravel template pack format with templates array
        if (isset($template_data['templates']) && is_array($template_data['templates'])) {
            // error_log('Creating pages from template pack: ' . count($template_data['templates']) . ' templates found');
            $is_first_page = true;
            foreach ($template_data['templates'] as $template) {
                // Check if template has json_file (from API) or json_data (local fallback)
                if (isset($template['json_file'])) {
                    $page_id = $this->create_page_from_laravel_template($template, $is_first_page, $keep_existing_data);
                } else {
                    $page_id = $this->create_page_from_template($template, $is_first_page, $keep_existing_data);
                }
                
                if ($page_id) {
                    $pages_created[] = $page_id;
                    // error_log('Created page ID: ' . $page_id . ' for template: ' . (isset($template['name']) ? $template['name'] : 'Unknown'));
                } else {
                    // error_log('Failed to create page for template: ' . (isset($template['name']) ? $template['name'] : 'Unknown'));
                }
                $is_first_page = false;
            }
        }
        // Handle Laravel template pack format with pages array
        elseif (isset($template_data['pages']) && is_array($template_data['pages'])) {
            // error_log('Creating pages from Laravel data: ' . count($template_data['pages']) . ' pages found');
            $is_first_page = true;
            foreach ($template_data['pages'] as $page_data) {
                $page_id = $this->create_page_from_laravel_data($page_data, $is_first_page, $keep_existing_data);
                // error_log('Created page ID: ' . $page_id);
                if ($page_id) {
                    $pages_created[] = $page_id;
                }
                $is_first_page = false;
            }
        }
        // Handle single template
        elseif (isset($template_data['json_data'])) {
            $page_id = $this->create_page_from_template($template_data, true, $keep_existing_data);
            if ($page_id) {
                $pages_created[] = $page_id;
            }
        }
        // Handle fallback template format or create default pages
        else {
            if (isset($template_data['templates']) && is_array($template_data['templates'])) {
                // error_log('Creating pages from fallback template: ' . count($template_data['templates']) . ' templates found');
                $is_first_page = true;
                foreach ($template_data['templates'] as $page_template) {
                    $page_id = $this->create_page_from_template($page_template, $is_first_page, $keep_existing_data);
                    // error_log('Created fallback page ID: ' . $page_id);
                    if ($page_id) {
                        $pages_created[] = $page_id;
                    }
                    $is_first_page = false;
                }
            } else {
                $pages_created = $this->create_default_pages();
            }
        }
        
        // error_log('Total pages created: ' . count($pages_created));
        
        // If no pages were created from templates, create a basic page
        if (empty($pages_created) && isset($template_data['name'])) {
            // error_log('No pages created from templates, creating basic page for: ' . $template_data['name']);
            $basic_page_id = $this->create_basic_page($template_data['name']);
            if ($basic_page_id) {
                $pages_created[] = $basic_page_id;
                // error_log('Created basic page with ID: ' . $basic_page_id);
            }
        }
        
        // Create navigation menu based on user choice
        if (!$keep_existing_data) {
            // Replace content - create new menu
            $this->create_navigation_menu_from_pages($pages_created);
            // error_log('Created new navigation menu');
        } else if (!$this->has_existing_menu()) {
            // Keep content but no existing menu - create one
            $this->create_navigation_menu_from_pages($pages_created);
            // error_log('Created navigation menu (no existing menu found)');
        } else {
            // error_log('Keeping existing navigation menu');
        }
        
        // Set homepage - if keeping existing data, only set if no current homepage exists
        $current_homepage = get_option('page_on_front');
        if (!$keep_existing_data || !$current_homepage) {
            $this->set_homepage($pages_created);
            // error_log('Homepage set to first created page');
        } else {
            // error_log('Keeping existing homepage: ' . $current_homepage);
        }
        
        return $pages_created;
    }
    
    private function cleanup_existing_pages() {
        global $wpdb;
        
        // Delete all pages and their meta
        $pages = get_pages();
        foreach ($pages as $page) {
            wp_delete_post($page->ID, true);
            // error_log('Deleted page: ' . $page->post_title);
        }
        
        // Clean orphaned meta
        $wpdb->query("DELETE FROM {$wpdb->postmeta} WHERE post_id NOT IN (SELECT ID FROM {$wpdb->posts})");
        
        // Reset homepage
        update_option('page_on_front', 0);
        update_option('show_on_front', 'posts');
        
        // Clear caches
        wp_cache_flush();
        
        // error_log('All pages cleaned and caches cleared');
    }
    
    private function create_page_from_template($template_data, $is_front_page = false, $keep_existing_data = true) {
        $title = isset($template_data['name']) ? $template_data['name'] : 'Home';
        $slug = isset($template_data['page_type']) ? $template_data['page_type'] : sanitize_title($title);
        
        // error_log('Creating page: ' . $title . ' with slug: ' . $slug);
        
        // Get JSON data from template
        $json_content = isset($template_data['json_data']) ? $template_data['json_data'] : '';
        
        if (empty($json_content)) {
            // error_log('No json_data found for template: ' . $title);
            return false;
        }
        
        // Parse JSON content
        if (is_string($json_content)) {
            $elementor_data = json_decode($json_content, true);
        } else {
            $elementor_data = $json_content;
        }
        
        if (!$elementor_data) {
            // error_log('Failed to parse elementor data for: ' . $title);
            return false;
        }
        
        // error_log('Elementor data parsed successfully for: ' . $title);
        
        // Create WordPress page
        $page_data_wp = array(
            'post_title' => $title,
            'post_content' => '',
            'post_status' => 'publish',
            'post_type' => 'page',
            'post_name' => $slug,
            'post_author' => get_current_user_id()
        );
        
        $page_id = wp_insert_post($page_data_wp);
        
        if (is_wp_error($page_id)) {
            // error_log('Error creating page: ' . $page_id->get_error_message());
            return false;
        }
        
        if (!$page_id || $page_id === 0) {
            // error_log('wp_insert_post returned 0 or false for: ' . $title);
            // error_log('Page data: ' . print_r($page_data_wp, true));
            return false;
        }
        
        if ($page_id) {
            // error_log('Page created successfully with ID: ' . $page_id);
            
            // Save Elementor data with proper meta fields
            update_post_meta($page_id, '_elementor_data', wp_slash(wp_json_encode($elementor_data)));
            update_post_meta($page_id, '_elementor_edit_mode', 'builder');
            update_post_meta($page_id, '_elementor_template_type', 'wp-page');
            update_post_meta($page_id, '_elementor_version', '3.18.0');
            update_post_meta($page_id, '_wp_page_template', 'default');
            update_post_meta($page_id, '_hide_title', 'yes');
            update_post_meta($page_id, '_page_template', 'default');
            
            // Force Elementor to handle this page
            update_post_meta($page_id, '_elementor_css', array());
            update_post_meta($page_id, '_elementor_pro_version', '3.18.0');
            
            // Force these as arrays, not JSON strings
            delete_post_meta($page_id, '_elementor_page_settings');
            delete_post_meta($page_id, '_elementor_page_assets');
            delete_post_meta($page_id, '_elementor_controls_usage');
            add_post_meta($page_id, '_elementor_page_settings', array( 'hide_title' => 'yes' ), true);
            add_post_meta($page_id, '_elementor_page_assets', array(), true);
            add_post_meta($page_id, '_elementor_controls_usage', array(), true);
            
            // error_log('Saved Elementor data for page: ' . $title);
            
            // Set as front page if it's home or first page
            $current_front_page = get_option('page_on_front');
            if (($is_front_page || strtolower($slug) === 'home' || strtolower($title) === 'home')) {
                // Only set as homepage if no existing homepage or user chose to replace content
                if (!$current_front_page || !$keep_existing_data) {
                    update_option('show_on_front', 'page');
                    update_option('page_on_front', $page_id);
                    
                    // Force update theme mods
                    set_theme_mod('page_on_front', $page_id);
                    
                    // error_log('Set as front page: ' . $page_id);
                    
                    // Force refresh rewrite rules and clear cache
                    flush_rewrite_rules();
                    wp_cache_flush();
                } else {
                    // error_log('Keeping existing homepage, created page: ' . $page_id);
                }
            }
        } else {
            // error_log('wp_insert_post returned false for: ' . $title);
        }
        
        return $page_id;
    }
    
    private function create_page_from_laravel_data($page_data, $is_front_page = false, $keep_existing_data = true) {
        $title = isset($page_data['title']) ? $page_data['title'] : 'Page';
        $slug = isset($page_data['slug']) ? $page_data['slug'] : sanitize_title($title);
        
        // Get JSON data from Laravel page - check both json_data and content fields
        $json_content = '';
        if (isset($page_data['json_data'])) {
            $json_content = $page_data['json_data'];
        } elseif (isset($page_data['content'])) {
            // Laravel stores JSON in content field
            if (is_array($page_data['content'])) {
                $json_content = $page_data['content'];
            } else {
                $decoded = json_decode($page_data['content'], true);
                $json_content = isset($decoded['content']) ? $decoded['content'] : $decoded;
            }
        }
        
        if (empty($json_content)) {
            return false;
        }
        
        // Parse JSON content
        if (is_string($json_content)) {
            $elementor_data = json_decode($json_content, true);
        } else {
            $elementor_data = $json_content;
        }
        
        if (!$elementor_data) {
            return false;
        }
        
        // Create WordPress page
        $page_data_wp = array(
            'post_title' => $title,
            'post_content' => '', // Elementor handles content
            'post_status' => 'publish',
            'post_type' => 'page',
            'post_name' => $slug
        );
        
        $page_id = wp_insert_post($page_data_wp);
        
        if ($page_id) {
            // Save Elementor data exactly as from Laravel
            update_post_meta($page_id, '_elementor_data', wp_slash(wp_json_encode($elementor_data)));
            update_post_meta($page_id, '_elementor_edit_mode', 'builder');
            update_post_meta($page_id, '_elementor_template_type', 'wp-page');
            update_post_meta($page_id, '_elementor_version', '3.18.0');
            update_post_meta($page_id, '_wp_page_template', 'default');
            update_post_meta($page_id, '_hide_title', 'yes');
            
            // Force these as arrays, not JSON strings
            delete_post_meta($page_id, '_elementor_page_settings');
            delete_post_meta($page_id, '_elementor_page_assets');
            delete_post_meta($page_id, '_elementor_controls_usage');
            add_post_meta($page_id, '_elementor_page_settings', array( 'hide_title' => 'yes' ), true);
            add_post_meta($page_id, '_elementor_page_assets', array(), true);
            add_post_meta($page_id, '_elementor_controls_usage', array(), true);
            
            // Set as front page if it's home or first page
            $current_front_page = get_option('page_on_front');
            if (($is_front_page || strtolower($slug) === 'home' || strtolower($title) === 'home')) {
                // Only set as homepage if no existing homepage or user chose to replace content
                if (!$current_front_page || !$keep_existing_data) {
                    update_option('page_on_front', $page_id);
                    update_option('show_on_front', 'page');
                    
                    // Force refresh rewrite rules
                    flush_rewrite_rules();
                    // error_log('Set as front page: ' . $page_id);
                } else {
                    // error_log('Keeping existing homepage, created page: ' . $page_id);
                }
            }
        }
        
        return $page_id;
    }
    
    private function create_page_from_laravel_template($template, $is_front_page = false, $keep_existing_data = true) {
        $title = isset($template['name']) ? $template['name'] : 'Page';
        $slug = isset($template['slug']) ? $template['slug'] : sanitize_title($title);
        
        // error_log('Creating Laravel template page: ' . $title);
        
        // Only use json_file method if we have a valid json_file and API is available
        if (isset($template['json_file']) && !empty($template['json_file']) && $this->is_api_available()) {
            // error_log('Using json_file for template: ' . $template['json_file']);
            return $this->create_page_from_json_file($template, $is_front_page, $keep_existing_data);
        } elseif (isset($template['json_data'])) {
            // error_log('Using local json_data for template');
            return $this->create_page_from_template($template, $is_front_page, $keep_existing_data);
        } else {
            // error_log('ERROR: No usable template data found');
            return false;
        }
    }
    
    private function create_page_from_json_file($template, $is_front_page = false, $keep_existing_data = true) {
        $title = isset($template['name']) ? $template['name'] : 'Page';
        $slug = isset($template['slug']) ? $template['slug'] : sanitize_title($title);
        
        // Fetch JSON content from the file URL
        $json_file_url = 'https://templates.wp-turbo.com/storage/' . $template['json_file'];
        // error_log('Fetching JSON from: ' . $json_file_url);
        
        $response = wp_remote_get($json_file_url, array(
            'timeout' => 30
        ));
        
        if (is_wp_error($response)) {
            // error_log('Error fetching JSON file: ' . $response->get_error_message());
            return false;
        }
        
        $response_code = wp_remote_retrieve_response_code($response);
        if ($response_code !== 200) {
            // error_log('JSON file request failed with status: ' . $response_code);
            return false;
        }
        
        $json_content = wp_remote_retrieve_body($response);
        // error_log('Raw JSON content length: ' . strlen($json_content));
        // error_log('Raw JSON preview: ' . substr($json_content, 0, 200));
        
        if (empty($json_content)) {
            // error_log('Empty JSON content received from: ' . $json_file_url);
            return $this->create_fallback_page($title, $slug, $is_front_page);
        }
        
        $elementor_data = json_decode($json_content, true);
        
        if (!$elementor_data) {
            // error_log('Failed to decode JSON content. JSON Error: ' . json_last_error_msg());
            return $this->create_fallback_page($title, $slug, $is_front_page);
        }
        
        // Extract content array if it exists
        if (isset($elementor_data['content'])) {
            $elementor_data = $elementor_data['content'];
        }
        
        // Validate and fix Elementor structure
        if (!$this->is_valid_elementor_structure($elementor_data)) {
            // error_log('Invalid Elementor structure detected, creating fallback page');
            return $this->create_fallback_page($title, $slug, $is_front_page);
        }
        
        // Fix any missing required fields
        $elementor_data = $this->fix_elementor_structure($elementor_data);
        
        // Create WordPress page
        $page_data_wp = array(
            'post_title' => $title,
            'post_content' => '', // Elementor handles content
            'post_status' => 'publish',
            'post_type' => 'page',
            'post_name' => $slug
        );
        
        $page_id = wp_insert_post($page_data_wp);
        
        if (is_wp_error($page_id)) {
            // error_log('Error creating page: ' . $page_id->get_error_message());
            return false;
        }
        
        if ($page_id && !is_wp_error($page_id)) {
            // error_log('Created page ID: ' . $page_id . ' for: ' . $title);
            
            // Save Elementor data with proper validation
            update_post_meta($page_id, '_elementor_data', wp_slash(wp_json_encode($elementor_data)));
            update_post_meta($page_id, '_elementor_edit_mode', 'builder');
            update_post_meta($page_id, '_elementor_template_type', 'wp-page');
            update_post_meta($page_id, '_elementor_version', '3.18.0');
            update_post_meta($page_id, '_wp_page_template', 'default');
            update_post_meta($page_id, '_hide_title', 'yes');
            
            // Ensure proper array meta fields
            update_post_meta($page_id, '_elementor_page_settings', array( 'hide_title' => 'yes' ));
            update_post_meta($page_id, '_elementor_page_assets', array());
            update_post_meta($page_id, '_elementor_controls_usage', array());
            
            // Set as homepage if first page or home
            if ($is_front_page || strtolower($slug) === 'home') {
                update_option('page_on_front', $page_id);
                update_option('show_on_front', 'page');
                // error_log('Set homepage to: ' . $page_id);
            }
        } else {
            // error_log('Failed to create page: ' . $title);
            return false;
        }
        
        return $page_id;
    }
    
    private function is_api_available() {
        $response = wp_remote_get($this->api_base . '/health', array(
            'timeout' => 5,
            'headers' => array('Accept' => 'application/json')
        ));
        
        return !is_wp_error($response) && wp_remote_retrieve_response_code($response) === 200;
    }
    
    private function get_local_fallback_template($template_id) {
        // Map template IDs to specific templates
        $template_map = array(
            10 => array(
                'id' => 10,
                'name' => 'Industrial & Manufacturing Home',
                'templates' => array(
                    array(
                        'name' => 'Industrial & Manufacturing Home',
                        'slug' => 'home',
                        'json_data' => $this->get_industrial_home_json()
                    )
                )
            ),
            2 => array(
                'id' => 2,
                'name' => 'Creative Portfolio Pack',
                'templates' => array(
                    array(
                        'name' => 'Home',
                        'slug' => 'home',
                        'json_data' => $this->get_portfolio_home_json()
                    )
                )
            ),
            5 => array(
                'id' => 5,
                'name' => 'Medical Pro',
                'is_pro' => true,
                'templates' => array(
                    array(
                        'name' => 'Medical Pro Home',
                        'slug' => 'home',
                        'json_data' => $this->get_medical_pro_json()
                    )
                )
            ),
            3 => array(
                'id' => 3,
                'name' => 'Business Pro',
                'is_pro' => true,
                'templates' => array(
                    array(
                        'name' => 'Business Pro Home',
                        'slug' => 'home',
                        'json_data' => $this->get_business_pro_json()
                    )
                )
            )
        );
        
        if (isset($template_map[$template_id])) {
            // error_log('Using local template for ID: ' . $template_id);
            return $template_map[$template_id];
        }
        
        // Default fallback
        return $this->get_fallback_template($template_id);
    }
    
    private function get_medical_pro_json() {
        return json_encode(array(
            array(
                'id' => 'medical-hero',
                'elType' => 'section',
                'settings' => array(
                    'background_background' => 'gradient',
                    'background_color' => '#0066CC',
                    'background_color_b' => '#004499',
                    'padding' => array('top' => '100', 'bottom' => '100')
                ),
                'elements' => array(
                    array(
                        'id' => 'medical-column',
                        'elType' => 'column',
                        'settings' => array('_column_size' => 100),
                        'elements' => array(
                            array(
                                'id' => 'medical-heading',
                                'elType' => 'widget',
                                'widgetType' => 'heading',
                                'settings' => array(
                                    'title' => 'Professional Medical Care',
                                    'size' => 'xl',
                                    'color' => '#ffffff',
                                    'align' => 'center'
                                )
                            ),
                            array(
                                'id' => 'medical-text',
                                'elType' => 'widget',
                                'widgetType' => 'text-editor',
                                'settings' => array(
                                    'editor' => '<p style="text-align: center; color: #ffffff; font-size: 18px;">Comprehensive healthcare services with experienced medical professionals.</p>'
                                )
                            )
                        )
                    )
                )
            )
        ));
    }
    
    private function get_business_pro_json() {
        return json_encode(array(
            array(
                'id' => 'business-hero',
                'elType' => 'section',
                'settings' => array(
                    'background_background' => 'gradient',
                    'background_color' => '#2C3E50',
                    'background_color_b' => '#34495E',
                    'padding' => array('top' => '100', 'bottom' => '100')
                ),
                'elements' => array(
                    array(
                        'id' => 'business-column',
                        'elType' => 'column',
                        'settings' => array('_column_size' => 100),
                        'elements' => array(
                            array(
                                'id' => 'business-heading',
                                'elType' => 'widget',
                                'widgetType' => 'heading',
                                'settings' => array(
                                    'title' => 'Professional Business Solutions',
                                    'size' => 'xl',
                                    'color' => '#ffffff',
                                    'align' => 'center'
                                )
                            ),
                            array(
                                'id' => 'business-text',
                                'elType' => 'widget',
                                'widgetType' => 'text-editor',
                                'settings' => array(
                                    'editor' => '<p style="text-align: center; color: #ffffff; font-size: 18px;">Strategic business consulting and professional services for growth.</p>'
                                )
                            )
                        )
                    )
                )
            )
        ));
    }
    
    private function get_industrial_home_json() {
        return json_encode(array(
            array(
                'id' => 'hero-section',
                'elType' => 'section',
                'settings' => array(
                    'background_background' => 'gradient',
                    'background_color' => '#1E3040',
                    'background_color_b' => '#2C4A5C',
                    'padding' => array('top' => '100', 'bottom' => '100')
                ),
                'elements' => array(
                    array(
                        'id' => 'hero-column',
                        'elType' => 'column',
                        'settings' => array('_column_size' => 100),
                        'elements' => array(
                            array(
                                'id' => 'hero-heading',
                                'elType' => 'widget',
                                'widgetType' => 'heading',
                                'settings' => array(
                                    'title' => 'Industrial & Manufacturing Solutions',
                                    'size' => 'xl',
                                    'color' => '#ffffff',
                                    'align' => 'center'
                                )
                            ),
                            array(
                                'id' => 'hero-text',
                                'elType' => 'widget',
                                'widgetType' => 'text-editor',
                                'settings' => array(
                                    'editor' => '<p style="text-align: center; color: #ffffff; font-size: 18px;">Leading provider of industrial manufacturing solutions with cutting-edge technology and expert craftsmanship.</p>'
                                )
                            ),
                            array(
                                'id' => 'hero-button',
                                'elType' => 'widget',
                                'widgetType' => 'button',
                                'settings' => array(
                                    'text' => 'Get Quote Today',
                                    'align' => 'center',
                                    'background_color' => '#FF6B35'
                                )
                            )
                        )
                    )
                )
            ),
            array(
                'id' => 'services-section',
                'elType' => 'section',
                'settings' => array(
                    'padding' => array('top' => '80', 'bottom' => '80')
                ),
                'elements' => array(
                    array(
                        'id' => 'services-column',
                        'elType' => 'column',
                        'settings' => array('_column_size' => 100),
                        'elements' => array(
                            array(
                                'id' => 'services-heading',
                                'elType' => 'widget',
                                'widgetType' => 'heading',
                                'settings' => array(
                                    'title' => 'Our Manufacturing Services',
                                    'size' => 'large',
                                    'align' => 'center'
                                )
                            ),
                            array(
                                'id' => 'services-grid',
                                'elType' => 'widget',
                                'widgetType' => 'text-editor',
                                'settings' => array(
                                    'editor' => '<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 30px; margin-top: 40px;"><div style="background: white; padding: 30px; border-radius: 10px; text-align: center; box-shadow: 0 4px 15px rgba(0,0,0,0.1);"><h3>🏭 Custom Fabrication</h3><p>Precision manufacturing and custom fabrication services for industrial applications.</p></div><div style="background: white; padding: 30px; border-radius: 10px; text-align: center; box-shadow: 0 4px 15px rgba(0,0,0,0.1);"><h3>⚙️ Machining Services</h3><p>Advanced CNC machining and precision engineering for complex components.</p></div><div style="background: white; padding: 30px; border-radius: 10px; text-align: center; box-shadow: 0 4px 15px rgba(0,0,0,0.1);"><h3>🔧 Assembly & Welding</h3><p>Professional welding and assembly services with quality assurance.</p></div></div>'
                                )
                            )
                        )
                    )
                )
            )
        ));
    }
    
    private function get_portfolio_home_json() {
        return json_encode(array(
            array(
                'id' => 'portfolio-hero',
                'elType' => 'section',
                'settings' => array(
                    'background_background' => 'gradient',
                    'background_color' => '#667eea',
                    'background_color_b' => '#764ba2',
                    'padding' => array('top' => '100', 'bottom' => '100')
                ),
                'elements' => array(
                    array(
                        'id' => 'portfolio-column',
                        'elType' => 'column',
                        'settings' => array('_column_size' => 100),
                        'elements' => array(
                            array(
                                'id' => 'portfolio-heading',
                                'elType' => 'widget',
                                'widgetType' => 'heading',
                                'settings' => array(
                                    'title' => 'Creative Portfolio',
                                    'size' => 'xl',
                                    'color' => '#ffffff',
                                    'align' => 'center'
                                )
                            ),
                            array(
                                'id' => 'portfolio-text',
                                'elType' => 'widget',
                                'widgetType' => 'text-editor',
                                'settings' => array(
                                    'editor' => '<p style="text-align: center; color: #ffffff; font-size: 18px;">Showcase your creative work with style and elegance.</p>'
                                )
                            )
                        )
                    )
                )
            )
        ));
    }
    
    private function get_fallback_template($template_id) {
        // Create a complete website template with multiple pages
        return array(
            'templates' => array(
                array(
                    'name' => 'Home',
                    'page_type' => 'home',
                    'json_data' => $this->get_home_elementor_json()
                ),
                array(
                    'name' => 'About Us',
                    'page_type' => 'about',
                    'json_data' => $this->get_about_elementor_json()
                ),
                array(
                    'name' => 'Our Services',
                    'page_type' => 'services',
                    'json_data' => $this->get_services_elementor_json()
                ),
                array(
                    'name' => 'Portfolio',
                    'page_type' => 'portfolio',
                    'json_data' => $this->get_portfolio_elementor_json()
                ),
                array(
                    'name' => 'Blog',
                    'page_type' => 'blog',
                    'json_data' => $this->get_blog_elementor_json()
                ),
                array(
                    'name' => 'Contact Us',
                    'page_type' => 'contact',
                    'json_data' => $this->get_contact_elementor_json()
                )
            )
        );
    }
    
    private function get_home_elementor_json() {
        return json_encode(array(
            // Hero Section
            array(
                'id' => 'hero-section',
                'elType' => 'section',
                'settings' => array(
                    'background_background' => 'gradient',
                    'background_color' => '#667eea',
                    'background_color_b' => '#764ba2',
                    'padding' => array('top' => '100', 'bottom' => '100')
                ),
                'elements' => array(
                    array(
                        'id' => 'hero-column',
                        'elType' => 'column',
                        'settings' => array('_column_size' => 100, 'width' => 100),
                        'elements' => array(
                            array(
                                'id' => 'hero-heading',
                                'elType' => 'widget',
                                'widgetType' => 'heading',
                                'settings' => array(
                                    'title' => 'Leading Industrial Manufacturing Solutions',
                                    'size' => 'xl',
                                    'color' => '#ffffff',
                                    'align' => 'center'
                                )
                            ),
                            array(
                                'id' => 'hero-text',
                                'elType' => 'widget', 
                                'widgetType' => 'text-editor',
                                'settings' => array(
                                    'editor' => '<p style="text-align: center; color: #ffffff; font-size: 18px;">Professional industrial solutions for modern manufacturing needs. Quality, reliability, and innovation in every project.</p>',
                                    'align' => 'center'
                                )
                            ),
                            array(
                                'id' => 'hero-button',
                                'elType' => 'widget',
                                'widgetType' => 'button',
                                'settings' => array(
                                    'text' => 'Get Started Today',
                                    'align' => 'center',
                                    'button_type' => 'success'
                                )
                            )
                        )
                    )
                )
            ),
            // Services Section
            array(
                'id' => 'services-section',
                'elType' => 'section',
                'settings' => array(
                    'background_background' => 'classic',
                    'background_color' => '#f8f9fa',
                    'padding' => array('top' => '80', 'bottom' => '80')
                ),
                'elements' => array(
                    array(
                        'id' => 'services-column',
                        'elType' => 'column',
                        'settings' => array('_column_size' => 100, 'width' => 100),
                        'elements' => array(
                            array(
                                'id' => 'services-heading',
                                'elType' => 'widget',
                                'widgetType' => 'heading',
                                'settings' => array(
                                    'title' => 'Our Manufacturing Services',
                                    'size' => 'large',
                                    'align' => 'center'
                                )
                            ),
                            array(
                                'id' => 'services-text',
                                'elType' => 'widget',
                                'widgetType' => 'text-editor',
                                'settings' => array(
                                    'editor' => '<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 30px; margin-top: 40px;"><div style="background: white; padding: 30px; border-radius: 10px; text-align: center; box-shadow: 0 4px 15px rgba(0,0,0,0.1);"><h3>🏭 Industrial Design</h3><p>Custom industrial design solutions tailored to your specific manufacturing requirements.</p></div><div style="background: white; padding: 30px; border-radius: 10px; text-align: center; box-shadow: 0 4px 15px rgba(0,0,0,0.1);"><h3>⚙️ Production Management</h3><p>Efficient production management systems to optimize your manufacturing processes.</p></div><div style="background: white; padding: 30px; border-radius: 10px; text-align: center; box-shadow: 0 4px 15px rgba(0,0,0,0.1);"><h3>🔧 Quality Control</h3><p>Comprehensive quality control measures ensuring the highest standards in manufacturing.</p></div></div>'
                                )
                            )
                        )
                    )
                )
            ),
            // About Section
            array(
                'id' => 'about-section',
                'elType' => 'section',
                'settings' => array(
                    'padding' => array('top' => '80', 'bottom' => '80')
                ),
                'elements' => array(
                    array(
                        'id' => 'about-column',
                        'elType' => 'column',
                        'settings' => array('_column_size' => 100, 'width' => 100),
                        'elements' => array(
                            array(
                                'id' => 'about-heading',
                                'elType' => 'widget',
                                'widgetType' => 'heading',
                                'settings' => array(
                                    'title' => 'Why Choose Our Manufacturing Solutions?',
                                    'size' => 'large',
                                    'align' => 'center'
                                )
                            ),
                            array(
                                'id' => 'about-content',
                                'elType' => 'widget',
                                'widgetType' => 'text-editor',
                                'settings' => array(
                                    'editor' => '<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 50px; align-items: center; margin-top: 40px;"><div><h3>🏆 20+ Years Experience</h3><p>With over two decades in the industrial manufacturing sector, we bring unmatched expertise to every project.</p><h3>🌍 Global Reach</h3><p>Serving clients worldwide with manufacturing solutions that meet international standards and regulations.</p><h3>💡 Innovation Focus</h3><p>Constantly investing in new technologies and methodologies to stay ahead of industry trends.</p></div><div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 40px; border-radius: 15px; color: white; text-align: center;"><h3>Ready to Transform Your Manufacturing?</h3><p>Contact us today to discuss how our industrial solutions can optimize your production processes and drive growth.</p><a href="#contact" style="display: inline-block; background: white; color: #667eea; padding: 12px 30px; border-radius: 25px; text-decoration: none; font-weight: bold; margin-top: 20px;">Get Free Consultation</a></div></div>'
                                )
                            )
                        )
                    )
                )
            ),
            // Contact Section
            array(
                'id' => 'contact-section',
                'elType' => 'section',
                'settings' => array(
                    'background_background' => 'classic',
                    'background_color' => '#333333',
                    'padding' => array('top' => '80', 'bottom' => '80')
                ),
                'elements' => array(
                    array(
                        'id' => 'contact-column',
                        'elType' => 'column',
                        'settings' => array('_column_size' => 100, 'width' => 100),
                        'elements' => array(
                            array(
                                'id' => 'contact-heading',
                                'elType' => 'widget',
                                'widgetType' => 'heading',
                                'settings' => array(
                                    'title' => 'Get In Touch With Our Experts',
                                    'size' => 'large',
                                    'color' => '#ffffff',
                                    'align' => 'center'
                                )
                            ),
                            array(
                                'id' => 'contact-info',
                                'elType' => 'widget',
                                'widgetType' => 'text-editor',
                                'settings' => array(
                                    'editor' => '<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 30px; margin-top: 40px; text-align: center;"><div style="color: white;"><h4>📧 Email Us</h4><p>info@industrialmanufacturing.com</p></div><div style="color: white;"><h4>📞 Call Us</h4><p>+1 (555) 123-4567</p></div><div style="color: white;"><h4>📍 Visit Us</h4><p>123 Industrial Ave, Manufacturing City, MC 12345</p></div></div><div style="text-align: center; margin-top: 40px;"><p style="color: #cccccc;">&copy; 2024 Industrial Manufacturing Solutions. All rights reserved.</p></div>'
                                )
                            )
                        )
                    )
                )
            )
        ));
    }
    
    private function get_about_elementor_json() {
        return json_encode(array(
            array(
                'id' => 'about-hero',
                'elType' => 'section',
                'settings' => array(
                    'background_background' => 'gradient',
                    'background_color' => '#667eea',
                    'background_color_b' => '#764ba2',
                    'padding' => array('top' => '80', 'bottom' => '80')
                ),
                'elements' => array(
                    array(
                        'id' => 'about-hero-column',
                        'elType' => 'column',
                        'settings' => array('_column_size' => 100),
                        'elements' => array(
                            array(
                                'id' => 'about-hero-heading',
                                'elType' => 'widget',
                                'widgetType' => 'heading',
                                'settings' => array(
                                    'title' => 'About Our Manufacturing Excellence',
                                    'size' => 'xl',
                                    'color' => '#ffffff',
                                    'align' => 'center'
                                )
                            ),
                            array(
                                'id' => 'about-hero-text',
                                'elType' => 'widget',
                                'widgetType' => 'text-editor',
                                'settings' => array(
                                    'editor' => '<p style="text-align: center; color: #ffffff; font-size: 18px;">Leading the industry with innovative manufacturing solutions since 2004</p>'
                                )
                            )
                        )
                    )
                )
            ),
            array(
                'id' => 'about-content',
                'elType' => 'section',
                'settings' => array(
                    'padding' => array('top' => '80', 'bottom' => '80')
                ),
                'elements' => array(
                    array(
                        'id' => 'about-content-column',
                        'elType' => 'column',
                        'settings' => array('_column_size' => 100),
                        'elements' => array(
                            array(
                                'id' => 'about-story',
                                'elType' => 'widget',
                                'widgetType' => 'text-editor',
                                'settings' => array(
                                    'editor' => '<div style="max-width: 800px; margin: 0 auto;"><h2>Our Story</h2><p>Founded in 2004, Industrial Manufacturing Solutions has grown from a small local operation to a globally recognized leader in industrial manufacturing. Our commitment to quality, innovation, and customer satisfaction has driven our success for over two decades.</p><h2>Our Mission</h2><p>To provide world-class manufacturing solutions that help businesses optimize their production processes, reduce costs, and achieve sustainable growth through innovative technology and expert craftsmanship.</p><h2>Our Values</h2><ul><li><strong>Quality First:</strong> Every product meets the highest industry standards</li><li><strong>Innovation:</strong> Continuously investing in cutting-edge technology</li><li><strong>Reliability:</strong> Dependable solutions you can count on</li><li><strong>Partnership:</strong> Building long-term relationships with our clients</li></ul></div>'
                                )
                            )
                        )
                    )
                )
            )
        ));
    }
    
    private function get_services_elementor_json() {
        return json_encode(array(
            array(
                'id' => 'services-hero',
                'elType' => 'section',
                'settings' => array(
                    'background_background' => 'gradient',
                    'background_color' => '#667eea',
                    'background_color_b' => '#764ba2',
                    'padding' => array('top' => '80', 'bottom' => '80')
                ),
                'elements' => array(
                    array(
                        'id' => 'services-hero-column',
                        'elType' => 'column',
                        'settings' => array('_column_size' => 100, 'width' => 100),
                        'elements' => array(
                            array(
                                'id' => 'services-hero-heading',
                                'elType' => 'widget',
                                'widgetType' => 'heading',
                                'settings' => array(
                                    'title' => 'Our Manufacturing Services',
                                    'size' => 'xl',
                                    'color' => '#ffffff',
                                    'align' => 'center'
                                )
                            ),
                            array(
                                'id' => 'services-hero-text',
                                'elType' => 'widget',
                                'widgetType' => 'text-editor',
                                'settings' => array(
                                    'editor' => '<p style="text-align: center; color: #ffffff; font-size: 18px;">Comprehensive industrial solutions for all your manufacturing needs</p>'
                                )
                            )
                        )
                    )
                )
            ),
            array(
                'id' => 'services-content',
                'elType' => 'section',
                'settings' => array(
                    'padding' => array('top' => '80', 'bottom' => '80')
                ),
                'elements' => array(
                    array(
                        'id' => 'services-content-column',
                        'elType' => 'column',
                        'settings' => array('_column_size' => 100, 'width' => 100),
                        'elements' => array(
                            array(
                                'id' => 'services-grid',
                                'elType' => 'widget',
                                'widgetType' => 'text-editor',
                                'settings' => array(
                                    'editor' => '<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(350px, 1fr)); gap: 40px;"><div style="background: white; padding: 40px; border-radius: 15px; box-shadow: 0 8px 25px rgba(0,0,0,0.1); text-align: center;"><div style="width: 80px; height: 80px; background: linear-gradient(135deg, #667eea, #764ba2); border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 20px; color: white; font-size: 24px;">🏭</div><h3 style="margin: 0 0 15px 0; color: #333;">Industrial Design</h3><p style="color: #666; line-height: 1.6;">Custom industrial design solutions tailored to your specific manufacturing requirements and industry standards.</p></div><div style="background: white; padding: 40px; border-radius: 15px; box-shadow: 0 8px 25px rgba(0,0,0,0.1); text-align: center;"><div style="width: 80px; height: 80px; background: linear-gradient(135deg, #4facfe, #00f2fe); border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 20px; color: white; font-size: 24px;">⚙️</div><h3 style="margin: 0 0 15px 0; color: #333;">Production Management</h3><p style="color: #666; line-height: 1.6;">Efficient production management systems to optimize your manufacturing processes and increase productivity.</p></div><div style="background: white; padding: 40px; border-radius: 15px; box-shadow: 0 8px 25px rgba(0,0,0,0.1); text-align: center;"><div style="width: 80px; height: 80px; background: linear-gradient(135deg, #43e97b, #38f9d7); border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 20px; color: white; font-size: 24px;">🔧</div><h3 style="margin: 0 0 15px 0; color: #333;">Quality Control</h3><p style="color: #666; line-height: 1.6;">Comprehensive quality control measures ensuring the highest standards in manufacturing and product delivery.</p></div><div style="background: white; padding: 40px; border-radius: 15px; box-shadow: 0 8px 25px rgba(0,0,0,0.1); text-align: center;"><div style="width: 80px; height: 80px; background: linear-gradient(135deg, #f093fb, #f5576c); border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 20px; color: white; font-size: 24px;">🤖</div><h3 style="margin: 0 0 15px 0; color: #333;">Automation Solutions</h3><p style="color: #666; line-height: 1.6;">Advanced automation systems to streamline your manufacturing processes and reduce operational costs.</p></div><div style="background: white; padding: 40px; border-radius: 15px; box-shadow: 0 8px 25px rgba(0,0,0,0.1); text-align: center;"><div style="width: 80px; height: 80px; background: linear-gradient(135deg, #667eea, #764ba2); border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 20px; color: white; font-size: 24px;">📊</div><h3 style="margin: 0 0 15px 0; color: #333;">Consulting Services</h3><p style="color: #666; line-height: 1.6;">Expert consulting to help you optimize your manufacturing operations and implement best practices.</p></div><div style="background: white; padding: 40px; border-radius: 15px; box-shadow: 0 8px 25px rgba(0,0,0,0.1); text-align: center;"><div style="width: 80px; height: 80px; background: linear-gradient(135deg, #4facfe, #00f2fe); border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 20px; color: white; font-size: 24px;">🛠️</div><h3 style="margin: 0 0 15px 0; color: #333;">Maintenance Support</h3><p style="color: #666; line-height: 1.6;">Ongoing maintenance and support services to keep your manufacturing equipment running at peak performance.</p></div></div>'
                                )
                            )
                        )
                    )
                )
            )
        ));
    }
    
    private function get_contact_elementor_json() {
        return json_encode(array(
            array(
                'id' => 'contact-section',
                'elType' => 'section',
                'settings' => array(
                    'padding' => array('top' => '80', 'bottom' => '80')
                ),
                'elements' => array(
                    array(
                        'id' => 'contact-column',
                        'elType' => 'column',
                        'settings' => array('_column_size' => 100, 'width' => 100),
                        'elements' => array(
                            array(
                                'id' => 'contact-heading',
                                'elType' => 'widget',
                                'widgetType' => 'heading',
                                'settings' => array(
                                    'title' => 'Get In Touch With Us',
                                    'size' => 'xl',
                                    'align' => 'center'
                                )
                            ),
                            array(
                                'id' => 'contact-form',
                                'elType' => 'widget',
                                'widgetType' => 'text-editor',
                                'settings' => array(
                                    'editor' => '<div style="max-width: 600px; margin: 0 auto;"><div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 20px;"><input type="text" placeholder="Your Name" style="padding: 15px; border: 1px solid #ddd; border-radius: 5px;"><input type="email" placeholder="Your Email" style="padding: 15px; border: 1px solid #ddd; border-radius: 5px;"></div><textarea placeholder="Your Message" rows="5" style="width: 100%; padding: 15px; border: 1px solid #ddd; border-radius: 5px; margin-bottom: 20px;"></textarea><button style="background: #667eea; color: white; padding: 15px 30px; border: none; border-radius: 5px; cursor: pointer; width: 100%;">Send Message</button></div>'
                                )
                            )
                        )
                    )
                )
            )
        ));
    }
    
    private function get_portfolio_elementor_json() {
        return json_encode(array(
            array(
                'id' => 'portfolio-section',
                'elType' => 'section',
                'settings' => array(
                    'padding' => array('top' => '80', 'bottom' => '80')
                ),
                'elements' => array(
                    array(
                        'id' => 'portfolio-column',
                        'elType' => 'column',
                        'settings' => array('_column_size' => 100, 'width' => 100),
                        'elements' => array(
                            array(
                                'id' => 'portfolio-heading',
                                'elType' => 'widget',
                                'widgetType' => 'heading',
                                'settings' => array(
                                    'title' => 'Our Portfolio',
                                    'size' => 'xl',
                                    'align' => 'center'
                                )
                            ),
                            array(
                                'id' => 'portfolio-gallery',
                                'elType' => 'widget',
                                'widgetType' => 'text-editor',
                                'settings' => array(
                                    'editor' => '<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 30px; margin-top: 40px;"><div style="background: white; border-radius: 10px; overflow: hidden; box-shadow: 0 4px 15px rgba(0,0,0,0.1);"><div style="height: 200px; background: linear-gradient(135deg, #667eea, #764ba2); display: flex; align-items: center; justify-content: center; color: white; font-size: 18px;">Project 1</div><div style="padding: 20px;"><h3>Manufacturing Plant Design</h3><p>Complete industrial facility design and implementation</p></div></div><div style="background: white; border-radius: 10px; overflow: hidden; box-shadow: 0 4px 15px rgba(0,0,0,0.1);"><div style="height: 200px; background: linear-gradient(135deg, #4facfe, #00f2fe); display: flex; align-items: center; justify-content: center; color: white; font-size: 18px;">Project 2</div><div style="padding: 20px;"><h3>Automation System</h3><p>Advanced automation solutions for modern manufacturing</p></div></div><div style="background: white; border-radius: 10px; overflow: hidden; box-shadow: 0 4px 15px rgba(0,0,0,0.1);"><div style="height: 200px; background: linear-gradient(135deg, #43e97b, #38f9d7); display: flex; align-items: center; justify-content: center; color: white; font-size: 18px;">Project 3</div><div style="padding: 20px;"><h3>Quality Control System</h3><p>Comprehensive quality assurance implementation</p></div></div></div>'
                                )
                            )
                        )
                    )
                )
            )
        ));
    }
    
    private function get_blog_elementor_json() {
        return json_encode(array(
            array(
                'id' => 'blog-section',
                'elType' => 'section',
                'settings' => array(
                    'padding' => array('top' => '80', 'bottom' => '80')
                ),
                'elements' => array(
                    array(
                        'id' => 'blog-column',
                        'elType' => 'column',
                        'settings' => array('_column_size' => 100, 'width' => 100),
                        'elements' => array(
                            array(
                                'id' => 'blog-heading',
                                'elType' => 'widget',
                                'widgetType' => 'heading',
                                'settings' => array(
                                    'title' => 'Latest News & Insights',
                                    'size' => 'xl',
                                    'align' => 'center'
                                )
                            ),
                            array(
                                'id' => 'blog-posts',
                                'elType' => 'widget',
                                'widgetType' => 'text-editor',
                                'settings' => array(
                                    'editor' => '<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(350px, 1fr)); gap: 30px; margin-top: 40px;"><article style="background: white; border-radius: 10px; overflow: hidden; box-shadow: 0 4px 15px rgba(0,0,0,0.1);"><div style="height: 200px; background: linear-gradient(135deg, #667eea, #764ba2); display: flex; align-items: center; justify-content: center; color: white; font-size: 16px;">Blog Post Image</div><div style="padding: 25px;"><h3 style="margin: 0 0 10px 0;">The Future of Industrial Manufacturing</h3><p style="color: #666; margin: 0 0 15px 0;">Exploring the latest trends and technologies shaping the manufacturing industry...</p><a href="#" style="color: #667eea; text-decoration: none; font-weight: 600;">Read More →</a></div></article><article style="background: white; border-radius: 10px; overflow: hidden; box-shadow: 0 4px 15px rgba(0,0,0,0.1);"><div style="height: 200px; background: linear-gradient(135deg, #4facfe, #00f2fe); display: flex; align-items: center; justify-content: center; color: white; font-size: 16px;">Blog Post Image</div><div style="padding: 25px;"><h3 style="margin: 0 0 10px 0;">Automation Best Practices</h3><p style="color: #666; margin: 0 0 15px 0;">Learn how to implement automation systems effectively in your manufacturing process...</p><a href="#" style="color: #667eea; text-decoration: none; font-weight: 600;">Read More →</a></div></article><article style="background: white; border-radius: 10px; overflow: hidden; box-shadow: 0 4px 15px rgba(0,0,0,0.1);"><div style="height: 200px; background: linear-gradient(135deg, #43e97b, #38f9d7); display: flex; align-items: center; justify-content: center; color: white; font-size: 16px;">Blog Post Image</div><div style="padding: 25px;"><h3 style="margin: 0 0 10px 0;">Quality Control Standards</h3><p style="color: #666; margin: 0 0 15px 0;">Understanding the importance of quality control in modern manufacturing...</p><a href="#" style="color: #667eea; text-decoration: none; font-weight: 600;">Read More →</a></div></article></div>'
                                )
                            )
                        )
                    )
                )
            )
        ));
    }
    
    private function create_default_pages() {
        $fallback_data = $this->get_fallback_template(1);
        return $this->create_pages($fallback_data);
    }
    
    private function create_navigation_menu() {
        // Create navigation menu
        $menu_name = 'Primary Menu';
        $menu_exists = wp_get_nav_menu_object($menu_name);
        
        if (!$menu_exists) {
            $menu_id = wp_create_nav_menu($menu_name);
            
            // Get all pages
            $pages = get_pages();
            
            foreach ($pages as $page) {
                wp_update_nav_menu_item($menu_id, 0, array(
                    'menu-item-title' => $page->post_title,
                    'menu-item-object' => 'page',
                    'menu-item-object-id' => $page->ID,
                    'menu-item-type' => 'post_type',
                    'menu-item-status' => 'publish'
                ));
            }
            
            // Assign menu to primary location
            $locations = get_theme_mod('nav_menu_locations');
            $locations['primary'] = $menu_id;
            set_theme_mod('nav_menu_locations', $locations);
        }
    }
    
    private function create_navigation_menu_from_pages($page_ids) {
        // Delete existing menus first
        $existing_menus = wp_get_nav_menus();
        foreach ($existing_menus as $menu) {
            wp_delete_nav_menu($menu->term_id);
        }
        
        // Create new primary menu
        $menu_name = 'Primary Menu';
        $menu_id = wp_create_nav_menu($menu_name);
        
        if ($menu_id && !is_wp_error($menu_id)) {
            // Add pages to menu in order
            foreach ($page_ids as $page_id) {
                $page = get_post($page_id);
                if ($page) {
                    wp_update_nav_menu_item($menu_id, 0, array(
                        'menu-item-title' => $page->post_title,
                        'menu-item-object' => 'page',
                        'menu-item-object-id' => $page->ID,
                        'menu-item-type' => 'post_type',
                        'menu-item-status' => 'publish'
                    ));
                    // error_log('Added to menu: ' . $page->post_title);
                }
            }
            
            // Assign menu to theme's registered locations
            $registered_locations = get_registered_nav_menus();
            $locations = get_theme_mod( 'nav_menu_locations', array() );
            if ( ! empty( $registered_locations ) ) {
                $first_location = array_key_first( $registered_locations );
                $locations[ $first_location ] = $menu_id;
                foreach ( array( 'primary', 'header', 'main', 'menu-1' ) as $loc ) {
                    if ( isset( $registered_locations[ $loc ] ) ) {
                        $locations[ $loc ] = $menu_id;
                    }
                }
            } else {
                $locations['primary'] = $menu_id;
                $locations['header']  = $menu_id;
            }
            set_theme_mod( 'nav_menu_locations', $locations );
            
            // error_log('Created navigation menu with ' . count($page_ids) . ' items');
        }
    }
    
    private function has_existing_menu() {
        $menus = wp_get_nav_menus();
        return !empty($menus);
    }
    
    private function set_homepage($pages_created) {
        if (!empty($pages_created)) {
            // Find the home page
            $home_page_id = null;
            foreach ($pages_created as $page_id) {
                $page = get_post($page_id);
                if ($page && (strtolower($page->post_name) === 'home' || strtolower($page->post_title) === 'home')) {
                    $home_page_id = $page_id;
                    break;
                }
            }
            
            // If no home page found, use the first page
            if (!$home_page_id && !empty($pages_created)) {
                $home_page_id = $pages_created[0];
            }
            
            if ($home_page_id) {
                // Force homepage setting multiple ways
                update_option('show_on_front', 'page');
                update_option('page_on_front', $home_page_id);
                set_theme_mod('page_on_front', $home_page_id);
                
                // Update page status to published
                wp_update_post(array(
                    'ID' => $home_page_id,
                    'post_status' => 'publish'
                ));
                
                // error_log('Final homepage set to: ' . $home_page_id);
                flush_rewrite_rules();
                wp_cache_flush();
            }
        }
    }
    
    private function convert_single_template_to_pack($template) {
        // error_log('Converting single template: ' . $template['name']);
        
        return array(
            'id' => $template['id'],
            'name' => $template['name'],
            'pack_type' => 'single-page',
            'templates' => array(
                array(
                    'id' => $template['id'],
                    'name' => $template['name'],
                    'slug' => 'home',
                    'page_type' => 'home',
                    'json_file' => $template['json_file']
                )
            )
        );
    }
    
    private function apply_customization($customization) {
        // Apply site info
        if (isset($customization['site_title'])) {
            update_option('blogname', $customization['site_title']);
        }
        
        if (isset($customization['site_tagline'])) {
            update_option('blogdescription', $customization['site_tagline']);
        }
        
        // Apply logo
        if (isset($customization['logo'])) {
            $this->set_logo($customization['logo']);
        }
        
        // Store customization settings for theme
        if (isset($customization['font_pair'])) {
            set_theme_mod('trstemp_body_font', $customization['font_pair']);
        }
        
        if (isset($customization['color_palette'])) {
            set_theme_mod('trstemp_color_palette', $customization['color_palette']);
        }
    }
    
    private function apply_customizations_to_page($page_id, $customization) {
        // error_log('Applying customizations to page: ' . $page_id);
        
        // Get current Elementor data
        $elementor_data = get_post_meta($page_id, '_elementor_data', true);
        if (empty($elementor_data)) {
            // error_log('No Elementor data found for page: ' . $page_id);
            return;
        }
        
        $data = json_decode($elementor_data, true);
        if (!$data) {
            // error_log('Failed to decode Elementor data for page: ' . $page_id);
            return;
        }
        
        // Apply font customization
        if (isset($customization['font_pair'])) {
            $data = $this->inject_font_to_elementor_data($data, $customization['font_pair']);
            // error_log('Applied font to page ' . $page_id . ': ' . $customization['font_pair']);
        }
        
        // Apply color customization
        if (isset($customization['color_palette'])) {
            $color_map = array(
                'blue' => '#2196F3',
                'green' => '#4CAF50',
                'purple' => '#9C27B0',
                'orange' => '#FF9800',
                'teal' => '#009688',
                'red' => '#F44336',
                'black' => '#212121'
            );
            
            $primary_color = isset($color_map[$customization['color_palette']]) ? $color_map[$customization['color_palette']] : '#667eea';
            $data = $this->inject_color_to_elementor_data($data, $primary_color);
            // error_log('Applied color to page ' . $page_id . ': ' . $customization['color_palette'] . ' (' . $primary_color . ')');
        }
        
        // Save updated Elementor data
        update_post_meta($page_id, '_elementor_data', wp_slash(wp_json_encode($data)));
        
        // Force Elementor to regenerate CSS for this page
        if (class_exists('\Elementor\Plugin')) {
            try {
                \Elementor\Core\Files\CSS\Post::create($page_id)->update();
                // error_log('Regenerated CSS for customized page: ' . $page_id);
            } catch (Exception $e) {
                // error_log('CSS regeneration failed for page ' . $page_id . ': ' . $e->getMessage());
            }
        }
    }
    
    private function apply_customizations_to_elementor_data($elementor_data, $customization) {
        // error_log('Applying customizations: ' . print_r($customization, true));
        
        // Apply font customization
        if (isset($customization['font_pair'])) {
            $elementor_data = $this->inject_font_to_elementor_data($elementor_data, $customization['font_pair']);
            // error_log('Applied font: ' . $customization['font_pair']);
        }
        
        // Apply color customization
        if (isset($customization['color_palette'])) {
            $color_map = array(
                'original' => '#667eea',
                'blue' => '#2196F3',
                'green' => '#4CAF50',
                'purple' => '#9C27B0',
                'orange' => '#FF9800',
                'teal' => '#009688',
                'red' => '#F44336',
                'black' => '#212121'
            );
            
            $primary_color = isset($color_map[$customization['color_palette']]) ? $color_map[$customization['color_palette']] : '#667eea';
            $elementor_data = $this->inject_color_to_elementor_data($elementor_data, $primary_color);
            // error_log('Applied color palette: ' . $customization['color_palette'] . ' (' . $primary_color . ')');
        }
        
        return $elementor_data;
    }
    
    private function apply_font_to_pages($font_family) {
        $pages = get_pages();
        foreach ($pages as $page) {
            $elementor_data = get_post_meta($page->ID, '_elementor_data', true);
            if ($elementor_data) {
                $data = json_decode($elementor_data, true);
                $data = $this->inject_font_to_elementor_data($data, $font_family);
                update_post_meta($page->ID, '_elementor_data', wp_slash(wp_json_encode($data)));
            }
        }
    }
    
    private function apply_colors_to_pages($color_palette) {
        $color_map = array(
            'blue' => '#2196F3',
            'green' => '#4CAF50', 
            'purple' => '#9C27B0',
            'orange' => '#FF9800',
            'teal' => '#009688',
            'red' => '#F44336',
            'dark' => '#212121'
        );
        
        $primary_color = isset($color_map[$color_palette]) ? $color_map[$color_palette] : '#667eea';
        
        $pages = get_pages();
        foreach ($pages as $page) {
            $elementor_data = get_post_meta($page->ID, '_elementor_data', true);
            if ($elementor_data) {
                $data = json_decode($elementor_data, true);
                $data = $this->inject_color_to_elementor_data($data, $primary_color);
                update_post_meta($page->ID, '_elementor_data', wp_slash(wp_json_encode($data)));
            }
        }
    }
    
    private function inject_font_to_elementor_data($data, $font_family) {
        if (!is_array($data)) return $data;
        
        foreach ($data as &$section) {
            if (isset($section['elements'])) {
                $section['elements'] = $this->inject_font_to_elements($section['elements'], $font_family);
            }
        }
        
        return $data;
    }
    
    private function inject_font_to_elements($elements, $font_family) {
        foreach ($elements as &$element) {
            // Apply font to heading widgets
            if (isset($element['widgetType']) && $element['widgetType'] === 'heading') {
                $element['settings']['typography_typography'] = 'custom';
                $element['settings']['typography_font_family'] = $font_family;
            }
            
            // Apply font to text editor widgets
            if (isset($element['widgetType']) && $element['widgetType'] === 'text-editor') {
                $element['settings']['typography_typography'] = 'custom';
                $element['settings']['typography_font_family'] = $font_family;
            }
            
            // Apply font to button widgets
            if (isset($element['widgetType']) && $element['widgetType'] === 'button') {
                $element['settings']['typography_typography'] = 'custom';
                $element['settings']['typography_font_family'] = $font_family;
            }
            
            // Apply font to Turbo Addons widgets
            if (isset($element['widgetType']) && strpos($element['widgetType'], 'trad-') === 0) {
                $element['settings']['typography_typography'] = 'custom';
                $element['settings']['typography_font_family'] = $font_family;
                $element['settings']['title_typography_typography'] = 'custom';
                $element['settings']['title_typography_font_family'] = $font_family;
            }
            
            // Recursively apply to nested elements
            if (isset($element['elements'])) {
                $element['elements'] = $this->inject_font_to_elements($element['elements'], $font_family);
            }
        }
        
        return $elements;
    }
    
    private function inject_color_to_elementor_data($data, $color) {
        if (!is_array($data)) return $data;
        
        foreach ($data as &$section) {
            // Apply color to section backgrounds
            if (isset($section['settings']['background_background']) && $section['settings']['background_background'] === 'gradient') {
                $section['settings']['background_color'] = $color;
                $section['settings']['background_color_b'] = $this->darken_color($color, 20);
            } elseif (isset($section['settings']['background_background']) && $section['settings']['background_background'] === 'classic') {
                $section['settings']['background_color'] = $color;
            }
            
            if (isset($section['elements'])) {
                $section['elements'] = $this->inject_color_to_elements($section['elements'], $color);
            }
        }
        
        return $data;
    }
    
    private function inject_color_to_elements($elements, $color) {
        foreach ($elements as &$element) {
            // Apply color to heading widgets
            if (isset($element['widgetType']) && $element['widgetType'] === 'heading') {
                // Only apply color if not white (preserve white text on colored backgrounds)
                if (!isset($element['settings']['color']) || $element['settings']['color'] !== '#ffffff') {
                    $element['settings']['title_color'] = $color;
                }
            }
            
            // Apply color to button widgets
            if (isset($element['widgetType']) && $element['widgetType'] === 'button') {
                $element['settings']['background_color'] = $color;
                $element['settings']['button_background_color'] = $color;
            }
            
            // Apply color to Turbo Addons widgets
            if (isset($element['widgetType']) && strpos($element['widgetType'], 'trad-') === 0) {
                $element['settings']['primary_color'] = $color;
                $element['settings']['button_color'] = $color;
                $element['settings']['button_background_color'] = $color;
                $element['settings']['accent_color'] = $color;
            }
            
            // Apply color to icon widgets
            if (isset($element['widgetType']) && $element['widgetType'] === 'icon') {
                $element['settings']['primary_color'] = $color;
            }
            
            // Recursively apply to nested elements
            if (isset($element['elements'])) {
                $element['elements'] = $this->inject_color_to_elements($element['elements'], $color);
            }
        }
        
        return $elements;
    }
    
    private function darken_color($hex, $percent) {
        // Remove # if present
        $hex = str_replace('#', '', $hex);
        
        // Convert to RGB
        $r = hexdec(substr($hex, 0, 2));
        $g = hexdec(substr($hex, 2, 2));
        $b = hexdec(substr($hex, 4, 2));
        
        // Darken by percentage
        $r = max(0, $r - ($r * $percent / 100));
        $g = max(0, $g - ($g * $percent / 100));
        $b = max(0, $b - ($b * $percent / 100));
        
        // Convert back to hex
        return '#' . str_pad(dechex($r), 2, '0', STR_PAD_LEFT) . 
                     str_pad(dechex($g), 2, '0', STR_PAD_LEFT) . 
                     str_pad(dechex($b), 2, '0', STR_PAD_LEFT);
    }
    
    private function set_logo( $logo_url ) {

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

        $image_data = null;
        $mime_type = 'image/png';

        // Handle base64 data URL (from Step 3 preview)
        if ( strpos( $logo_url, 'data:image' ) === 0 ) {
            // Extract MIME type and base64 data
            if ( preg_match( '/^data:image\/(\w+);base64,(.*)$/', $logo_url, $matches ) ) {
                $mime_type = 'image/' . $matches[1];
                $image_data = base64_decode( $matches[2], true );
            }
        } else {
            // Handle regular URL
            $response = wp_remote_get(
                esc_url_raw( $logo_url ),
                array(
                    'timeout'   => 15,
                    'sslverify' => true,
                )
            );

            if ( is_wp_error( $response ) ) {
                return;
            }

            $image_data = wp_remote_retrieve_body( $response );
        }

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

        // Upload directory
        $upload_dir = wp_upload_dir();
        $extension = 'png';

        if ( strpos( $mime_type, 'jpeg' ) !== false || strpos( $mime_type, 'jpg' ) !== false ) {
            $extension = 'jpg';
        } elseif ( strpos( $mime_type, 'gif' ) !== false ) {
            $extension = 'gif';
        } elseif ( strpos( $mime_type, 'webp' ) !== false ) {
            $extension = 'webp';
        }

        $filename = 'turbo-logo-' . time() . '.' . $extension;

        if ( wp_mkdir_p( $upload_dir['path'] ) ) {
            $file = trailingslashit( $upload_dir['path'] ) . $filename;
        } else {
            $file = trailingslashit( $upload_dir['basedir'] ) . $filename;
        }

        // Save image safely
        if ( file_put_contents( $file, $image_data ) === false ) {
            return;
        }

        // Prepare attachment
        $attachment = array(
            'post_mime_type' => $mime_type,
            'post_title'     => __( 'Turbo Logo', 'turbo-templates-library-for-elementor' ),
            'post_content'   => '',
            'post_status'    => 'inherit',
        );

        $attach_id = wp_insert_attachment( $attachment, $file );

        if ( ! $attach_id ) {
            return;
        }

        require_once ABSPATH . 'wp-admin/includes/image.php';

        $attach_data = wp_generate_attachment_metadata( $attach_id, $file );
        wp_update_attachment_metadata( $attach_id, $attach_data );

        // Set as site logo
        set_theme_mod( 'custom_logo', $attach_id );
    }

    private function import_elementor_images($elementor_data) {
        if (!is_array($elementor_data)) {
            return $elementor_data;
        }
        
        // error_log('Starting image import for Elementor data with ' . count($elementor_data) . ' sections');
        
        foreach ($elementor_data as &$section) {
            if (isset($section['elements'])) {
                $section['elements'] = $this->process_elements_for_images($section['elements']);
            }
            if (isset($section['settings'])) {
                $section['settings'] = $this->process_settings_for_images($section['settings']);
            }
        }
        
        // error_log('Completed image import for Elementor data');
        return $elementor_data;
    }
    
    private function process_elements_for_images($elements) {
        foreach ($elements as &$element) {
            if (isset($element['settings'])) {
                $element['settings'] = $this->process_settings_for_images($element['settings']);
            }
            if (isset($element['elements'])) {
                $element['elements'] = $this->process_elements_for_images($element['elements']);
            }
        }
        return $elements;
    }
    
    private function process_settings_for_images($settings) {
        foreach ($settings as $key => &$value) {
            // Handle Elementor background_image / image array: { "url": "...", "id": "" }
            if (
                is_array($value) &&
                isset($value['url']) &&
                is_string($value['url']) &&
                $this->is_demo_image_url($value['url'])
            ) {
                // error_log('Processing Elementor image array for key: ' . $key . ' url: ' . $value['url']);
                $imported = $this->import_image_with_id($value['url']);
                if ($imported['url'] && $imported['url'] !== $value['url']) {
                    $value['url'] = $imported['url'];
                    $value['id']  = $imported['id'] ?: '';
                    // error_log('Replaced image array url with: ' . $imported['url'] . ' (id: ' . $value['id'] . ')');
                }
            } elseif (is_string($value) && $this->is_demo_image_url($value)) {
                // error_log('Processing image URL: ' . $value);
                $local_image = $this->import_image_to_media_library($value);
                if ($local_image && $local_image !== $value) {
                    $value = $local_image;
                    // error_log('Replaced with local image: ' . $local_image);
                }
            } elseif (is_array($value)) {
                $value = $this->process_settings_for_images($value);
            }
        }
        return $settings;
    }
    
    private function is_demo_image_url($url) {
        if (!is_string($url) || empty($url)) {
            return false;
        }
        
        $demo_domains = array(
            'demo.turbo-addons.com',
            'templates.wp-turbo.com',
            'turbo-addons.com'
        );
        
        $image_extensions = array('.jpg', '.jpeg', '.png', '.gif', '.webp', '.svg');
        
        foreach ($demo_domains as $domain) {
            if (strpos($url, $domain) !== false) {
                foreach ($image_extensions as $ext) {
                    if (strpos($url, $ext) !== false) {
                        return true;
                    }
                }
            }
        }
        
        return false;
    }
    
    private function create_basic_page($title) {
        $slug = sanitize_title($title);
        
        // Create a basic page with minimal Elementor content
        $page_data = array(
            'post_title' => $title,
            'post_content' => '',
            'post_status' => 'publish',
            'post_type' => 'page',
            'post_name' => $slug
        );
        
        $page_id = wp_insert_post($page_data);
        
        if ($page_id && !is_wp_error($page_id)) {
            // Add basic Elementor structure
            $basic_elementor_data = array(
                array(
                    'id' => 'basic-section',
                    'elType' => 'section',
                    'settings' => array(
                        'padding' => array('top' => '80', 'bottom' => '80')
                    ),
                    'elements' => array(
                        array(
                            'id' => 'basic-column',
                            'elType' => 'column',
                            'settings' => array('_column_size' => 100),
                            'elements' => array(
                                array(
                                    'id' => 'basic-heading',
                                    'elType' => 'widget',
                                    'widgetType' => 'heading',
                                    'settings' => array(
                                        'title' => $title,
                                        'size' => 'xl',
                                        'align' => 'center'
                                    )
                                ),
                                array(
                                    'id' => 'basic-text',
                                    'elType' => 'widget',
                                    'widgetType' => 'text-editor',
                                    'settings' => array(
                                        'editor' => '<p style="text-align: center;">This page was created from template. Content will be added soon.</p>'
                                    )
                                )
                            )
                        )
                    )
                )
            );
            
            update_post_meta($page_id, '_elementor_data', wp_slash(wp_json_encode($basic_elementor_data)));
            update_post_meta($page_id, '_elementor_edit_mode', 'builder');
            update_post_meta($page_id, '_elementor_template_type', 'wp-page');
            update_post_meta($page_id, '_elementor_version', '3.18.0');
            update_post_meta($page_id, '_wp_page_template', 'default');
            update_post_meta($page_id, '_hide_title', 'yes');
            // Force these as arrays, not JSON strings
            delete_post_meta($page_id, '_elementor_page_settings');
            delete_post_meta($page_id, '_elementor_page_assets');
            delete_post_meta($page_id, '_elementor_controls_usage');
            add_post_meta($page_id, '_elementor_page_settings', array( 'hide_title' => 'yes' ), true);
            add_post_meta($page_id, '_elementor_page_assets', array(), true);
            add_post_meta($page_id, '_elementor_controls_usage', array(), true);
            
            return $page_id;
        }
        
        return false;
    }
    

    
    private function import_image_with_id($image_url) {
        static $imported_images = array();
        if (isset($imported_images[$image_url])) {
            return $imported_images[$image_url];
        }

        if (!$this->is_valid_image_url($image_url)) {
            return array('url' => $this->get_placeholder_image(), 'id' => '');
        }

        $upload_dir = wp_upload_dir();
        $image_data = wp_remote_get($image_url, array(
            'timeout' => 30,
            'headers' => array(
                'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
                'Referer' => 'https://unsplash.com/'
            )
        ));

        if (is_wp_error($image_data) || wp_remote_retrieve_response_code($image_data) !== 200) {
            return array('url' => $this->get_placeholder_image(), 'id' => '');
        }

        $image_content = wp_remote_retrieve_body($image_data);
        if (empty($image_content)) {
            return array('url' => $this->get_placeholder_image(), 'id' => '');
        }

        // Detect extension from URL
        $ext = 'jpg';
        foreach (array('webp','png','gif','svg','jpeg','jpg') as $e) {
            if (strpos($image_url, '.' . $e) !== false) { $ext = $e; break; }
        }
        $mime_map = array('jpg'=>'image/jpeg','jpeg'=>'image/jpeg','png'=>'image/png','gif'=>'image/gif','webp'=>'image/webp','svg'=>'image/svg+xml');
        $mime = $mime_map[$ext] ?? 'image/jpeg';

        $filename = 'turbo-' . time() . '-' . wp_rand(1000, 9999) . '.' . $ext;
        $file = $upload_dir['path'] . '/' . $filename;
        $url  = $upload_dir['url']  . '/' . $filename;

        if (!wp_mkdir_p($upload_dir['path'])) {
            $file = $upload_dir['basedir'] . '/' . $filename;
            $url  = $upload_dir['baseurl'] . '/' . $filename;
        }

        if (file_put_contents($file, $image_content) === false) {
            return array('url' => $this->get_placeholder_image(), 'id' => '');
        }

        $attach_id = wp_insert_attachment(array(
            'post_mime_type' => $mime,
            'post_title'     => 'Turbo Template Image',
            'post_content'   => '',
            'post_status'    => 'inherit'
        ), $file);

        if (!is_wp_error($attach_id)) {
            require_once ABSPATH . 'wp-admin/includes/image.php';
            wp_update_attachment_metadata($attach_id, wp_generate_attachment_metadata($attach_id, $file));
        } else {
            $attach_id = '';
        }

        $result = array('url' => $url, 'id' => $attach_id);
        $imported_images[$image_url] = $result;
        // error_log('import_image_with_id: ' . $image_url . ' -> ' . $url . ' id=' . $attach_id);
        return $result;
    }

    private function import_image_to_media_library($image_url) {
        // Check if already imported
        static $imported_images = array();
        if (isset($imported_images[$image_url])) {
            return $imported_images[$image_url]['url'] ?? $imported_images[$image_url];
        }
        
        // Skip if not a valid image URL
        if (!$this->is_valid_image_url($image_url)) {
            return $this->get_placeholder_image(); // Return placeholder instead
        }
        
        $upload_dir = wp_upload_dir();
        $image_data = wp_remote_get($image_url, array(
            'timeout' => 30,
            'headers' => array(
                'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
                'Referer' => 'https://unsplash.com/'
            )
        ));
        
        if (is_wp_error($image_data) || wp_remote_retrieve_response_code($image_data) !== 200) {
            // error_log('Failed to fetch image: ' . $image_url);
            return $this->get_placeholder_image(); // Return placeholder as fallback
        }
        
        $image_content = wp_remote_retrieve_body($image_data);
        if (empty($image_content)) {
            return $this->get_placeholder_image();
        }
        
        $filename = 'turbo-' . time() . '-' . wp_rand(1000, 9999) . '.jpg';
        
        if (wp_mkdir_p($upload_dir['path'])) {
            $file = $upload_dir['path'] . '/' . $filename;
            $url = $upload_dir['url'] . '/' . $filename;
        } else {
            $file = $upload_dir['basedir'] . '/' . $filename;
            $url = $upload_dir['baseurl'] . '/' . $filename;
        }
        
        $result = file_put_contents($file, $image_content);
        if ($result === false) {
            // error_log('Failed to write image file: ' . $file);
            return $this->get_placeholder_image();
        }
        
        $attachment = array(
            'post_mime_type' => 'image/jpeg',
            'post_title' => 'Turbo Template Image',
            'post_content' => '',
            'post_status' => 'inherit'
        );
        
        $attach_id = wp_insert_attachment($attachment, $file);
        if (is_wp_error($attach_id)) {
            // error_log('Failed to create attachment: ' . $attach_id->get_error_message());
            return $this->get_placeholder_image();
        }
        
        require_once(ABSPATH . 'wp-admin/includes/image.php');
        $attach_data = wp_generate_attachment_metadata($attach_id, $file);
        wp_update_attachment_metadata($attach_id, $attach_data);
        
        $imported_images[$image_url] = array( 'url' => $url, 'id' => $attach_id );
        // error_log('Successfully imported image: ' . $image_url . ' -> ' . $url . ' (id: ' . $attach_id . ')');
        
        return $url;
    }
    
    private function is_valid_image_url($url) {
        if (empty($url) || !is_string($url)) {
            return false;
        }
        
        return (strpos($url, 'unsplash.com') !== false || 
                strpos($url, 'demo.turbo-addons.com') !== false ||
                strpos($url, 'templates.wp-turbo.com') !== false ||
                strpos($url, 'pixabay.com') !== false ||
                strpos($url, 'pexels.com') !== false) &&
               (strpos($url, '.jpg') !== false || 
                strpos($url, '.jpeg') !== false || 
                strpos($url, '.png') !== false || 
                strpos($url, '.webp') !== false ||
                strpos($url, '.svg') !== false);
    }
    
    private function get_placeholder_image() {
        // Return a data URL for a simple placeholder image
        return 'data:image/svg+xml;base64,' . base64_encode('<svg width="400" height="300" xmlns="http://www.w3.org/2000/svg"><rect width="100%" height="100%" fill="#f0f0f0"/><text x="50%" y="50%" font-family="Arial, sans-serif" font-size="16" fill="#999" text-anchor="middle" dy=".3em">Image Placeholder</text></svg>');
    }
    
    private function fix_existing_elementor_pages() {
        // error_log('Fixing existing Elementor pages meta fields...');
        
        $pages = get_pages(array('meta_key' => '_elementor_edit_mode'));
        
        foreach ($pages as $page) {
            // Check if meta fields are strings instead of arrays
            $page_assets = get_post_meta($page->ID, '_elementor_page_assets', true);
            $page_settings = get_post_meta($page->ID, '_elementor_page_settings', true);
            $controls_usage = get_post_meta($page->ID, '_elementor_controls_usage', true);
            
            // Fix if they are strings
            if (is_string($page_assets)) {
                delete_post_meta($page->ID, '_elementor_page_assets');
                add_post_meta($page->ID, '_elementor_page_assets', array(), true);
                // error_log('Fixed _elementor_page_assets for page ' . $page->ID);
            }
            
            if (is_string($page_settings)) {
                delete_post_meta($page->ID, '_elementor_page_settings');
                add_post_meta($page->ID, '_elementor_page_settings', array( 'hide_title' => 'yes' ), true);
                // error_log('Fixed _elementor_page_settings for page ' . $page->ID);
            }
            
            if (is_string($controls_usage)) {
                delete_post_meta($page->ID, '_elementor_controls_usage');
                add_post_meta($page->ID, '_elementor_controls_usage', array(), true);
                // error_log('Fixed _elementor_controls_usage for page ' . $page->ID);
            }
        }
        
        // error_log('Finished fixing existing Elementor pages');
    }
    
    private function fix_page_templates() {
        // error_log('Fixing page templates for Elementor pages...');
        
        $pages = get_pages(array('meta_key' => '_elementor_edit_mode'));
        
        foreach ($pages as $page) {
            update_post_meta($page->ID, '_wp_page_template', 'default');
            update_post_meta($page->ID, '_hide_title', 'yes');
            update_post_meta($page->ID, '_page_template', 'default');
            // error_log('Fixed template for page ' . $page->ID . ': ' . $page->post_title);
        }
        
        // error_log('Finished fixing page templates');
    }
    
    private function clear_all_caches() {
        // Clear WordPress object cache
        wp_cache_flush();
        
        // Clear Elementor cache
        if (class_exists('\Elementor\Plugin')) {
            \Elementor\Plugin::$instance->files_manager->clear_cache();
        }
        
        // Clear any other caches
        if (function_exists('wp_cache_clear_cache')) {
            wp_cache_clear_cache();
        }
        
        // error_log('Cleared all caches after template import');
    }
    
    private function debug_homepage_status() {
        $front_page_id = get_option('page_on_front');
        $show_on_front = get_option('show_on_front');
        
        // error_log('=== HOMEPAGE DEBUG ===');
        // error_log('show_on_front: ' . $show_on_front);
        // error_log('page_on_front: ' . $front_page_id);
        
        if ($front_page_id) {
            $page = get_post($front_page_id);
            if ($page) {
                // error_log('Homepage title: ' . $page->post_title);
                // error_log('Homepage status: ' . $page->post_status);
                // error_log('Homepage slug: ' . $page->post_name);
                
                $elementor_data = get_post_meta($front_page_id, '_elementor_data', true);
                // error_log('Has Elementor data: ' . (empty($elementor_data) ? 'NO' : 'YES'));
                // error_log('Elementor data length: ' . strlen($elementor_data));
                
                // Debug actual Elementor data content
                if (!empty($elementor_data)) {
                    $decoded_data = json_decode($elementor_data, true);
                    if ($decoded_data) {
                        // error_log('Elementor sections count: ' . count($decoded_data));
                        // error_log('First section type: ' . (isset($decoded_data[0]['elType']) ? $decoded_data[0]['elType'] : 'unknown'));
                    } else {
                        // error_log('ERROR: Elementor data is not valid JSON');
                    }
                }
            } else {
                // error_log('ERROR: Homepage page not found!');
            }
        } else {
            // error_log('ERROR: No homepage set!');
        }
        
        // error_log('Site URL: ' . home_url());
        // error_log('=== END HOMEPAGE DEBUG ===');
    }
    
    private function force_elementor_recognition($pages_created) {
        if (class_exists('\Elementor\Plugin')) {
            foreach ($pages_created as $page_id) {
                // Force Elementor to rebuild page
                \Elementor\Plugin::$instance->db->set_is_elementor_page($page_id, true);
                
                // Generate CSS file
                \Elementor\Core\Files\CSS\Post::create($page_id)->update();
                
                // error_log('Forced Elementor recognition for page: ' . $page_id);
            }
        }
    }
    
    private function force_theme_elementor_support() {
        // Force any theme to load Elementor content properly
        add_action('wp_head', function() {
            if (is_front_page() && class_exists('\Elementor\Plugin')) {
                $page_id = get_queried_object_id();
                if (get_post_meta($page_id, '_elementor_edit_mode', true)) {
                    // Force Elementor to load its CSS and JS
                    \Elementor\Plugin::$instance->frontend->enqueue_styles();
                    \Elementor\Plugin::$instance->frontend->enqueue_scripts();
                }
            }
        });
        
        // Override page template for Elementor pages
        add_filter('page_template', function($template) {
            if (is_front_page() && class_exists('\Elementor\Plugin')) {
                $page_id = get_queried_object_id();
                if (get_post_meta($page_id, '_elementor_edit_mode', true)) {
                    // Use Elementor canvas template
                    $elementor_template = ELEMENTOR_PATH . 'modules/page-templates/templates/canvas.php';
                    if (file_exists($elementor_template)) {
                        return $elementor_template;
                    }
                }
            }
            return $template;
        });
        
        // error_log('Forced universal theme Elementor support');
    }
    
    private function fetch_laravel_template_11() {
        // Try to fetch real template 11 from Laravel API
$json_url = 'https://templates.wp-turbo.com/storage/templates/json/cIQzy5xDF3hoyiU4F4eK1ZlPYGMNVUq1xAlOVDCH.txt';
        
        // error_log('Fetching real JSON from: ' . $json_url);
        
        $response = wp_remote_get($json_url, array(
            'timeout' => 30
        ));
        
        if (is_wp_error($response)) {
            // error_log('Laravel API error: ' . $response->get_error_message());
            return false;
        }
        
        $response_code = wp_remote_retrieve_response_code($response);
        if ($response_code !== 200) {
            // error_log('Laravel API returned status: ' . $response_code);
            return false;
        }
        
        $json_content = wp_remote_retrieve_body($response);
        if (empty($json_content)) {
            // error_log('Empty JSON content from Laravel API');
            return false;
        }
        
        // error_log('Laravel JSON content length: ' . strlen($json_content));
        
        // For single page templates, extract content array if nested
        $decoded = json_decode($json_content, true);
        if (!$decoded) {
            // error_log('Invalid JSON from Laravel API');
            return false;
        }
        
        // Check if JSON has nested content structure (Laravel format)
        if (isset($decoded['content']) && is_array($decoded['content'])) {
            // error_log('Found nested content structure, extracting...');
            $decoded = $decoded['content'];
            $json_content = json_encode($decoded);
        }
        
        // error_log('Final JSON elements count: ' . (is_array($decoded) ? count($decoded) : 0));
        // error_log('Final JSON length: ' . strlen($json_content));
        
        // Return in expected format
        return array(
            'id' => 11,
            'name' => 'AGRO TEMPLATE 2025',
            'templates' => array(
                array(
                    'name' => 'Home',
                    'slug' => 'home',
                    'json_data' => $json_content
                )
            )
        );
    }
    
    private function fix_elementor_json_structure($data) {
        if (!is_array($data)) {
            return json_encode(array());
        }
        
        $fixed_data = array();
        
        foreach ($data as $element) {
            if (is_array($element)) {
                // Ensure required Elementor fields exist
                if (!isset($element['elType'])) {
                    $element['elType'] = 'section';
                }
                if (!isset($element['id'])) {
                    $element['id'] = 'element-' . uniqid();
                }
                
                // Fix nested elements
                if (isset($element['elements']) && is_array($element['elements'])) {
                    $element['elements'] = $this->fix_nested_elements($element['elements']);
                }
                
                $fixed_data[] = $element;
            }
        }
        
        // error_log('Fixed JSON structure, elements: ' . count($fixed_data));
        return json_encode($fixed_data);
    }
    
    private function fix_nested_elements($elements) {
        $fixed = array();
        
        foreach ($elements as $index => $element) {
            if (is_array($element)) {
                if (!isset($element['elType'])) {
                    $element['elType'] = 'column';
                }
                if (!isset($element['id'])) {
                    $element['id'] = 'element-' . ($index + 1);
                }
                
                if (isset($element['elements']) && is_array($element['elements'])) {
                    $element['elements'] = $this->fix_nested_elements($element['elements']);
                }
                
                $fixed[] = $element;
            }
        }
        
        return $fixed;
    }
    
    private function is_valid_elementor_structure($data) {
        if (!is_array($data) || empty($data)) {
            return false;
        }
        
        // Check if at least one element has required Elementor fields
        foreach ($data as $element) {
            if (is_array($element) && isset($element['elType'])) {
                return true;
            }
        }
        
        return false;
    }
    
    private function fix_elementor_structure($data) {
        if (!is_array($data)) {
            return array();
        }
        
        $fixed_data = array();
        
        foreach ($data as $index => $element) {
            if (is_array($element)) {
                // Ensure required Elementor fields
                if (!isset($element['elType'])) {
                    $element['elType'] = 'section';
                }
                if (!isset($element['id'])) {
                    $element['id'] = 'section-' . ($index + 1);
                }
                
                // Fix nested elements
                if (isset($element['elements']) && is_array($element['elements'])) {
                    $element['elements'] = $this->fix_nested_elements($element['elements']);
                }
                
                $fixed_data[] = $element;
            }
        }
        
        return $fixed_data;
    }
    
    private function create_fallback_page($title, $slug, $is_front_page = false) {
        // error_log('Creating fallback page for: ' . $title);
        
        // Create page with working Elementor structure
        $page_data = array(
            'post_title' => $title,
            'post_content' => '',
            'post_status' => 'publish',
            'post_type' => 'page',
            'post_name' => $slug,
            'post_author' => get_current_user_id()
        );
        
        $page_id = wp_insert_post($page_data);
        
        if ($page_id && !is_wp_error($page_id)) {
            // error_log('Created fallback page successfully: ' . $page_id);
            
            // Add comprehensive Elementor structure with multiple sections
            $fallback_data = array(
                // Hero Section
                array(
                    'id' => 'hero-section-' . $page_id,
                    'elType' => 'section',
                    'settings' => array(
                        'background_background' => 'gradient',
                        'background_color' => '#667eea',
                        'background_color_b' => '#764ba2',
                        'padding' => array('top' => '100', 'bottom' => '100', 'unit' => 'px')
                    ),
                    'elements' => array(
                        array(
                            'id' => 'hero-column-' . $page_id,
                            'elType' => 'column',
                            'settings' => array('_column_size' => 100, 'width' => 100),
                            'elements' => array(
                                array(
                                    'id' => 'hero-heading-' . $page_id,
                                    'elType' => 'widget',
                                    'widgetType' => 'heading',
                                    'settings' => array(
                                        'title' => $title,
                                        'size' => 'xl',
                                        'color' => '#ffffff',
                                        'align' => 'center',
                                        'typography_typography' => 'custom',
                                        'typography_font_size' => array('size' => 48, 'unit' => 'px')
                                    )
                                ),
                                array(
                                    'id' => 'hero-text-' . $page_id,
                                    'elType' => 'widget',
                                    'widgetType' => 'text-editor',
                                    'settings' => array(
                                        'editor' => '<p style="text-align: center; color: #ffffff; font-size: 18px; margin-top: 20px;">Professional template imported successfully. Your website is ready for customization with Elementor.</p>',
                                        'align' => 'center'
                                    )
                                ),
                                array(
                                    'id' => 'hero-button-' . $page_id,
                                    'elType' => 'widget',
                                    'widgetType' => 'button',
                                    'settings' => array(
                                        'text' => 'Get Started',
                                        'align' => 'center',
                                        'background_color' => '#FF6B35',
                                        'button_text_color' => '#ffffff',
                                        'size' => 'lg'
                                    )
                                )
                            )
                        )
                    )
                ),
                // Content Section
                array(
                    'id' => 'content-section-' . $page_id,
                    'elType' => 'section',
                    'settings' => array(
                        'background_color' => '#f8f9fa',
                        'padding' => array('top' => '80', 'bottom' => '80', 'unit' => 'px')
                    ),
                    'elements' => array(
                        array(
                            'id' => 'content-column-' . $page_id,
                            'elType' => 'column',
                            'settings' => array('_column_size' => 100, 'width' => 100),
                            'elements' => array(
                                array(
                                    'id' => 'content-heading-' . $page_id,
                                    'elType' => 'widget',
                                    'widgetType' => 'heading',
                                    'settings' => array(
                                        'title' => 'Ready to Customize',
                                        'size' => 'large',
                                        'align' => 'center',
                                        'color' => '#333333'
                                    )
                                ),
                                array(
                                    'id' => 'content-text-' . $page_id,
                                    'elType' => 'widget',
                                    'widgetType' => 'text-editor',
                                    'settings' => array(
                                        'editor' => '<div style="max-width: 800px; margin: 0 auto; text-align: center;"><p>Your template has been successfully imported and is ready for customization. You can now edit this page with Elementor to add your own content, images, and styling.</p><p><strong>Next Steps:</strong></p><ul style="text-align: left; display: inline-block;"><li>Click "Edit with Elementor" to customize this page</li><li>Add your own content and images</li><li>Customize colors and fonts to match your brand</li><li>Create additional pages as needed</li></ul></div>'
                                    )
                                )
                            )
                        )
                    )
                )
            );
            
            // Save Elementor data with proper meta fields
            update_post_meta($page_id, '_elementor_data', wp_slash(wp_json_encode($fallback_data)));
            update_post_meta($page_id, '_elementor_edit_mode', 'builder');
            update_post_meta($page_id, '_elementor_template_type', 'wp-page');
            update_post_meta($page_id, '_elementor_version', '3.18.0');
            update_post_meta($page_id, '_wp_page_template', 'default');
            update_post_meta($page_id, '_hide_title', 'yes');
            update_post_meta($page_id, '_page_template', 'default');
            
            // Force proper array meta fields (not JSON strings)
            delete_post_meta($page_id, '_elementor_page_settings');
            delete_post_meta($page_id, '_elementor_page_assets');
            delete_post_meta($page_id, '_elementor_controls_usage');
            add_post_meta($page_id, '_elementor_page_settings', array( 'hide_title' => 'yes' ), true);
            add_post_meta($page_id, '_elementor_page_assets', array(), true);
            add_post_meta($page_id, '_elementor_controls_usage', array(), true);
            
            if ($is_front_page) {
                $this->set_as_homepage($page_id);
            }
            
            // error_log('Created fallback page successfully: ' . $page_id);
        }
        
        return $page_id;
    }
    
    private function get_agro_template_data() {
        // Real AGRO template data with turbo-addons widgets
        return array(
            'id' => 11,
            'name' => 'AGRO TEMPLATE 2025',
            'templates' => array(
                array(
                    'name' => 'Home',
                    'slug' => 'home',
                    'json_data' => $this->get_real_agro_json()
                )
            )
        );
    }
    
    private function get_portfolio_template_json() {

        // ✅ Local placeholder image (NO remote images – WP.org safe)
        $placeholder = TRSTEMP_URI . 'assets/images/placeholder.png';

        return json_encode( array(

            /* ================= HERO SECTION ================= */
            array(
                'id'     => 'portfolio-hero',
                'elType' => 'section',
                'settings' => array(
                    'background_background' => 'classic',
                    'background_image' => array(
                        'url' => $placeholder
                    ),
                    'background_overlay_background' => 'classic',
                    'background_overlay_color' => 'rgba(0,0,0,0.5)',
                    'padding' => array(
                        'top'    => '150',
                        'bottom' => '150',
                    ),
                ),
                'elements' => array(
                    array(
                        'id'     => 'hero-column',
                        'elType' => 'column',
                        'settings' => array( '_column_size' => 100 ),
                        'elements' => array(
                            array(
                                'id'         => 'hero-heading',
                                'elType'     => 'widget',
                                'widgetType'=> 'heading',
                                'settings'  => array(
                                    'title' => 'I am a freelance product designer',
                                    'size'  => 'xl',
                                    'color' => '#ffffff',
                                    'align' => 'center',
                                ),
                            ),
                            array(
                                'id'         => 'hero-subtitle',
                                'elType'     => 'widget',
                                'widgetType'=> 'heading',
                                'settings'  => array(
                                    'title' => "Let's work together",
                                    'size'  => 'large',
                                    'color' => '#ffffff',
                                    'align' => 'center',
                                ),
                            ),
                            array(
                                'id'         => 'hero-button',
                                'elType'     => 'widget',
                                'widgetType'=> 'button',
                                'settings'  => array(
                                    'text'             => 'View My Work',
                                    'align'            => 'center',
                                    'background_color' => '#FF6B35',
                                ),
                            ),
                        ),
                    ),
                ),
            ),

            /* ================= ABOUT SECTION ================= */
            array(
                'id'     => 'portfolio-about',
                'elType' => 'section',
                'settings' => array(
                    'padding' => array(
                        'top'    => '80',
                        'bottom' => '80',
                    ),
                ),
                'elements' => array(
                    array(
                        'id'     => 'about-column',
                        'elType' => 'column',
                        'settings' => array( '_column_size' => 50 ),
                        'elements' => array(
                            array(
                                'id'         => 'about-image',
                                'elType'     => 'widget',
                                'widgetType'=> 'image',
                                'settings'  => array(
                                    'image' => array(
                                        'url' => $placeholder,
                                    ),
                                ),
                            ),
                        ),
                    ),
                    array(
                        'id'     => 'about-content',
                        'elType' => 'column',
                        'settings' => array( '_column_size' => 50 ),
                        'elements' => array(
                            array(
                                'id'         => 'about-heading',
                                'elType'     => 'widget',
                                'widgetType'=> 'heading',
                                'settings'  => array(
                                    'title' => 'About Me',
                                    'size'  => 'large',
                                ),
                            ),
                            array(
                                'id'         => 'about-text',
                                'elType'     => 'widget',
                                'widgetType'=> 'text-editor',
                                'settings'  => array(
                                    'editor' =>
                                        '<p>I am a passionate product designer with over 5 years of experience creating digital experiences that users love.</p>
                                        <p>My approach combines creativity with data-driven insights to deliver designs that not only look great but also perform exceptionally well.</p>',
                                ),
                            ),
                        ),
                    ),
                ),
            ),

            /* ================= GALLERY SECTION ================= */
            array(
                'id'     => 'portfolio-gallery',
                'elType' => 'section',
                'settings' => array(
                    'background_color' => '#f8f9fa',
                    'padding' => array(
                        'top'    => '80',
                        'bottom' => '80',
                    ),
                ),
                'elements' => array(
                    array(
                        'id'     => 'gallery-column',
                        'elType' => 'column',
                        'settings' => array( '_column_size' => 100 ),
                        'elements' => array(
                            array(
                                'id'         => 'gallery-heading',
                                'elType'     => 'widget',
                                'widgetType'=> 'heading',
                                'settings'  => array(
                                    'title' => 'My Recent Work',
                                    'size'  => 'large',
                                    'align' => 'center',
                                ),
                            ),
                            array(
                                'id'         => 'gallery-grid',
                                'elType'     => 'widget',
                                'widgetType'=> 'text-editor',
                                'settings'  => array(
                                    'editor' =>
                                        '<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(300px,1fr));gap:30px;margin-top:40px;">'

                                        . '<div style="background:#fff;border-radius:10px;overflow:hidden;box-shadow:0 4px 15px rgba(0,0,0,0.1);">'
                                        . '<img src="' . esc_url( $placeholder ) . '" style="width:100%;height:200px;object-fit:cover;">'
                                        . '<div style="padding:20px;"><h3>Mobile App Design</h3><p>E-commerce mobile application with modern UI</p></div>'
                                        . '</div>'

                                        . '<div style="background:#fff;border-radius:10px;overflow:hidden;box-shadow:0 4px 15px rgba(0,0,0,0.1);">'
                                        . '<img src="' . esc_url( $placeholder ) . '" style="width:100%;height:200px;object-fit:cover;">'
                                        . '<div style="padding:20px;"><h3>Dashboard Design</h3><p>Analytics dashboard for business intelligence</p></div>'
                                        . '</div>'

                                        . '<div style="background:#fff;border-radius:10px;overflow:hidden;box-shadow:0 4px 15px rgba(0,0,0,0.1);">'
                                        . '<img src="' . esc_url( $placeholder ) . '" style="width:100%;height:200px;object-fit:cover;">'
                                        . '<div style="padding:20px;"><h3>Website Redesign</h3><p>Complete website redesign for tech startup</p></div>'
                                        . '</div>'

                                        . '</div>',
                                ),
                            ),
                        ),
                    ),
                ),
            ),

        ) );
    }

    private function get_real_agro_json() {
        // Real Elementor JSON with turbo-addons widgets
        return json_encode(array(
            array(
                'id' => 'agro-hero',
                'elType' => 'section',
                'settings' => array(
                    'background_background' => 'gradient',
                    'background_color' => '#2E7D32',
                    'background_color_b' => '#4CAF50',
                    'padding' => array('top' => '120', 'bottom' => '120')
                ),
                'elements' => array(
                    array(
                        'id' => 'agro-column',
                        'elType' => 'column',
                        'settings' => array('_column_size' => 100),
                        'elements' => array(
                            array(
                                'id' => 'agro-heading',
                                'elType' => 'widget',
                                'widgetType' => 'trad-heading',
                                'settings' => array(
                                    'title' => 'Leading Agricultural Solutions for Modern Farming',
                                    'title_color' => '#ffffff',
                                    'typography_typography' => 'custom',
                                    'typography_font_size' => array('size' => 48, 'unit' => 'px'),
                                    'typography_font_weight' => '700',
                                    'align' => 'center'
                                )
                            ),
                            array(
                                'id' => 'agro-subtitle',
                                'elType' => 'widget',
                                'widgetType' => 'trad-text',
                                'settings' => array(
                                    'text' => 'We are a forward-thinking agricultural company committed to transforming farming through innovation and sustainability.',
                                    'text_color' => '#ffffff',
                                    'typography_font_size' => array('size' => 18, 'unit' => 'px'),
                                    'align' => 'center'
                                )
                            ),
                            array(
                                'id' => 'agro-button',
                                'elType' => 'widget',
                                'widgetType' => 'trad-button',
                                'settings' => array(
                                    'text' => 'Explore Our Solutions',
                                    'button_background_color' => '#FF6B35',
                                    'button_text_color' => '#ffffff',
                                    'align' => 'center',
                                    'size' => 'lg'
                                )
                            )
                        )
                    )
                )
            ),
            array(
                'id' => 'agro-services',
                'elType' => 'section',
                'settings' => array(
                    'background_color' => '#f8f9fa',
                    'padding' => array('top' => '80', 'bottom' => '80')
                ),
                'elements' => array(
                    array(
                        'id' => 'services-column',
                        'elType' => 'column',
                        'settings' => array('_column_size' => 100),
                        'elements' => array(
                            array(
                                'id' => 'services-heading',
                                'elType' => 'widget',
                                'widgetType' => 'trad-heading',
                                'settings' => array(
                                    'title' => 'Our Agricultural Services',
                                    'align' => 'center',
                                    'typography_font_size' => array('size' => 36, 'unit' => 'px')
                                )
                            ),
                            array(
                                'id' => 'services-grid',
                                'elType' => 'widget',
                                'widgetType' => 'trad-service-box',
                                'settings' => array(
                                    'services' => array(
                                        array(
                                            'title' => 'Crop Management',
                                            'description' => 'Advanced crop management solutions for maximum yield',
                                            'icon' => 'fas fa-seedling'
                                        ),
                                        array(
                                            'title' => 'Soil Analysis',
                                            'description' => 'Comprehensive soil testing and analysis services',
                                            'icon' => 'fas fa-microscope'
                                        ),
                                        array(
                                            'title' => 'Equipment Supply',
                                            'description' => 'Modern farming equipment and machinery',
                                            'icon' => 'fas fa-tractor'
                                        )
                                    )
                                )
                            )
                        )
                    )
                )
            )
        ));
    }
    
    private function regenerate_elementor_css() {
        if (class_exists('\Elementor\Plugin')) {
            try {
                // Clear Elementor cache
                \Elementor\Plugin::$instance->files_manager->clear_cache();
                
                // Regenerate CSS for all pages with error handling
                $pages = get_pages(array('meta_key' => '_elementor_edit_mode'));
                foreach ($pages as $page) {
                    try {
                        \Elementor\Core\Files\CSS\Post::create($page->ID)->update();
                        // error_log('CSS regenerated for page: ' . $page->ID);
                    } catch (Exception $e) {
                        // error_log('CSS regeneration failed for page ' . $page->ID . ': ' . $e->getMessage());
                    }
                }
                
                // Force global CSS regeneration
                \Elementor\Plugin::$instance->files_manager->clear_cache();
                
                // error_log('Regenerated Elementor CSS for ' . count($pages) . ' pages');
            } catch (Exception $e) {
                // error_log('Elementor CSS regeneration error: ' . $e->getMessage());
            }
        } else {
            // error_log('Elementor not available for CSS regeneration');
        }
    }
    
    private function check_plugin_dependencies() {
        // Check if turbo-addons-elementor is installed
        if (!file_exists(WP_PLUGIN_DIR . '/turbo-addons-elementor/turbo-addons-elementor.php')) {
            return array(
                'success' => false,
                'message' => 'This template requires Turbo Addons Elementor plugin. Please install it first.',
                'action' => 'install_plugin',
                'plugin' => 'turbo-addons-elementor'
            );
        }
        
        // Check if turbo-addons-elementor is active
        if (!is_plugin_active('turbo-addons-elementor/turbo-addons-elementor.php')) {
            return array(
                'success' => false,
                'message' => 'This template requires Turbo Addons Elementor plugin to be active. Please activate it first.',
                'action' => 'activate_plugin',
                'plugin' => 'turbo-addons-elementor/turbo-addons-elementor.php'
            );
        }
        
        return array('success' => true);
    }
    
    private function set_as_homepage($page_id) {
        // error_log('Setting page as homepage: ' . $page_id);
        
        // Multiple methods to ensure homepage is set
        update_option('show_on_front', 'page');
        update_option('page_on_front', $page_id);
        set_theme_mod('page_on_front', $page_id);
        
        // Force database update
        global $wpdb;
        $wpdb->update(
            $wpdb->options,
            array('option_value' => $page_id),
            array('option_name' => 'page_on_front')
        );
        $wpdb->update(
            $wpdb->options,
            array('option_value' => 'page'),
            array('option_name' => 'show_on_front')
        );
        
        // Clear caches
        wp_cache_flush();
        flush_rewrite_rules();
        
        // error_log('Homepage set successfully');
    }
    
    private function verify_final_setup($page_id) {
        // error_log('=== FINAL SETUP VERIFICATION ===');
        
        // Check page exists and is published
        $page = get_post($page_id);
        if (!$page) {
            // error_log('ERROR: Page not found!');
            return false;
        }
        
        // error_log('Page status: ' . $page->post_status);
        // error_log('Page title: ' . $page->post_title);
        
        // Check homepage settings
        $front_page = get_option('page_on_front');
        $show_on_front = get_option('show_on_front');
        // error_log('page_on_front: ' . $front_page);
        // error_log('show_on_front: ' . $show_on_front);
        
        // Check Elementor data
        $elementor_data = get_post_meta($page_id, '_elementor_data', true);
        // error_log('Has Elementor data: ' . (!empty($elementor_data) ? 'YES' : 'NO'));
        if (!empty($elementor_data)) {
            $decoded = json_decode($elementor_data, true);
            // error_log('Elementor sections: ' . (is_array($decoded) ? count($decoded) : 0));
        }
        
        // Check page template
        $template = get_post_meta($page_id, '_wp_page_template', true);
        // error_log('Page template: ' . $template);
        
        // error_log('Site URL: ' . home_url());
        // error_log('=== END FINAL VERIFICATION ===');
        
        return true;
    }
    
    public function force_theme_compatibility() {
        // Hello Elementor theme should work perfectly with Elementor
        // Just ensure Elementor recognizes the pages properly
        add_action('init', function() {
            // Force Elementor to load properly on canvas pages
            add_action('wp_enqueue_scripts', function() {
                if (is_page() && class_exists('\Elementor\Plugin')) {
                    $page_id = get_queried_object_id();
                    if (get_post_meta($page_id, '_elementor_edit_mode', true)) {
                        \Elementor\Plugin::$instance->frontend->enqueue_styles();
                        \Elementor\Plugin::$instance->frontend->enqueue_scripts();
                    }
                }
            });
        });
        
        // error_log('Hello Elementor compatibility ensured');
    }
    
    private function replace_demo_urls_in_elementor_data($elementor_data) {
        if (!is_array($elementor_data)) {
            return $elementor_data;
        }
        
        $site_url = home_url();
        $demo_urls = array(
            'https://demo.turbo-addons.com',
            'https://templates.wp-turbo.com',
            'http://demo.turbo-addons.com',
            'http://templates.wp-turbo.com'
        );
        
        return $this->replace_urls_recursive($elementor_data, $demo_urls, $site_url);
    }
    
    private function replace_urls_recursive($data, $demo_urls, $site_url) {
        if (is_array($data)) {
            foreach ($data as $key => &$value) {
                $value = $this->replace_urls_recursive($value, $demo_urls, $site_url);
            }
        } elseif (is_string($data)) {
            // Replace demo URLs with local site URL
            foreach ($demo_urls as $demo_url) {
                $data = str_replace($demo_url, $site_url, $data);
            }
        }
        
        return $data;
    }
    
    public function __construct() {
        // Initialize theme compatibility on plugin load
        $this->force_theme_compatibility();
    }
}


