<?php
if ( ! defined( 'ABSPATH' ) ) exit;

/**
 * VMO Business Wizard Multi-Agent Handler
 * Comprehensive business consultant that gathers all necessary business information
 * and generates complete business websites with legal documents
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

class VMO_Business_Wizard {
    
    private $api_key;
    private $agents;
    private $business_questions;
    
    public function __construct() {
        $this->api_key = get_option('vmo_openai_api_key');
        $this->init_agents();
        $this->init_business_questions();
    }
    
    /**
     * Initialize comprehensive business consultation questions
     */
    private function init_business_questions() {
        $this->business_questions = [
            'business_basics' => [
                'What type of business are you creating the website for?',
                'What industry does your business operate in?',
                'What is the main purpose/goal of your business?',
                'Where is your business located? (City, State/Province, Country)',
                'What is your business name and do you have a tagline?'
            ],
            'target_market' => [
                'Who is your target audience? (Demographics, age group, interests)',
                'What geographic area do you serve? (Local, regional, national, international)',
                'What problems does your business solve for customers?',
                'How do your customers currently find businesses like yours?',
                'What is your ideal customer profile?'
            ],
            'business_model' => [
                'How does your business make money? (Services, products, subscriptions, etc.)',
                'What are your main products or services?',
                'What are your pricing strategies?',
                'Do you need online ordering/payment systems?',
                'Do you need appointment booking or reservation systems?'
            ],
            'goals_objectives' => [
                'What do you want visitors to do on your website? (Contact, buy, book, subscribe)',
                'What are your short-term business goals (next 6-12 months)?',
                'What are your long-term business goals (2-5 years)?',
                'What does success look like for your business?',
                'How many customers/clients do you want to serve monthly?'
            ],
            'brand_vision' => [
                'What is your company mission statement?',
                'What is your company vision for the future?',
                'What values does your business stand for?',
                'How do you want customers to perceive your brand?',
                'What makes your business unique from competitors?'
            ],
            'operational_needs' => [
                'Do you need customer forms (contact, quote requests, applications)?',
                'Do you need automated invoicing and receipt systems?',
                'Do you need inventory management features?',
                'Do you need customer testimonials/review sections?',
                'Do you need blog or news sections for content marketing?'
            ]
        ];
    }

    /**
     * Initialize AI agent configurations with comprehensive business consulting capabilities
     */
    private function init_agents() {
        $this->agents = [
            'business_consultant' => [
                'name' => 'Senior Business Consultant',
                'role' => 'Comprehensive business analysis and strategic planning',
                'system_prompt' => 'You are a senior business consultant with 20+ years of experience helping businesses succeed online. You conduct thorough business analysis, identify market opportunities, analyze competition, and create comprehensive business strategies. You ask probing questions to understand every aspect of the business: target market, industry dynamics, competitive landscape, revenue models, operational needs, legal requirements, and growth objectives. Your analysis is detailed, actionable, and includes specific recommendations for website features, business processes, and market positioning.',
                'tasks' => ['business_analysis', 'market_research', 'competitive_analysis', 'strategic_planning', 'business_model_optimization']
            ],
            'web_architect' => [
                'name' => 'Senior Web Designer & UX Architect',
                'role' => 'Complete website design and user experience planning',
                'system_prompt' => 'You are a senior web designer and UX architect specializing in business websites that convert visitors into customers. You create comprehensive website architectures with multiple pages, intuitive navigation, conversion-optimized layouts, and modern responsive designs. You understand how design psychology, color theory, typography, and user flow impact business success. You design websites with specific business goals in mind: lead generation, e-commerce, service booking, brand awareness, or information sharing. Your designs include detailed page structures, content layouts, form placements, and call-to-action optimization.',
                'tasks' => ['website_architecture', 'multi_page_design', 'user_experience', 'conversion_optimization', 'responsive_design', 'visual_branding']
            ],
            'content_strategist' => [
                'name' => 'Content Marketing & SEO Specialist',
                'role' => 'Comprehensive content strategy and copywriting',
                'system_prompt' => 'You are a content marketing specialist and professional copywriter who creates compelling, SEO-optimized content that drives business results. You develop complete content strategies including website copy, blog content, product descriptions, service pages, about pages, and marketing materials. You understand keyword research, local SEO, industry-specific content needs, and how to write copy that converts visitors into customers. Your content is engaging, informative, and optimized for both search engines and human readers. You create content that establishes authority, builds trust, and drives specific business actions.',
                'tasks' => ['content_strategy', 'seo_copywriting', 'page_content', 'blog_planning', 'product_descriptions', 'marketing_copy']
            ],
            'legal_compliance' => [
                'name' => 'Business Legal & Compliance Specialist',
                'role' => 'Legal documentation and business compliance',
                'system_prompt' => 'You are a business legal specialist who creates comprehensive legal documentation and ensures business compliance. You generate privacy policies, terms of service, disclaimer pages, cookie policies, and other legal documents tailored to specific business types and locations. You understand GDPR, CCPA, and other privacy regulations, e-commerce legal requirements, service business legal needs, and industry-specific compliance issues. You explain legal requirements in simple terms and create documents that protect businesses while remaining user-friendly. All documents are comprehensive, legally sound, and tailored to the specific business model.',
                'tasks' => ['privacy_policy', 'terms_of_service', 'disclaimers', 'cookie_policy', 'business_compliance', 'legal_documents']
            ],
            'seo_marketing' => [
                'name' => 'SEO & Digital Marketing Expert',
                'role' => 'Search optimization and digital marketing strategy',
                'system_prompt' => 'You are an SEO expert and digital marketing strategist who optimizes websites for maximum online visibility and business growth. You conduct keyword research based on business location, industry, and target audience. You create comprehensive SEO strategies including on-page optimization, local SEO, content marketing plans, and technical SEO recommendations. You understand Google My Business optimization, local search ranking factors, industry-specific SEO challenges, and how to create marketing funnels that convert traffic into customers. Your strategies are actionable, measurable, and designed to deliver real business results.',
                'tasks' => ['keyword_research', 'local_seo', 'competitor_seo_analysis', 'content_optimization', 'marketing_strategy', 'conversion_tracking']
            ],
            'operations_specialist' => [
                'name' => 'Business Operations & Systems Specialist',
                'role' => 'Business process optimization and system integration',
                'system_prompt' => 'You are a business operations specialist who designs efficient business processes and recommends system integrations. You understand e-commerce platforms, payment processing, CRM systems, booking systems, inventory management, automated workflows, and customer communication systems. You create recommendations for business tools, software integrations, and operational processes that streamline business operations and improve customer experience. Your recommendations are practical, cost-effective, and scalable as the business grows.',
                'tasks' => ['payment_systems', 'booking_systems', 'crm_integration', 'automation_workflows', 'inventory_management', 'customer_communication']
            ]
        ];
    }
    
    /**
     * Start comprehensive business consultation process
     */
    public function start_business_consultation() {
        return [
            'phase' => 'consultation',
            'message' => 'Welcome! I\'m your AI Business Consultant. I\'ll ask you detailed questions about your business to create a comprehensive website and business package tailored specifically for your needs. This consultation covers all aspects of your business including target market, goals, operations, and legal requirements.',
            'questions' => $this->business_questions,
            'current_category' => 'business_basics',
            'total_questions' => $this->count_total_questions(),
            'progress' => 5
        ];
    }
    
    /**
     * Process consultation responses and generate comprehensive business analysis
     */
    public function process_consultation_responses($responses) {
        try {
            // Generate comprehensive business analysis
            $business_analysis = $this->generate_business_analysis($responses);
            
            // Generate competitor analysis
            $competitor_analysis = $this->generate_competitor_analysis($responses);
            
            // Generate SEO strategy
            $seo_strategy = $this->generate_seo_strategy($responses);
            
            // Generate website architecture plan
            $website_plan = $this->generate_website_architecture($responses);
            
            // Generate operational requirements
            $operational_requirements = $this->generate_operational_requirements($responses);
            
            // Generate legal document requirements
            $legal_requirements = $this->generate_legal_requirements($responses);
            
            // Create comprehensive business package proposal
            $business_package = [
                'business_analysis' => $business_analysis,
                'competitor_analysis' => $competitor_analysis,
                'seo_strategy' => $seo_strategy,
                'website_architecture' => $website_plan,
                'operational_systems' => $operational_requirements,
                'legal_documentation' => $legal_requirements,
                'implementation_timeline' => $this->generate_implementation_timeline($responses),
                'cost_benefit_analysis' => $this->generate_cost_benefit_analysis($responses)
            ];
            
            return [
                'phase' => 'business_package_proposal',
                'package' => $business_package,
                'message' => 'Based on your consultation, I\'ve created a comprehensive business package proposal. Please review all sections carefully and let me know if you\'d like me to proceed with generating your complete business website and documentation.',
                'progress' => 50
            ];
            
        } catch (Exception $e) {
            error_log('VMO Business Consultation Error: ' . $e->getMessage());
            throw new Exception('Failed to process consultation responses: ' . $e->getMessage());
        }
    }
    
    /**
     * Generate complete business website based on all consultation data
     */
    public function generate_complete_business_website($responses) {
        try {
            // Generate main website
            $main_website = $this->create_main_website($responses);
            
            // Generate additional pages
            $additional_pages = $this->create_additional_pages($responses);
            
            // Generate legal documents
            $legal_documents = $this->create_legal_documents($responses);
            
            // Create downloadable business plan
            $business_plan_pdf = $this->create_business_plan_pdf($responses);
            
            // Initialize business phone service if available
            $phone_setup = $this->setup_business_phone_service($responses);
            
            // Initialize shipping service if needed
            $shipping_setup = $this->setup_shipping_service($responses);
            
            return [
                'phase' => 'complete_website_generated',
                'website' => [
                    'main_page' => $main_website,
                    'pages' => $additional_pages,
                    'legal_docs' => $legal_documents
                ],
                'downloads' => [
                    'business_plan' => $business_plan_pdf
                ],
                'business_services' => [
                    'phone_setup' => $phone_setup,
                    'shipping_setup' => $shipping_setup
                ],
                'message' => 'Your complete business website has been generated with professional phone service! Review it in the preview below and use the chat to request any refinements.',
                'progress' => 100
            ];
            
        } catch (Exception $e) {
            error_log('VMO Website Generation Error: ' . $e->getMessage());
            throw new Exception('Failed to generate complete website: ' . $e->getMessage());
        }
    }
    
    /**
     * Setup business phone service integration
     */
    private function setup_business_phone_service($responses) {
        try {
            // Check if enhanced business phone class is available
            if (class_exists('VMO_Enhanced_Business_Phone')) {
                // Extract business information from responses
                $business_data = $this->extract_business_data_for_phone($responses);
                
                return [
                    'status' => 'available',
                    'message' => 'Business phone service ready for activation',
                    'business_data' => $business_data,
                    'activation_instructions' => 'Phone service can be activated from your business dashboard'
                ];
            } else {
                return [
                    'status' => 'unavailable',
                    'message' => 'Phone service integration not available'
                ];
            }
        } catch (Exception $e) {
            error_log('VMO Phone Setup Error: ' . $e->getMessage());
            return [
                'status' => 'error',
                'message' => 'Phone service setup encountered an error: ' . $e->getMessage()
            ];
        }
    }

    /**
     * Setup automated shipping service
     */
    private function setup_shipping_service($responses) {
        try {
            if (function_exists('vmo_auto_configure_shipping')) {
                $business_data = $this->extract_business_data_for_phone($responses); // Reuse extraction logic
                $result = vmo_auto_configure_shipping($business_data);
                
                return [
                    'status' => $result['success'] ? 'configured' : 'skipped',
                    'message' => $result['message'],
                    'carriers' => $result['carriers'] ?? []
                ];
            }
            return ['status' => 'unavailable', 'message' => 'Shipping automation module not loaded'];
        } catch (Exception $e) {
            error_log('VMO Shipping Setup Error: ' . $e->getMessage());
            return ['status' => 'error', 'message' => 'Shipping setup error'];
        }
    }
    
    /**
     * Extract business data for phone service setup
     */
    private function extract_business_data_for_phone($responses) {
        $business_data = array();
        
        // Extract business name, type, location from responses
        foreach ($responses as $response) {
            if (is_string($response)) {
                // Look for business name patterns
                if (preg_match('/business.*name.*:?\s*([^\n\r.]+)/i', $response, $matches)) {
                    $business_data['business_name'] = trim($matches[1]);
                }
                
                // Look for business type patterns
                if (preg_match('/business.*type.*:?\s*([^\n\r.]+)/i', $response, $matches)) {
                    $business_data['business_type'] = trim($matches[1]);
                }
                
                // Look for location patterns
                if (preg_match('/location.*:?\s*([^\n\r.]+)/i', $response, $matches)) {
                    $business_data['location'] = trim($matches[1]);
                }
            }
        }
        
        return $business_data;
    }
    
    /**
     * Generate comprehensive business analysis
     */
    private function generate_business_analysis($responses) {
        $consultant = $this->agents['business_consultant'];
        
        $prompt = "Based on the following business consultation responses, provide a comprehensive business analysis:\n\n";
        $prompt .= $this->format_responses_for_analysis($responses);
        $prompt .= "\n\nProvide detailed analysis covering:\n";
        $prompt .= "• Business model assessment and optimization recommendations\n";
        $prompt .= "• Target market analysis and customer persona development\n";
        $prompt .= "• Market opportunity assessment\n";
        $prompt .= "• Revenue potential and pricing strategy recommendations\n";
        $prompt .= "• Business growth opportunities and scaling strategies\n";
        $prompt .= "• Risk assessment and mitigation strategies\n";
        $prompt .= "• Key success factors and performance metrics\n";
        
        return $this->call_openai($consultant['system_prompt'], $prompt);
    }
    
    /**
     * Generate competitor analysis based on business information
     */
    private function generate_competitor_analysis($responses) {
        $consultant = $this->agents['business_consultant'];
        
        $business_info = $this->extract_business_info($responses);
        
        $prompt = "Based on this business information: {$business_info}, provide comprehensive competitor analysis:\n\n";
        $prompt .= "• Identify 5-10 main competitors in the industry and location\n";
        $prompt .= "• Analyze competitor strengths and weaknesses\n";
        $prompt .= "• Identify market gaps and opportunities\n";
        $prompt .= "• Recommend competitive advantages and differentiation strategies\n";
        $prompt .= "• Analyze competitor pricing models and market positioning\n";
        $prompt .= "• Suggest strategies to outperform competitors online\n";
        
        return $this->call_openai($consultant['system_prompt'], $prompt);
    }
    
    /**
     * Generate comprehensive SEO strategy
     */
    private function generate_seo_strategy($responses) {
        $seo_expert = $this->agents['seo_marketing'];
        
        $business_info = $this->extract_business_info($responses);
        
        $prompt = "Create comprehensive SEO strategy for: {$business_info}\n\n";
        $prompt .= "Provide detailed SEO analysis including:\n";
        $prompt .= "• Primary and secondary keyword research (20+ keywords)\n";
        $prompt .= "• Local SEO strategy for business location\n";
        $prompt .= "• Content marketing plan and blog topics\n";
        $prompt .= "• On-page SEO recommendations for each website page\n";
        $prompt .= "• Technical SEO requirements\n";
        $prompt .= "• Link building strategy\n";
        $prompt .= "• Google My Business optimization plan\n";
        $prompt .= "• Competitor SEO analysis and opportunities\n";
        $prompt .= "• Measurable SEO goals and KPIs\n";
        
        return $this->call_openai($seo_expert['system_prompt'], $prompt);
    }
    
    /**
     * Generate comprehensive website architecture plan
     */
    private function generate_website_architecture($responses) {
        $architect = $this->agents['web_architect'];
        
        $business_info = $this->extract_business_info($responses);
        
        $prompt = "Design complete website architecture for: {$business_info}\n\n";
        $prompt .= "Create detailed website plan including:\n";
        $prompt .= "• Complete site map with all pages and subpages\n";
        $prompt .= "• Page-by-page content structure and layout\n";
        $prompt .= "• Navigation design and user flow\n";
        $prompt .= "• Conversion optimization strategy\n";
        $prompt .= "• Mobile responsiveness requirements\n";
        $prompt .= "• Design concept and visual style guide\n";
        $prompt .= "• Call-to-action placement and optimization\n";
        $prompt .= "• Form design and lead capture strategy\n";
        $prompt .= "• User experience optimization\n";
        $prompt .= "• Brand integration and visual identity\n";
        
        return $this->call_openai($architect['system_prompt'], $prompt);
    }
    
    /**
     * Generate operational requirements and system recommendations
     */
    private function generate_operational_requirements($responses) {
        $ops_specialist = $this->agents['operations_specialist'];
        
        $business_info = $this->extract_business_info($responses);
        
        $prompt = "Based on business requirements: {$business_info}, recommend operational systems:\n\n";
        $prompt .= "Provide comprehensive operational analysis:\n";
        $prompt .= "• Required forms (contact, quote, booking, application forms)\n";
        $prompt .= "• Payment processing systems and integration\n";
        $prompt .= "• Automated invoicing and receipt systems\n";
        $prompt .= "• Customer relationship management (CRM) recommendations\n";
        $prompt .= "• Booking/appointment systems if needed\n";
        $prompt .= "• Inventory management systems if applicable\n";
        $prompt .= "• Email marketing automation setup\n";
        $prompt .= "• Customer communication workflows\n";
        $prompt .= "• Analytics and tracking implementation\n";
        $prompt .= "• Integration recommendations and costs\n";
        
        return $this->call_openai($ops_specialist['system_prompt'], $prompt);
    }
    
    /**
     * Generate legal documentation requirements
     */
    private function generate_legal_requirements($responses) {
        $legal_specialist = $this->agents['legal_compliance'];
        
        $business_info = $this->extract_business_info($responses);
        
        $prompt = "Analyze legal requirements for: {$business_info}\n\n";
        $prompt .= "Provide comprehensive legal documentation plan:\n";
        $prompt .= "• Required legal pages and documents\n";
        $prompt .= "• Privacy policy requirements (GDPR, CCPA compliance)\n";
        $prompt .= "• Terms of service and conditions\n";
        $prompt .= "• Disclaimer requirements\n";
        $prompt .= "• Cookie policy and consent requirements\n";
        $prompt .= "• Industry-specific legal compliance\n";
        $prompt .= "• Business licensing and permit information\n";
        $prompt .= "• Liability protection recommendations\n";
        $prompt .= "• Customer data protection requirements\n";
        $prompt .= "• E-commerce legal requirements if applicable\n";
        
        return $this->call_openai($legal_specialist['system_prompt'], $prompt);
    }
    
    /**
     * Create main website HTML
     */
    private function create_main_website($responses) {
        $architect = $this->agents['web_architect'];
        
        $business_info = $this->format_responses_for_analysis($responses);
        
        $prompt = "Create a complete, professional, multi-page business website based on this consultation:\n\n";
        $prompt .= $business_info;
        $prompt .= "\n\nRequirements:\n";
        $prompt .= "• Modern Tailwind CSS website with React 18, GSAP ScrollTrigger animations, Lenis smooth scroll\n";
        $prompt .= "• Use Tailwind utility classes for all layout and styling\n";
        $prompt .= "• Add data-vmo-animate attribute on sections for scroll reveal\n";
        $prompt .= "• CDN libraries (Tailwind, GSAP, Lenis, Swiper, React) are pre-loaded — do NOT include CDN links\n";
        $prompt .= "• Professional design with proper branding\n";
        $prompt .= "• Multiple pages (Home, About, Services, Contact, etc.)\n";
        $prompt .= "• All necessary forms for business operations\n";
        $prompt .= "• SEO-optimized content and structure\n";
        $prompt .= "• Mobile-responsive design\n";
        $prompt .= "• Fast loading and professional appearance\n";
        $prompt .= "• Call-to-action buttons throughout\n";
        $prompt .= "• Contact forms, quote forms, booking forms as needed\n";
        $prompt .= "• Footer with links to legal documents\n";
        
        $html = $this->call_openai($architect['system_prompt'], $prompt);
        
        // ✅ GrapesJS: Wrap in premium composition shell
        if (is_string($html) && class_exists('VMO_Grapes_Composer') && !empty(get_option('vmo_grapesjs_api_key'))) {
            $html = VMO_Grapes_Composer::wrap_in_premium_shell($html, array(
                'tech_stack' => array('React 18', 'Tailwind CSS', 'GSAP', 'Lenis', 'Swiper.js'),
            ));
        }
        
        return $html;
    }
    
    /**
     * Create additional website pages
     */
    private function create_additional_pages($responses) {
        $pages = [];
        
        // About Page
        $pages['about'] = $this->create_about_page($responses);
        
        // Services/Products Page
        $pages['services'] = $this->create_services_page($responses);
        
        // Contact Page
        $pages['contact'] = $this->create_contact_page($responses);
        
        // FAQ Page
        $pages['faq'] = $this->create_faq_page($responses);
        
        // Blog Page (if content marketing is needed)
        if ($this->needs_blog($responses)) {
            $pages['blog'] = $this->create_blog_page($responses);
        }
        
        return $pages;
    }
    
    /**
     * Create legal documents as downloadable PDFs and web pages
     */
    private function create_legal_documents($responses) {
        $legal_specialist = $this->agents['legal_compliance'];
        $documents = [];
        
        $business_info = $this->extract_business_info($responses);
        
        // Privacy Policy
        $privacy_prompt = "Create comprehensive GDPR and CCPA compliant privacy policy for: {$business_info}";
        $documents['privacy_policy'] = $this->call_openai($legal_specialist['system_prompt'], $privacy_prompt);
        
        // Terms of Service
        $terms_prompt = "Create comprehensive terms of service for: {$business_info}";
        $documents['terms_of_service'] = $this->call_openai($legal_specialist['system_prompt'], $terms_prompt);
        
        // Disclaimer
        $disclaimer_prompt = "Create business disclaimer for: {$business_info}";
        $documents['disclaimer'] = $this->call_openai($legal_specialist['system_prompt'], $disclaimer_prompt);
        
        // Cookie Policy
        $cookie_prompt = "Create cookie policy for: {$business_info}";
        $documents['cookie_policy'] = $this->call_openai($legal_specialist['system_prompt'], $cookie_prompt);
        
        return $documents;
    }
    
    /**
     * Create business plan PDF
     */
    private function create_business_plan_pdf($responses) {
        $consultant = $this->agents['business_consultant'];
        
        $business_info = $this->format_responses_for_analysis($responses);
        
        $prompt = "Create a comprehensive business plan document based on:\n\n{$business_info}\n\n";
        $prompt .= "Include:\n• Executive Summary\n• Market Analysis\n• Business Model\n";
        $prompt .= "• Marketing Strategy\n• Financial Projections\n• Implementation Timeline\n";
        $prompt .= "• Risk Assessment\n• Success Metrics\n";
        
        $business_plan = $this->call_openai($consultant['system_prompt'], $prompt);
        
        // Convert to PDF (you'll need to implement PDF generation)
        return $this->convert_to_pdf($business_plan, 'Business Plan');
    }
    
    /**
     * Helper method to count total questions
     */
    private function count_total_questions() {
        $total = 0;
        foreach ($this->business_questions as $category => $questions) {
            $total += count($questions);
        }
        return $total;
    }
    
    /**
     * Format consultation responses for AI analysis
     */
    private function format_responses_for_analysis($responses) {
        $formatted = "BUSINESS CONSULTATION RESPONSES:\n\n";
        
        foreach ($responses as $category => $answers) {
            $formatted .= strtoupper(str_replace('_', ' ', (string) $category)) . ":\n";
            if (is_array($answers)) {
                foreach ($answers as $question => $answer) {
                    $formatted .= "Q: {$question}\nA: {$answer}\n\n";
                }
            }
            $formatted .= "\n";
        }
        
        return $formatted;
    }
    
    /**
     * Extract key business information for prompt building
     */
    private function extract_business_info($responses) {
        $info = [];
        
        // Extract key details from responses
        foreach ($responses as $category => $answers) {
            if (is_array($answers)) {
                foreach ($answers as $question => $answer) {
                    if (stripos($question, 'business name') !== false) {
                        $info['business_name'] = $answer;
                    } elseif (stripos($question, 'industry') !== false) {
                        $info['industry'] = $answer;
                    } elseif (stripos($question, 'location') !== false) {
                        $info['location'] = $answer;
                    } elseif (stripos($question, 'target audience') !== false) {
                        $info['target_audience'] = $answer;
                    } elseif (stripos($question, 'type of business') !== false) {
                        $info['business_type'] = $answer;
                    }
                }
            }
        }
        
        return json_encode($info);
    }
    
    // Helper methods for specific page creation
    private function create_about_page($responses) {
        $content_strategist = $this->agents['content_strategist'];
        $business_info = $this->format_responses_for_analysis($responses);
        
        $prompt = "Create compelling About page content for:\n{$business_info}\n\nInclude business story, team, mission, values, and trust-building elements.";
        
        return $this->call_openai($content_strategist['system_prompt'], $prompt);
    }
    
    private function create_services_page($responses) {
        $content_strategist = $this->agents['content_strategist'];
        $business_info = $this->format_responses_for_analysis($responses);
        
        $prompt = "Create detailed Services/Products page for:\n{$business_info}\n\nInclude service descriptions, benefits, pricing, and clear calls-to-action.";
        
        return $this->call_openai($content_strategist['system_prompt'], $prompt);
    }
    
    private function create_contact_page($responses) {
        $content_strategist = $this->agents['content_strategist'];
        $business_info = $this->format_responses_for_analysis($responses);
        
        $prompt = "Create comprehensive Contact page for:\n{$business_info}\n\nInclude contact forms, business hours, location, and multiple contact methods.";
        
        return $this->call_openai($content_strategist['system_prompt'], $prompt);
    }
    
    private function create_faq_page($responses) {
        $content_strategist = $this->agents['content_strategist'];
        $business_info = $this->format_responses_for_analysis($responses);
        
        $prompt = "Create comprehensive FAQ page for:\n{$business_info}\n\nInclude common questions about services, pricing, process, and policies.";
        
        return $this->call_openai($content_strategist['system_prompt'], $prompt);
    }
    
    private function create_blog_page($responses) {
        $content_strategist = $this->agents['content_strategist'];
        $business_info = $this->format_responses_for_analysis($responses);
        
        $prompt = "Create blog/news page structure and sample posts for:\n{$business_info}\n\nInclude content strategy and SEO-optimized blog posts.";
        
        return $this->call_openai($content_strategist['system_prompt'], $prompt);
    }
    
    private function needs_blog($responses) {
        // Logic to determine if business needs a blog based on responses
        $business_info = json_decode($this->extract_business_info($responses), true);
        
        // Default to true for most businesses as blogs help with SEO
        return true;
    }
    
    private function generate_implementation_timeline($responses) {
        $consultant = $this->agents['business_consultant'];
        $business_info = $this->extract_business_info($responses);
        
        $prompt = "Create detailed implementation timeline for business launch: {$business_info}";
        
        return $this->call_openai($consultant['system_prompt'], $prompt);
    }
    
    private function generate_cost_benefit_analysis($responses) {
        $consultant = $this->agents['business_consultant'];
        $business_info = $this->extract_business_info($responses);
        
        $prompt = "Provide cost-benefit analysis and ROI projections for: {$business_info}";
        
        return $this->call_openai($consultant['system_prompt'], $prompt);
    }
    
    /**
     * Convert text content to PDF
     */
    private function convert_to_pdf($content, $filename) {
        // This would need a PDF library like TCPDF or mPDF
        // For now, return the content with instructions to implement PDF generation
        return [
            'content' => $content,
            'filename' => $filename . '.pdf',
            'download_url' => '#', // Would be actual download URL
            'note' => 'PDF generation to be implemented with TCPDF or similar library'
        ];
    }
    
    /**
     * Call OpenAI API
     */
    private function call_openai($system_prompt, $user_prompt) {
        if (!$this->api_key) {
            throw new Exception('OpenAI API key not configured');
        }
        
        // ✅ TOKEN DEDUCTION v8.1.0: Charge for business wizard AI call
        $user_id = get_current_user_id();
        if (function_exists('vmo_deduct_tokens')) {
            if (!vmo_deduct_tokens($user_id, 600, 'business_wizard', 'Business wizard AI consultation')) {
                throw new Exception('Insufficient tokens. Please top up your balance to continue.');
            }
        }
        
        // ✅ FIX: Use correct token parameter based on model (GPT-5.2 requires max_completion_tokens)
        $token_param = function_exists('vmo_get_token_param') 
            ? vmo_get_token_param(VMO_OPENAI_MODEL, 4000) 
            : array('max_completion_tokens' => 4000);
        
        $data = array_merge([
            'model' => VMO_OPENAI_MODEL,
            'messages' => [
                ['role' => 'system', 'content' => $system_prompt],
                ['role' => 'user', 'content' => $user_prompt]
            ],
            'temperature' => 0.7
        ], $token_param);
        
        $response = wp_remote_post('https://api.openai.com/v1/chat/completions', [
            'headers' => [
                'Authorization' => 'Bearer ' . $this->api_key,
                'Content-Type' => 'application/json'
            ],
            'body' => json_encode($data),
            'timeout' => 120,
            'sslverify' => true,
            'redirection' => 5,
            'httpversion' => '1.0',
            'blocking' => true,
        ]);
        
        if (is_wp_error($response)) {
            $error_message = $response->get_error_message();
            error_log('VMO Business Wizard - API Error: ' . $error_message);
            throw new Exception('API request failed: ' . $error_message);
        }
        
        // Check HTTP response code
        $response_code = wp_remote_retrieve_response_code( $response );
        if ( $response_code !== 200 ) {
            $response_body = wp_remote_retrieve_body( $response );
            error_log( 'VMO Business Wizard - HTTP Error ' . $response_code . ': ' . $response_body );
            throw new Exception('OpenAI API returned error code: ' . $response_code);
        }
        
        $body = wp_remote_retrieve_body($response);
        $decoded = json_decode($body, true);
        
        if (!isset($decoded['choices'][0]['message']['content'])) {
            throw new Exception('Invalid API response');
        }
        
        return $decoded['choices'][0]['message']['content'];
    }
    
    /**
     * Process voice consultation conversation
     */
    public function process_voice_consultation($user_message, $session_id, $step, $previous_responses = []) {
        // Get consultation context
        $consultation_context = $this->get_consultation_context($step);
        
        // Prepare conversation history
        $conversation_history = $this->format_conversation_history($previous_responses);
        
        // Create AI prompt for business consultation
        $business_consultant = $this->agents['business_consultant'];
        $prompt = "You are conducting a voice-enabled business consultation to gather information for creating a website.

Session ID: {$session_id}
Current Step: {$step}
User's Response: {$user_message}

Previous Conversation:
{$conversation_history}

Current Focus: {$consultation_context['focus']}
Questions to Cover: " . implode(', ', $consultation_context['questions']) . "

Provide a conversational response that:
1. Acknowledges their answer professionally
2. Asks the next logical question to gather business information
3. Keeps the conversation flowing naturally for voice interaction
4. Is concise and clear for text-to-speech
5. Guides toward complete website requirements

If you have enough information to create a business website (5+ meaningful responses covering business type, target audience, services, goals), respond with: '[CONSULTATION_COMPLETE]' at the end.

Response:";

        try {
            $ai_response = (string) $this->call_openai($business_consultant['system_prompt'], $prompt);
            
            // Check if consultation is complete
            $consultation_complete = strpos($ai_response, '[CONSULTATION_COMPLETE]') !== false;
            $clean_response = str_replace('[CONSULTATION_COMPLETE]', '', $ai_response);
            
            return [
                'message' => trim($clean_response),
                'consultation_complete' => $consultation_complete,
                'step' => $step + 1,
                'session_id' => $session_id
            ];
            
        } catch (Exception $e) {
            throw new Exception('Failed to process consultation: ' . $e->getMessage());
        }
    }
    
    /**
     * Generate website from voice consultation data
     */
    public function generate_website_from_consultation($session_id, $responses) {
        try {
            // Format responses for website generation
            $formatted_responses = $this->format_consultation_responses($responses);
            
            // Generate website using existing method
            $website_data = $this->generate_complete_business_website($formatted_responses);
            
            // Add session tracking
            $website_data['consultation_session'] = $session_id;
            $website_data['generated_via'] = 'voice_consultation';
            
            return [
                'website_data' => $website_data,
                'redirect_url' => admin_url('admin.php?page=vmo-ai-builder&project=' . $website_data['project_id']),
                'message' => 'Your business website has been generated successfully from the voice consultation!'
            ];
            
        } catch (Exception $e) {
            throw new Exception('Failed to generate website from consultation: ' . $e->getMessage());
        }
    }
    
    /**
     * Get consultation context for current step
     */
    private function get_consultation_context($step) {
        $contexts = [
            0 => [
                'focus' => 'Business Type & Industry',
                'questions' => $this->business_questions['business_basics']
            ],
            1 => [
                'focus' => 'Target Market & Audience', 
                'questions' => $this->business_questions['target_market']
            ],
            2 => [
                'focus' => 'Business Model & Services',
                'questions' => $this->business_questions['business_model']
            ],
            3 => [
                'focus' => 'Goals & Objectives',
                'questions' => $this->business_questions['goals_objectives']
            ],
            4 => [
                'focus' => 'Brand Vision & Values',
                'questions' => $this->business_questions['brand_vision']
            ],
            5 => [
                'focus' => 'Operational Needs',
                'questions' => $this->business_questions['operational_needs']
            ]
        ];
        
        $context_key = min($step, count($contexts) - 1);
        return $contexts[$context_key];
    }
    
    /**
     * Format conversation history for AI context
     */
    private function format_conversation_history($responses) {
        if (empty($responses)) {
            return "This is the start of the consultation.";
        }
        
        $history = "Previous responses:\n";
        foreach ($responses as $step => $response) {
            $history .= "Step {$step}: {$response}\n";
        }
        
        return $history;
    }
    
    /**
     * Format consultation responses for website generation
     */
    private function format_consultation_responses($responses) {
        // Convert voice consultation responses to the format expected by generate_complete_business_website
        $formatted = [];
        
        // Map responses to expected structure
        foreach ($responses as $step => $response) {
            switch ($step) {
                case 0:
                    $formatted['business_type'] = $response;
                    break;
                case 1:
                    $formatted['target_audience'] = $response;
                    break;
                case 2:
                    $formatted['services'] = $response;
                    break;
                case 3:
                    $formatted['website_goals'] = $response;
                    break;
                case 4:
                    $formatted['branding_preferences'] = $response;
                    break;
                default:
                    $formatted['additional_info_' . $step] = $response;
                    break;
            }
        }
        
        return $formatted;
    }
}

// Register AJAX handlers
add_action('wp_ajax_vmo_start_business_consultation', 'vmo_ajax_start_business_consultation');
add_action('wp_ajax_vmo_process_consultation_responses', 'vmo_ajax_process_consultation_responses');
add_action('wp_ajax_vmo_generate_business_website', 'vmo_ajax_generate_business_website');

function vmo_ajax_start_business_consultation() {
    $admin_nonce   = isset($_POST['nonce']) ? $_POST['nonce'] : '';
    $builder_nonce = isset($_POST['security']) ? $_POST['security'] : '';
    if (!(($admin_nonce && wp_verify_nonce($admin_nonce, 'vmo_admin_nonce')) || ($builder_nonce && wp_verify_nonce($builder_nonce, 'vmo_builder_nonce')))) {
        wp_send_json_error(['message' => 'Security check failed', 'status' => 'invalid_nonce']);
        return;
    }
    
    try {
        $wizard = new VMO_Business_Wizard();
        $result = $wizard->start_business_consultation();
        wp_send_json_success($result);
    } catch (Exception $e) {
        wp_send_json_error(['message' => $e->getMessage()]);
    }
}

function vmo_ajax_process_consultation_responses() {
    $admin_nonce   = isset($_POST['nonce']) ? $_POST['nonce'] : '';
    $builder_nonce = isset($_POST['security']) ? $_POST['security'] : '';
    if (!(($admin_nonce && wp_verify_nonce($admin_nonce, 'vmo_admin_nonce')) || ($builder_nonce && wp_verify_nonce($builder_nonce, 'vmo_builder_nonce')))) {
        wp_send_json_error(['message' => 'Security check failed', 'status' => 'invalid_nonce']);
        return;
    }
    
    try {
        $responses = json_decode(wp_unslash($_POST['responses']), true);
        
        $wizard = new VMO_Business_Wizard();
        $result = $wizard->process_consultation_responses($responses);
        wp_send_json_success($result);
    } catch (Exception $e) {
        wp_send_json_error(['message' => $e->getMessage()]);
    }
}

function vmo_ajax_generate_business_website() {
    $admin_nonce   = isset($_POST['nonce']) ? $_POST['nonce'] : '';
    $builder_nonce = isset($_POST['security']) ? $_POST['security'] : '';
    if (!(($admin_nonce && wp_verify_nonce($admin_nonce, 'vmo_admin_nonce')) || ($builder_nonce && wp_verify_nonce($builder_nonce, 'vmo_builder_nonce')))) {
        wp_send_json_error(['message' => 'Security check failed', 'status' => 'invalid_nonce']);
        return;
    }
    
    try {
        $responses = json_decode(wp_unslash($_POST['responses']), true);
        
        $wizard = new VMO_Business_Wizard();
        $result = $wizard->generate_complete_business_website($responses);
        wp_send_json_success($result);
    } catch (Exception $e) {
        wp_send_json_error(['message' => $e->getMessage()]);
    }
}

// AJAX handler for voice-enabled business consultation
add_action('wp_ajax_vmo_business_consultation', 'vmo_handle_business_consultation');
function vmo_handle_business_consultation() {
    // Verify nonce (accept both)
    $admin_nonce   = isset($_POST['nonce']) ? $_POST['nonce'] : '';
    $builder_nonce = isset($_POST['security']) ? $_POST['security'] : '';
    if (!(($admin_nonce && wp_verify_nonce($admin_nonce, 'vmo_admin_nonce')) || ($builder_nonce && wp_verify_nonce($builder_nonce, 'vmo_builder_nonce')))) {
        wp_send_json_error(['message' => 'Security check failed', 'status' => 'invalid_nonce']);
        return;
    }

    // Note: Text-based business consultation is always available
    // Voice features are optional and don't block text consultation

    try {
        // Handle consultation_data - could be JSON string or array
        $consultation_data = wp_unslash($_POST['consultation_data']);  // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- complex data sanitized downstream
        if (is_string($consultation_data)) {
            $consultation_data = json_decode(stripslashes($consultation_data), true);
        }
        
        if (!is_array($consultation_data)) {
            wp_send_json_error(['message' => 'Invalid consultation data format']);
            return;
        }
        
        $user_message = isset($consultation_data['user_message']) ? sanitize_text_field($consultation_data['user_message']) : '';
        $session_id = isset($consultation_data['session_id']) ? sanitize_text_field($consultation_data['session_id']) : '';
        $step = isset($consultation_data['step']) ? intval($consultation_data['step']) : 0;
        $previous_responses = isset($consultation_data['previous_responses']) ? $consultation_data['previous_responses'] : [];

        if (empty($user_message)) {
            wp_send_json_error(['message' => 'No message provided']);
            return;
        }

        $wizard = new VMO_Business_Wizard();
        $result = $wizard->process_voice_consultation($user_message, $session_id, $step, $previous_responses);
        
        wp_send_json_success($result);
    } catch (Exception $e) {
        wp_send_json_error(['message' => $e->getMessage()]);
    }
}

// AJAX handler for generating business website from consultation
add_action('wp_ajax_vmo_generate_business_website', 'vmo_handle_generate_business_website');
function vmo_handle_generate_business_website() {
    // Verify nonce (accept both)
    $admin_nonce   = isset($_POST['nonce']) ? $_POST['nonce'] : '';
    $builder_nonce = isset($_POST['security']) ? $_POST['security'] : '';
    if (!(($admin_nonce && wp_verify_nonce($admin_nonce, 'vmo_admin_nonce')) || ($builder_nonce && wp_verify_nonce($builder_nonce, 'vmo_builder_nonce')))) {
        wp_send_json_error(['message' => 'Security check failed', 'status' => 'invalid_nonce']);
        return;
    }

    try {
        $business_data = wp_unslash($_POST['business_data']);  // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- complex data sanitized downstream
        $session_id = sanitize_text_field($business_data['session_id']);
        $responses = $business_data['responses'];

        $wizard = new VMO_Business_Wizard();
        $result = $wizard->generate_website_from_consultation($session_id, $responses);
        
        wp_send_json_success($result);
    } catch (Exception $e) {
        wp_send_json_error(['message' => $e->getMessage()]);
    }
}
