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

/**
 * VMO Business Consultation Handler
 * Handles voice-based business consultation flow with comprehensive AI responses
 */

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

class VMO_Business_Consultation {
    
    private $openai_api_key;
    private $consultation_questions;
    
    public function __construct() {
        $this->openai_api_key = get_option('vmo_openai_api_key', '');
        $this->init_consultation_flow();
        
        // Hook AJAX handlers
        // AJAX handlers for logged-in users
        add_action('wp_ajax_vmo_start_business_consultation', array($this, 'start_consultation'));
        add_action('wp_ajax_vmo_consultation_message', array($this, 'handle_consultation_message'));
        add_action('wp_ajax_vmo_complete_consultation', array($this, 'complete_consultation'));
        // VOICE SYSTEM REMOVED: Voice TTS endpoint removed for No Voice version
        
        // AJAX handlers for non-logged-in users (if needed)
        add_action('wp_ajax_nopriv_vmo_start_business_consultation', array($this, 'start_consultation'));
        add_action('wp_ajax_nopriv_vmo_consultation_message', array($this, 'handle_consultation_message'));
        add_action('wp_ajax_nopriv_vmo_complete_consultation', array($this, 'complete_consultation'));
        // VOICE SYSTEM REMOVED: Voice TTS nopriv endpoint removed for No Voice version
    }
    
    /**
     * Initialize consultation flow with comprehensive questions
     */
    private function init_consultation_flow() {
        $this->consultation_questions = [
            'business_basics' => [
                'What is your business name and what industry are you in?',
                'What is the main purpose of your business? What problems do you solve?',
                'Where is your business located? Do you serve local, national, or international customers?',
                'What makes your business unique compared to competitors?'
            ],
            'target_audience' => [
                'Who is your ideal customer? Describe their demographics and interests.',
                'What are the main pain points your customers face?',
                'How do customers currently find businesses like yours?',
                'What would make a customer choose you over a competitor?'
            ],
            'business_goals' => [
                'What do you want visitors to do on your website? Contact you, buy products, book appointments?',
                'What are your main business goals for the next 12 months?',
                'What would success look like for your online presence (e.g., specific revenue, lead volume)?'
            ],
            'reference_website' => [
                'Do you have a reference website that inspires you? If yes, paste the URL and I will scan it to extract its style/features automatically. If not, just say "no" and I will design a masterpiece from scratch.'
            ],
            'contact_preferences' => [
                'What is your business phone number? (For website display)',
                'What is your public business email address? (For website display)',
                'What are your business hours?',
                'Do you prefer customers to call, email, or use online forms?'
            ]
        ];
    }
    
    /**
     * Start business consultation
     */
    public function start_consultation() {
        if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['security'])), 'vmo_builder_nonce')) {
            wp_send_json_error(array('message' => 'Security check failed'));
        }
        
        if (!is_user_logged_in()) {
            wp_send_json_error(array('message' => 'User not logged in'));
        }
        
        $user_id = get_current_user_id();
        
        // Create new consultation session
        $consultation_id = 'consult_' . time() . '_' . $user_id;
        
        // Store consultation data
        update_user_meta($user_id, 'vmo_current_consultation', $consultation_id);
        update_user_meta($user_id, 'vmo_consultation_data_' . $consultation_id, array(
            'started_at' => current_time('mysql'),
            'status' => 'in_progress',
            'current_section' => 'business_basics',
            'question_index' => 0,
            'responses' => array()
        ));
        
        // Generate welcome message and first question
        $welcome_message = "Welcome to your comprehensive business consultation! I'm going to ask you a series of questions to understand your business and build the perfect website for you. We'll cover your business basics, target audience, goals, services, and contact preferences. Let's start with the first question: " . $this->consultation_questions['business_basics'][0];
        
        wp_send_json_success(array(
            'consultation_id' => $consultation_id,
            'message' => $welcome_message,
            'question_section' => 'business_basics',
            'question_index' => 0,
            'progress' => 5 // 5% complete
        ));
    }
    
    /**
     * Handle consultation message/response
     */
    public function handle_consultation_message() {
        if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['security'])), 'vmo_builder_nonce')) {
            wp_send_json_error(array('message' => 'Security check failed'));
        }
        
        if (!is_user_logged_in()) {
            wp_send_json_error(array('message' => 'User not logged in'));
        }
        
        $user_id = get_current_user_id();
        $consultation_id = sanitize_text_field(wp_unslash($_POST['consultation_id']));
        $user_response = sanitize_textarea_field($_POST['user_response']);
        $consultation_data = get_user_meta($user_id, 'vmo_consultation_data_' . $consultation_id, true);
        
        if (!$consultation_data) {
            wp_send_json_error(array('message' => 'Consultation not found'));
        }
        
        // Store user response
        $current_section = $consultation_data['current_section'];
        $question_index = $consultation_data['question_index'];
        
        // ✅ TOKEN DEDUCTION: Charge for consultation AI responses (300 tokens each)
        if (function_exists('vmo_deduct_tokens_for_operation')) {
            if (!vmo_deduct_tokens_for_operation($user_id, 'consultation_message')) {
                // Continue anyway but log it - consultation should not be blocked
                error_log("VMO Consultation: Insufficient tokens for user {$user_id}, continuing anyway");
            }
        }
        
        if (!isset($consultation_data['responses'][$current_section])) {
            $consultation_data['responses'][$current_section] = array();
        }
        
        $consultation_data['responses'][$current_section][$question_index] = $user_response;
        
        // [VMO-SCANNER] Intercept Reference Website Response
        $analysis_html = '';
        if ($current_section === 'reference_website') {
             // Regex to find URL in text
             preg_match('#\bhttps?://[^,\s()<>]+(?:\([\w\d]+\)|([^,[:punct:]\s]|/))#', $user_response, $matches);
             $url = isset($matches[0]) ? $matches[0] : '';
             
             if (!empty($url)) {
                 if (!class_exists('VMO_Website_Scanner')) {
                     $scanner_path = plugin_dir_path(__FILE__) . 'class-vmo-website-scanner.php';
                     if (file_exists($scanner_path)) require_once $scanner_path;
                 }
                 
                 if (class_exists('VMO_Website_Scanner')) {
                    $scanner = VMO_Website_Scanner::get_instance();
                    $scan_result = $scanner->fetch_url($url);
                    
                    if (!is_wp_error($scan_result)) {
                        $analysis_html = $this->generate_reference_analysis_html($scan_result, $consultation_data);
                    }
                 }
             }
        }

        // Move to next question
        $next_response = $this->get_next_question($consultation_data);
        
        if (!empty($analysis_html)) {
             // Prepend analysis to the next question
             $next_response['message'] = $analysis_html . $next_response['message'];
        }
        
        // Update consultation data
        update_user_meta($user_id, 'vmo_consultation_data_' . $consultation_id, $consultation_data);
        
        wp_send_json_success($next_response);
    }
    
    /**
     * Get next question in consultation flow
     */
    private function get_next_question($consultation_data) {
        $sections = array_keys($this->consultation_questions);
        $current_section = $consultation_data['current_section'];
        $question_index = $consultation_data['question_index'];
        
        // Move to next question in current section
        $question_index++;
        
        // Check if we need to move to next section
        if ($question_index >= count($this->consultation_questions[$current_section])) {
            $current_section_index = array_search($current_section, $sections);
            
            // Check if consultation is complete
            if ($current_section_index >= count($sections) - 1) {
                return array(
                    'consultation_complete' => true,
                    'message' => 'Thank you for completing the consultation! I now have all the information needed to build your perfect website. Let me generate your website now...',
                    'progress' => 100
                );
            }
            
            // Move to next section
            $current_section = $sections[$current_section_index + 1];
            $question_index = 0;
        }
        
        // Update consultation data
        $consultation_data['current_section'] = $current_section;
        $consultation_data['question_index'] = $question_index;
        
        // Calculate progress
        $total_questions = array_sum(array_map('count', $this->consultation_questions));
        $completed_questions = 0;
        
        foreach ($sections as $section) {
            if ($section === $current_section) {
                $completed_questions += $question_index;
                break;
            }
            $completed_questions += count($this->consultation_questions[$section]);
        }
        
        $progress = min(95, ($completed_questions / $total_questions) * 100);
        
        // Get next question
        $next_question = $this->consultation_questions[$current_section][$question_index];
        
        // Add section transition message if starting new section
        $section_messages = array(
            'target_audience' => 'Great! Now let\'s talk about your target audience. ',
            'business_goals' => 'Perfect! Now I\'d like to understand your business goals. ',
            'services_products' => 'Excellent! Let\'s discuss your products and services. ',
            'contact_preferences' => 'Almost done! Finally, let\'s set up your contact information. '
        );
        
        $message = '';
        if ($question_index === 0 && isset($section_messages[$current_section])) {
            $message = $section_messages[$current_section];
        }
        
        $message .= $next_question;
        
        return array(
            'message' => $message,
            'question_section' => $current_section,
            'question_index' => $question_index,
            'progress' => $progress,
            'consultation_data' => $consultation_data
        );
    }
    
    /**
     * Complete consultation and generate website
     */
    public function complete_consultation() {
        if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['security'])), 'vmo_builder_nonce')) {
            wp_send_json_error(array('message' => 'Security check failed'));
        }
        
        if (!is_user_logged_in()) {
            wp_send_json_error(array('message' => 'User not logged in'));
        }
        
        $user_id = get_current_user_id();
        $consultation_id = sanitize_text_field(wp_unslash($_POST['consultation_id']));
        $consultation_data = get_user_meta($user_id, 'vmo_consultation_data_' . $consultation_id, true);
        
        if (!$consultation_data) {
            wp_send_json_error(array('message' => 'Consultation not found'));
        }
        
        // Generate comprehensive business summary
        $business_summary = $this->generate_business_summary($consultation_data['responses']);
        
        // Generate website based on consultation
            try {
                $website_result = $this->generate_website_from_consultation($consultation_data['responses'], $business_summary);
            } catch (Exception $e) {
                wp_send_json_error(array('message' => 'Website generation failed: ' . $e->getMessage()));
            }
        
        // Update consultation as complete
        $consultation_data['status'] = 'completed';
        $consultation_data['completed_at'] = current_time('mysql');
        $consultation_data['generated_website'] = $website_result;
        
        update_user_meta($user_id, 'vmo_consultation_data_' . $consultation_id, $consultation_data);
        
        // Persist a DB record for integration pipeline (session_id == consultation_id)
        try {
            if (!class_exists('VMO_Consultation_Database')) {
                require_once plugin_dir_path(__FILE__) . 'class-vmo-consultation-database.php';
            }
            $db = new VMO_Consultation_Database();
            // Prepare compact data payload
            $db_payload = array(
                'business_name' => '',
                'business_type' => '',
                'consultation_data' => $consultation_data['responses'] ?? array(),
                'conversation_log' => array(),
                'website_data' => $website_result,
                'status' => 'completed'
            );
            $insert_id = $db->save_consultation($user_id, $consultation_id, $db_payload);
            // Fire integration hook for async full-site generation/publish
            do_action('vmo_consultation_completed', array(
                'session_id' => $consultation_id,
                'consultation_id' => $insert_id,
                'user_id' => $user_id
            ));
        } catch (Exception $e) {
            error_log('VMO complete_consultation DB/Hook error: ' . $e->getMessage());
        }

        // Generate final summary message
        $summary_message = $this->generate_completion_summary($consultation_data, $website_result);
        
        wp_send_json_success(array(
            'website_generated' => true,
            'summary_message' => $summary_message,
            'website_data' => $website_result,
            'consultation_complete' => true,
            // Signal for UI to refresh KPIs and preview
            'refresh_signals' => array('preview_iframe' => true, 'kpis' => true)
        ));
    }
    
    /**
     * Generate business summary from consultation responses
     */
    private function generate_business_summary($responses) {
        $summary = "Business Summary:\n";
        
        foreach ($responses as $section => $section_responses) {
            $summary .= "\n" . ucwords(str_replace('_', ' ', $section)) . ":\n";
            foreach ($section_responses as $index => $response) {
                $summary .= "- " . $response . "\n";
            }
        }
        
        return $summary;
    }
    
    /**
     * Generate website from consultation data
     */
    private function generate_website_from_consultation($responses, $business_summary = '') {
        if (!is_array($responses)) {
            throw new Exception('Invalid consultation responses payload.');
        }

        if (!class_exists('VMO_Business_Wizard')) {
            $wizard_path = plugin_dir_path(__FILE__) . 'business-wizard-handler.php';
            if (file_exists($wizard_path)) {
                require_once $wizard_path;
            }
        }

        if (class_exists('VMO_Business_Wizard')) {
            $wizard = new VMO_Business_Wizard();
            $generated = $wizard->generate_complete_business_website($responses);

            $main_page = '';
            if (isset($generated['website']['main_page']) && is_string($generated['website']['main_page'])) {
                $main_page = trim($generated['website']['main_page']);
            }

            $pages = array('home');
            if (!empty($generated['website']['pages']) && is_array($generated['website']['pages'])) {
                $pages = array_values(array_unique(array_merge($pages, array_keys($generated['website']['pages']))));
            }

            $features = array(
                'contact_forms',
                'mobile_responsive_design',
                'seo_optimization',
            );

            $phone_status = $generated['business_services']['phone_setup']['status'] ?? '';
            if (in_array($phone_status, array('available', 'configured'), true)) {
                $features[] = 'phone_integration';
            }

            $shipping_status = $generated['business_services']['shipping_setup']['status'] ?? '';
            if ($shipping_status === 'configured') {
                $features[] = 'shipping_automation';
            }

            return array(
                'content' => $main_page,
                'main_page' => $main_page,
                'pages' => $pages,
                'features' => array_values(array_unique($features)),
                'business_summary' => $business_summary ?: $this->generate_business_summary($responses),
                'phase' => $generated['phase'] ?? 'complete_website_generated',
                'message' => $generated['message'] ?? '',
                'website' => $generated['website'] ?? array(),
                'downloads' => $generated['downloads'] ?? array(),
                'business_services' => $generated['business_services'] ?? array(),
            );
        }

        if (function_exists('vmo_generate_ai_content')) {
            $prompt = "Based on this business consultation: \n\n" . ($business_summary ?: $this->generate_business_summary($responses)) . "\n\nGenerate a complete professional website homepage with contact forms, service descriptions, and modern design. Return production-ready HTML.";
            $content = vmo_generate_ai_content($prompt);

            return array(
                'content' => is_string($content) ? $content : '',
                'main_page' => is_string($content) ? $content : '',
                'pages' => array('home'),
                'features' => array('contact_forms', 'mobile_responsive_design'),
                'business_summary' => $business_summary ?: $this->generate_business_summary($responses),
            );
        }

        throw new Exception('No website generation engine is available.');
    }
    
    /**
     * Generate completion summary message
     */
    private function generate_completion_summary($consultation_data, $website_result) {
        $features_added = array(
            'a multi-page website draft',
            'contact forms with email notifications',
            'service showcase pages',
            'mobile-responsive design',
            'core SEO content'
        );

        if (!empty($website_result['features']) && is_array($website_result['features'])) {
            foreach ($website_result['features'] as $feature) {
                $feature = trim(str_replace('_', ' ', (string) $feature));
                if ($feature !== '' && !in_array($feature, $features_added, true)) {
                    $features_added[] = $feature;
                }
            }
        }
        
        // Extract phone numbers from consultation responses
        $phone_numbers = array();
        foreach ($consultation_data['responses'] as $responses) {
            foreach ($responses as $response) {
                if (preg_match('/(\(?\d{3}\)?\s?-?\d{3}-?\d{4})/', $response, $matches)) {
                    $phone_numbers[] = $matches[1];
                }
            }
        }
        
        if (empty($phone_numbers)) {
            $phone_numbers[] = 'your provided contact number';
        }

        $summary = "Your consultation is complete. I generated a website draft for your business with " . implode(', ', $features_added) . ". ";

        $phone_status = $website_result['business_services']['phone_setup']['status'] ?? '';
        if (in_array($phone_status, array('available', 'configured'), true)) {
            $summary .= "Your phone details for " . implode(' and ', $phone_numbers) . " have been prepared in the dashboard so you can review or activate the communication flow. ";
        } else {
            $summary .= "Your provided contact details, including " . implode(' and ', $phone_numbers) . ", were captured for the website draft where applicable. ";
        }

        $summary .= "Review the draft preview, request refinements if needed, and continue from the dashboard to publish and monitor analytics.";
        
        return $summary;
    }
    
    // VOICE SYSTEM REMOVED: handle_text_to_speech and synthesize_speech methods removed for No Voice version

    /**
     * Generate HTML for Reference Site Analysis
     */
    private function generate_reference_analysis_html($scan_result, $consultation_data) {
        $url = $scan_result['url'];
        
        // Detailed Analysis Logic (Simulated for speed, but real code would parse $scan_result['sections'])
        $analysis_reasoning = "I've analyzed the structure of <strong>" . esc_html($scan_result['url']) . "</strong>. While it has good visual hierarchy, my analysis suggests we can improve the 'Conversion Paths' and 'Mobile Responsiveness' by 40% using our modernized framework.";
        
        // Generate HTML Card
        ob_start();
        ?>
        <div class="vmo-scanner-result" style="margin: 1.5rem 0; padding: 1.5rem; background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.1); border-radius: 12px; font-family: sans-serif;">
            <div style="display:flex; align-items:center; margin-bottom:1rem;">
                <span style="font-size:1.5rem; margin-right:0.75rem;">🔍</span>
                <div>
                    <h4 style="margin:0; font-size:1rem; color:#fff;">Reference Analysis Complete</h4>
                    <a href="<?php echo esc_url($url); ?>" target="_blank" style="font-size:0.8rem; color:#aaa; text-decoration:none;"><?php echo esc_html($url); ?></a>
                </div>
            </div>
            
            <div style="margin-bottom:1rem; padding:1rem; background:rgba(0,0,0,0.2); border-radius:8px; font-size:0.9rem; color:#ddd; line-height: 1.5;">
                <strong>AI Insight:</strong> <?php echo esc_html( $analysis_reasoning ); ?>
            </div>
            
            <div class="vmo-scan-choices">
                <p style="margin:0 0 0.5rem 0; font-size:0.85rem; color:#aaa; text-transform:uppercase; letter-spacing:1px; font-weight:600;">How should we proceed?</p>
                
                <div style="display:grid; gap:0.5rem;">
                    <!-- Option 1: User Preference -->
                    <div style="background:rgba(255,255,255,0.05); border-radius:8px; padding:0.25rem;">
                        <label style="display:flex; align-items:center; padding:0.5rem; cursor:pointer; width:100%;">
                            <input type="radio" name="preference_choice" value="Replicate Reference" style="margin-right:10px;" onclick="window.vmoSubmitChoice && window.vmoSubmitChoice(this.value)">
                            <div>
                                <strong style="display:block; color:#fff; font-size:0.95rem;">Replicate Exact Style</strong>
                                <span style="font-size:0.8rem; color:#aaa;">Follow the reference design closely.</span>
                            </div>
                        </label>
                    </div>
                    
                    <!-- Option 2: AI Suggestion -->
                    <div style="background:rgba(100, 200, 255, 0.1); border:1px solid rgba(100, 200, 255, 0.3); border-radius:8px; padding:0.25rem;">
                        <label style="display:flex; align-items:center; padding:0.5rem; cursor:pointer; width:100%;">
                            <input type="radio" name="preference_choice" value="Use AI Enhanced Version" style="margin-right:10px;" onclick="window.vmoSubmitChoice && window.vmoSubmitChoice(this.value)">
                            <div>
                                <strong style="display:block; color:#fff; font-size:0.95rem;">Use AI Enhanced Version ✨</strong>
                                <span style="font-size:0.8rem; color:#aaa;">Combine reference vibes with high-conversion tactics.</span>
                            </div>
                        </label>
                    </div>
                </div>
            </div>
        </div>
        <?php
        return ob_get_clean();
    }
}


// Initialize the consultation handler
new VMO_Business_Consultation();

/**
 * ============================================================================
 * DYNAMIC AI RECOMMENDATIONS GENERATOR
 * Generates personalized recommendations by comparing user desires vs research
 * ============================================================================
 */

add_action('wp_ajax_vmo_generate_dynamic_recommendations', 'vmo_generate_dynamic_recommendations');
add_action('wp_ajax_nopriv_vmo_generate_dynamic_recommendations', 'vmo_generate_dynamic_recommendations');

/**
 * Generate AI-powered dynamic recommendations that compare user desires with research findings
 */
function vmo_generate_dynamic_recommendations() {
    $nonce = sanitize_text_field(
        wp_unslash(
            $_POST['security']
                ?? $_POST['nonce']
                ?? $_POST['_ajax_nonce']
                ?? ''
        )
    );

    $nonce_valid = $nonce && (
        wp_verify_nonce($nonce, 'vmo_builder_nonce')
        || wp_verify_nonce($nonce, 'vmo_admin_nonce')
        || wp_verify_nonce($nonce, 'vmo_ajax_nonce')
    );

    if (!$nonce_valid) {
        wp_send_json_error(['message' => 'Security check failed', 'status' => 'invalid_nonce'], 403);
    }
    
    // ✅ TOKEN DEDUCTION v8.1.0: Charge for dynamic recommendations
    $user_id = get_current_user_id();
    if (function_exists('vmo_deduct_tokens')) {
        if (!vmo_deduct_tokens($user_id, 600, 'consultation', 'AI-powered recommendations')) {
            wp_send_json_error(['message' => 'Insufficient tokens. Please top up your balance.']);
        }
    }
    
    $user_info = isset($_POST['user_info']) ? json_decode(wp_unslash($_POST['user_info']), true) : [];
    $research_results = isset($_POST['research_results']) ? json_decode(wp_unslash($_POST['research_results']), true) : [];
    
    if (empty($user_info)) {
        wp_send_json_error(['message' => 'No user information provided']);
    }
    
    $openai_api_key = get_option('vmo_openai_api_key', '');
    if (empty($openai_api_key)) {
        wp_send_json_error(['message' => 'OpenAI API key not configured']);
    }
    
    // Build the prompt for AI to generate comparison-based recommendations
    $prompt = vmo_build_dynamic_recommendations_prompt($user_info, $research_results);
    
    // Call OpenAI to generate dynamic recommendations
    $response = wp_remote_post('https://api.openai.com/v1/chat/completions', [
        'timeout' => 120, // Increased timeout for deep reasoning
        'headers' => [
            'Authorization' => 'Bearer ' . $openai_api_key,
            'Content-Type' => 'application/json'
        ],
        // ✅ FIX: GPT-5.2 requires max_completion_tokens, not max_tokens
        'body' => json_encode(array_merge([
            'model' => 'gpt-5.2-2025-12-11',
            'messages' => [
                [
                    'role' => 'system',
                    'content' => 'You are an expert business consultant who provides personalized recommendations by comparing what the client wants versus what market research reveals. You help clients make informed decisions by presenting options clearly. Always be specific and actionable. Return ONLY valid JSON without markdown code blocks.'
                ],
                [
                    'role' => 'user',
                    'content' => $prompt
                ]
            ],
            'temperature' => 0.7,
        ], function_exists('vmo_get_token_param') ? vmo_get_token_param('gpt-5.2-2025-12-11', 4000) : ['max_tokens' => 4000]))
    ]);
    
    if (is_wp_error($response)) {
        wp_send_json_error(['message' => 'Failed to generate recommendations: ' . $response->get_error_message()]);
    }
    
    $body = json_decode(wp_remote_retrieve_body($response), true);
    $content = $body['choices'][0]['message']['content'] ?? '';
    
    // Parse the AI response (should be JSON)
    $content = trim($content);
    // Remove markdown code blocks if present
    $content = preg_replace('/^```json\s*/', '', $content);
    $content = preg_replace('/^```\s*/', '', $content);
    $content = preg_replace('/\s*```$/', '', $content);
    
    $recommendations = json_decode($content, true);
    
    if (json_last_error() !== JSON_ERROR_NONE) {
        // Fallback: return raw content for client-side parsing
        wp_send_json_success([
            'recommendations' => null,
            'raw_content' => $content,
            'parse_error' => json_last_error_msg()
        ]);
    }
    
    wp_send_json_success([
        'recommendations' => $recommendations
    ]);
}

/**
 * Build the prompt for generating dynamic recommendations
 */
function vmo_build_dynamic_recommendations_prompt($user_info, $research_results) {
    // Extract user desires
    $business_name = $user_info['businessName'] ?? $user_info['business_name'] ?? 'the business';
    $industry = $user_info['industry'] ?? $user_info['industry_confirmation'] ?? $user_info['industry_name'] ?? '';
    $target_audience = $user_info['targetAudience'] ?? $user_info['target_audience'] ?? 'general audience';
    $goals = $user_info['businessGoals'] ?? $user_info['goals'] ?? [];
    $goals_text = is_array($goals) ? implode(', ', $goals) : $goals;
    $custom_pages = $user_info['customPages'] ?? [];
    $special_features = $user_info['specialFeatures'] ?? [];
    $style = $user_info['preferredStyle'] ?? $user_info['style'] ?? 'modern and professional';
    $colors = $user_info['colors'] ?? $user_info['brandColors'] ?? '';
    $needs_ecommerce = $user_info['ecommerce_needed'] ?? $user_info['needsEcommerce'] ?? false;
    $offerings = $user_info['offerings'] ?? $user_info['businessIdea'] ?? $user_info['business_idea'] ?? '';
    $references = $user_info['references'] ?? $user_info['inspirationSites'] ?? '';
    if (empty($industry)) {
        $industry = 'Not confirmed yet';
    }
    
    // Extract research findings
    $competitors = $research_results['competitors_list'] ?? [];
    $competitor_names = array_map(function($c) { return is_array($c) ? ($c['name'] ?? '') : $c; }, array_slice($competitors, 0, 5));
    $market_size = $research_results['market_size'] ?? '';
    $market_trends = $research_results['market_trends'] ?? [];
    $gaps = $research_results['gaps'] ?? [];
    $recommendations_from_research = $research_results['recommendations'] ?? [];
    $leads_count = $research_results['leads_generated_count'] ?? 0;
    $top_earners = $research_results['top_earners'] ?? [];
    
    $prompt = <<<PROMPT
Based on the following client consultation data and market research, generate personalized recommendations.

## CLIENT'S DESIRES (What they told us during consultation)
- Business Name: {$business_name}
- Industry: {$industry}
- Target Audience: {$target_audience}
- Business Goals: {$goals_text}
- Custom Pages Requested: {$custom_pages_json}
- Special Features Requested: {$special_features_json}
- Preferred Style: {$style}
- Brand Colors: {$colors}
- Needs E-Commerce: {$needs_ecommerce_text}
- Products/Services: {$offerings}
- Reference Sites: {$references}

## RESEARCH FINDINGS (What our deep market research revealed)
- Competitors Found: {$competitor_names_text}
- Market Size/Value: {$market_size}
- Market Trends: {$trends_text}
- Gaps/Opportunities Identified: {$gaps_text}
- Research Recommendations: {$research_recs_text}
- Top Industry Earners: {$earners_text}
- Initial Leads Generated: {$leads_count}

## YOUR TASK
Generate a JSON object with personalized recommendations. For each major decision point, show:
1. What the client originally wanted
2. What research revealed about that desire (feasibility, alternatives, market data)
3. Your expert recommendation
4. Why you recommend it
5. Options for the client to choose (original, recommended, or hybrid)

Return this EXACT JSON structure:
{
  "summary": "A brief 2-3 sentence personalized summary addressing the client by business name",
  "categories": [
    {
      "key": "category_key",
      "title": "Category Title with emoji",
      "items": [
        {
          "id": "unique_id",
          "label": "Recommendation title",
          "user_wanted": "What client specifically requested or implied",
          "research_found": "What market research revealed about this",
          "recommendation": "Your expert recommendation",
          "why": "Reasoning for your recommendation",
          "options": [
            {"id": "original", "label": "Keep Original Plan", "description": "Brief description"},
            {"id": "recommended", "label": "Use AI Recommendation", "description": "Brief description"},
            {"id": "hybrid", "label": "Combine Both", "description": "Brief description if applicable"}
          ],
          "default_choice": "original|recommended|hybrid",
          "impact": "high|medium|low"
        }
      ]
    }
  ],
  "custom_pages": [
    // For each custom page the user requested, evaluate feasibility and provide recommendation
    {
      "page_requested": "Page name user asked for",
      "feasibility": "high|medium|low|not_recommended",
      "recommendation": "What you recommend for this page",
      "why": "Why this recommendation"
    }
  ],
  "leads_info": {
    "count": {$leads_count},
    "summary": "Brief description of leads found if any"
  }
}

IMPORTANT RULES:
1. Be SPECIFIC - reference actual data, competitor names, market values when available
2. If user wanted something that research shows is not optimal, explain the contrast
3. If user's idea aligns with research, celebrate it
4. Always give the user final choice - never override their desires, just inform
5. Include ALL custom pages/features the user requested - evaluate each one
6. Be encouraging but honest
7. **MASTERPIECE QUALITY & AUTONOMY (CRITICAL):**
   - **REFERENCE WEBSITE STRATEGY:** If a reference website exists (`{$references}` is not empty):
     - **DO NOT** ask granular design questions (color codes, fonts, nav position). You must INFER these from the reference style.
     - **DO** collect general preferences (brand themes, color names) but use "Color Psychology" analysis to recommend improvements.
       - *Example:* "You requested Pink (like the reference), but deep research shows Red evokes hunger for this food niche. I recommend a Red/Pink hybrid."
     - **Recommendation Strategy:** Present a choice:
       - **Option A:** Replicate Reference (The user's safe choice).
       - **Option B (RECOMMENDED):** "Silicon Valley Masterpiece" — Enhance the reference with modern tech (GSAP animations, Locomotive Scroll, floating menus, pre-loaders).
       - Explain WHY: "The reference is good, but Option B adds a 'Wow Factor' overlay menu and deeper mobile optimization."
   - **DOCUMENT MEMORY:** Did the user upload a document? Check `custom_pages` carefully.
     - If the document asks for specific Dashboards, Membership Rules, or Affiliate Pages, these are **MANDATORY**. Do not offer generic alternatives.
     - Implement exactly what is requested in the document (dashboards, databases, rules).
   - **MENU & LOGO:** Default to "Masterpiece" standards:
     - Recommend: Full-screen overlay menus (like `capsules.moyra.co`) instead of boring lists.
     - Recommend: Interactive Logos (animate on hover, change color on scroll).
PROMPT;

    // Replace placeholders with actual values
    $custom_pages_json = json_encode($custom_pages ?: []);
    $special_features_json = json_encode($special_features ?: []);
    $needs_ecommerce_text = $needs_ecommerce ? 'Yes' : 'Not specified';
    $competitor_names_text = !empty($competitor_names) ? implode(', ', $competitor_names) : 'Not yet researched';
    $trends_text = is_array($market_trends) ? implode('; ', array_slice($market_trends, 0, 5)) : ($market_trends ?: 'Not yet researched');
    $gaps_text = is_array($gaps) ? implode('; ', array_slice($gaps, 0, 5)) : ($gaps ?: 'Not yet identified');
    $research_recs_text = is_array($recommendations_from_research) ? implode('; ', array_slice($recommendations_from_research, 0, 5)) : ($recommendations_from_research ?: 'Pending analysis');
    $earners_text = is_array($top_earners) ? implode(', ', array_slice($top_earners, 0, 5)) : ($top_earners ?: 'Not yet researched');

    // If this looks like a website-builder / business-suite SaaS, enforce richer website recommendations.
    $market_hint = strtolower((string)$industry . ' ' . (string)$business_name . ' ' . (string)$offerings . ' ' . (string)$references);
    $market_is_builder = (
        strpos($market_hint, 'website builder') !== false ||
        strpos($market_hint, 'site builder') !== false ||
        strpos($market_hint, 'web builder') !== false ||
        strpos($market_hint, 'business suite') !== false ||
        strpos($market_hint, 'saas') !== false ||
        strpos($market_hint, 'wix') !== false ||
        strpos($market_hint, 'squarespace') !== false ||
        strpos($market_hint, 'shopify') !== false ||
        strpos($market_hint, 'webflow') !== false
    );

    $builder_requirements = $market_is_builder
        ? "\n\nWEBSITE/PRODUCT RECOMMENDATIONS REQUIREMENTS (IMPORTANT):\n- You MUST include a category focused on WEBSITE ARCHITECTURE & CONVERSION (e.g., key='website_architecture').\n- In that category, include items that describe WHAT the site/app experience includes (pages, onboarding flow, demo/sandbox, pricing, comparison page, trust/proof, integrations, dashboard preview).\n- For each website-related item, the 'why' field MUST be 2-4 sentences and MUST include at least one DIRECT comparison to major competitors in this market.\n- Use DIRECT competitor names from the research list when available. If the research list is empty or too generic, you may use: Wix, Squarespace, Shopify, Webflow (only if relevant).\n- When you compare, be concrete: describe the competitor's typical approach and how the client will differentiate.\n"
        : "";
    
    // Build the final prompt with actual values
    $prompt = "Based on the following client consultation data and market research, generate personalized recommendations.

## CLIENT'S DESIRES (What they told us during consultation)
- Business Name: {$business_name}
- Industry: {$industry}
- Target Audience: {$target_audience}
- Business Goals: {$goals_text}
- Custom Pages Requested: {$custom_pages_json}
- Special Features Requested: {$special_features_json}
- Preferred Style: {$style}
- Brand Colors: {$colors}
- Needs E-Commerce: {$needs_ecommerce_text}
- Products/Services: {$offerings}
- Reference Sites: {$references}

## RESEARCH FINDINGS (What our deep market research revealed)
- Competitors Found: {$competitor_names_text}
- Market Size/Value: {$market_size}
- Market Trends: {$trends_text}
- Gaps/Opportunities Identified: {$gaps_text}
- Research Recommendations: {$research_recs_text}
- Top Industry Earners: {$earners_text}
- Initial Leads Generated: {$leads_count}

## YOUR TASK
Generate a JSON object with personalized recommendations. For each major decision point, show:
1. What the client originally wanted
2. What research revealed about that desire (feasibility, alternatives, market data)
3. Your expert recommendation
4. Why you recommend it
5. Options for the client to choose (original, recommended, or hybrid)

{$builder_requirements}

Return this EXACT JSON structure:
{
  \"summary\": \"A brief 2-3 sentence personalized summary addressing the client by business name\",
  \"categories\": [
    {
      \"key\": \"category_key\",
      \"title\": \"Category Title with emoji\",
      \"items\": [
        {
          \"id\": \"unique_id\",
          \"label\": \"Recommendation title\",
          \"user_wanted\": \"What client specifically requested or implied\",
          \"research_found\": \"What market research revealed about this\",
          \"recommendation\": \"Your expert recommendation\",
          \"why\": \"Reasoning for your recommendation\",
          \"options\": [
            {\"id\": \"original\", \"label\": \"Keep Original Plan\", \"description\": \"Brief description\"},
            {\"id\": \"recommended\", \"label\": \"Use AI Recommendation\", \"description\": \"Brief description\"},
            {\"id\": \"hybrid\", \"label\": \"Combine Both\", \"description\": \"Brief description if applicable\"}
          ],
          \"default_choice\": \"original|recommended|hybrid\",
          \"impact\": \"high|medium|low\"
        }
      ]
    }
  ],
  \"custom_pages\": [
    {
      \"page_requested\": \"Page name user asked for\",
      \"feasibility\": \"high|medium|low|not_recommended\",
      \"recommendation\": \"What you recommend for this page\",
      \"why\": \"Why this recommendation\"
    }
  ],
  \"leads_info\": {
    \"count\": {$leads_count},
    \"summary\": \"Brief description of leads found if any\"
  },
  \"market_position\": {
    \"current\": \"Honest assessment of client's current market standing\",
    \"short_term_6mo\": \"Projected position after 6 months of executing these recommendations\",
    \"mid_term_2_3yr\": \"Projected position after 2-3 years\",
    \"long_term_5yr_plus\": \"Projected position after 5+ years\"
  },
  \"industry_value\": {
    \"global_total\": \"Total global market value in USD\",
    \"local_total\": \"Local/regional market value in USD\",
    \"growth_rate\": \"Annual growth rate\"
  },
  \"competitor_analysis\": [
    {
      \"name\": \"Competitor Name\",
      \"type\": \"direct|indirect\",
      \"valuation\": \"Company worth in USD\",
      \"weakness\": \"Their specific weakness\",
      \"how_we_beat_them\": \"How these recommendations exploit this weakness\"
    }
  ]
}

IMPORTANT RULES:
1. Be SPECIFIC - reference actual data, competitor names, market values when available
2. If user wanted something that research shows is not optimal, explain the contrast
3. If user's idea aligns with research, celebrate it
4. Always give the user final choice - never override their desires, just inform
5. Include ALL custom pages/features the user requested - evaluate each one
6. Be encouraging but honest
7. Make website-related recommendations very detailed: describe pages/components and the reasoning behind each

MANDATORY — MARKET POSITION (CRITICAL):
- The 'market_position' object MUST always be present and fully filled out
- 'current' MUST honestly state the client's position — even if it's 'No established market presence yet (new entrant)'
- short_term, mid_term, and long_term MUST describe realistic projected positions IF recommendations are executed properly
- Reference specific competitor names when describing projected competitive standing

MANDATORY — INDUSTRY VALUE (CRITICAL):
- 'industry_value' MUST always be present with global_total and local_total in USD
- Use real market research data — e.g., '\$8.5 Billion globally', '\$420 Million in Georgia'

MANDATORY — COMPETITOR ANALYSIS (CRITICAL):
- 'competitor_analysis' MUST include both DIRECT and INDIRECT competitors
- Direct = companies offering the SAME products/services
- Indirect = companies in adjacent markets competing for the same customer budget (e.g., for a website builder: theme sellers, payment platforms, SEO tools that might lose customers to an all-in-one solution)
- Each competitor MUST have: valuation/worth, a specific weakness, and how_we_beat_them (linking to the recommendations)

MANDATORY — SPECIFIC PAGES (CRITICAL):
- The 'website' category MUST recommend the EXACT pages this specific business needs to succeed — NOT generic pages
- Every page recommended must include WHY it's needed based on research findings
- Consider: competitor gap pages, industry-specific landing pages, conversion funnels, trust/proof pages, comparison pages, etc.

MANDATORY — LEADS (CRITICAL):
- leads_info.count MUST be at least 5 even if the research only found template leads
- If the deep research found real leads, reference them. If not, explain that tiered leads (primary contacts, secondary organizations, tertiary institutions) are available in the CRM
- NEVER report 0 leads — the system always generates at least template leads

8. Return ONLY valid JSON, no markdown code blocks";

    return $prompt;
}
