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

/**
 * VMO Website Generator
 * Generates complete, multi-page websites based on consultation and research
 */

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

class VMO_Website_Generator {
    
    private $api_key;
    private $deep_research;
    
    public function __construct() {
        $this->api_key = get_option('vmo_openai_api_key');
        require_once plugin_dir_path(__FILE__) . 'class-vmo-deep-research.php';
        $this->deep_research = new VMO_Deep_Research();
    }
    
    /**
     * Generate complete website from consultation data
     * This is the MAIN function called after consultation completion
     */
    public function generate_complete_website($user_id, $consultation_data, $research_data = null) {
        error_log('🏗️ VMO Website Generator: Starting website generation...');
        
        // Extract business intelligence from consultation
        $business_intelligence = $this->extract_business_intelligence($consultation_data);

        // --- DOMAIN LOCKING ENFORCEMENT ---
        // Security: Ensure the project is strictly tied to the installation domain.
        // This prevents generating websites for unauthorized domains (e.g. generating for blue.com on yellow.com).
        $current_host = parse_url(get_site_url(), PHP_URL_HOST);
        $current_host = preg_replace('/^www\./', '', $current_host);
        
        // Force the domain in the business intelligence to match the current installation
        $business_intelligence['website_domain'] = $current_host;
        $business_intelligence['website_url'] = get_site_url();
        
        error_log("🔒 Domain Locked: Enforcing project domain to {$current_host}");
        // ----------------------------------
        
        // If no research provided, conduct it now
        if (!$research_data) {
            error_log('🔍 No research data provided, conducting deep research...');
            $research_data = $this->deep_research->conduct_deep_research($business_intelligence);
        }
        
        // Generate website architecture plan
        $architecture = $this->plan_website_architecture($business_intelligence, $research_data);
        
        // Generate design system (colors, fonts, style)
        $design_system = $this->create_design_system($business_intelligence, $research_data);
        
        // Generate each page
        $pages = [];
        foreach ($architecture['pages'] as $page_config) {
            error_log("📄 Generating page: {$page_config['slug']}");
            $page_content = $this->generate_page(
                $page_config,
                $business_intelligence,
                $research_data,
                $design_system
            );
            $pages[] = $page_content;
        }
        
        // Generate business documents
        $documents = $this->generate_business_documents($business_intelligence, $research_data);
        
        // Create website package
        $website_package = [
            'business_intelligence' => $business_intelligence,
            'research_data' => $research_data,
            'architecture' => $architecture,
            'design_system' => $design_system,
            'pages' => $pages,
            'documents' => $documents,
            'preview_url' => '',
            'published_url' => '',
            'status' => 'draft',
            'created_at' => current_time('mysql'),
            'updated_at' => current_time('mysql')
        ];
        
        // Store website in database
        $website_id = $this->store_website($user_id, $website_package);
        $website_package['id'] = $website_id;
        
        // Generate preview URL
        $website_package['preview_url'] = $this->create_preview($user_id, $website_id, $website_package);
        
        // Initialize KPI tracking
        $this->initialize_kpi_tracking($user_id, $business_intelligence);
        
        error_log('✅ VMO Website Generator: Website generation complete!');
        
        return $website_package;
    }
    
    /**
     * Extract structured business intelligence from consultation conversation
     */
    private function extract_business_intelligence($consultation_data) {
        error_log('🧠 Extracting business intelligence from consultation...');
        
        $conversation_log = $consultation_data['conversation_log'] ?? [];
        
        // Build full conversation context
        $conversation_text = '';
        foreach ($conversation_log as $message) {
            $role = $message['type'] === 'user' ? 'Customer' : 'Consultant';
            $conversation_text .= "{$role}: {$message['content']}\n\n";
        }
        
        $prompt = "Analyze this business consultation conversation and extract structured business intelligence:

CONSULTATION CONVERSATION:
{$conversation_text}

EXTRACTION TASK:
Extract and structure the following information in JSON format:

{
  \"business_name\": \"Exact business name mentioned\",
  \"business_type\": \"Type/category of business\",
  \"industry\": \"Specific industry\",
  \"tagline\": \"Tagline if mentioned, or create compelling one\",
  \"description\": \"2-3 sentence business description\",
  \"mission\": \"Mission statement\",
  \"vision\": \"Vision statement\",
  \"values\": [\"Core value 1\", \"Core value 2\", \"Core value 3\"],
  \"services\": [
    {
      \"name\": \"Service 1\",
      \"description\": \"What it includes\",
      \"benefits\": [\"Benefit 1\", \"Benefit 2\"]
    }
  ],
  \"target_market\": {
    \"demographics\": \"Age, income, location, etc.\",
    \"psychographics\": \"Values, interests, lifestyle\",
    \"pain_points\": [\"Problem 1\", \"Problem 2\"],
    \"goals\": [\"Goal 1\", \"Goal 2\"]
  },
  \"unique_selling_proposition\": \"What makes this business unique\",
  \"competitive_advantages\": [\"Advantage 1\", \"Advantage 2\"],
  \"location\": {
    \"city\": \"City\",
    \"state\": \"State\",
    \"country\": \"Country\",
    \"service_area\": \"Geographic area served\"
  },
  \"contact\": {
    \"phone\": \"Phone if mentioned\",
    \"email\": \"Email if mentioned\",
    \"address\": \"Physical address if mentioned\"
  },
  \"pricing_strategy\": \"Pricing approach mentioned\",
  \"brand_personality\": \"Professional/Friendly/Modern/Traditional/etc.\",
  \"tone_of_voice\": \"How the business should communicate\",
  \"call_to_action\": \"Primary action for website visitors\",
  \"goals\": [\"Business goal 1\", \"Business goal 2\"],
  \"features_needed\": [\"Feature 1\", \"Feature 2\"],
  \"content_preferences\": \"Style, tone, approach preferences\"
}

IMPORTANT:
- Extract actual information from the conversation
- For missing information, infer intelligently based on context
- Create professional, compelling copy
- Ensure consistency and coherence
- Return ONLY valid JSON, no extra text";

        $response = $this->call_openai($prompt, 3000);
        
        // Clean response and parse JSON
        $response = trim($response);
        $response = preg_replace('/```json\s*/', '', $response);
        $response = preg_replace('/```\s*$/', '', $response);
        
        $intelligence = json_decode($response, true);
        
        if (!$intelligence) {
            error_log('❌ Failed to extract business intelligence, using fallback');
            $intelligence = $this->create_fallback_intelligence($conversation_log);
        }
        
        error_log('✅ Business intelligence extracted successfully');
        return $intelligence;
    }
    
    /**
     * Plan complete website architecture
     * Checks for turnkey blueprints first, then falls back to AI generation
     */
    private function plan_website_architecture($business_intelligence, $research_data) {
        error_log('🏗️ Planning website architecture...');
        
        $business_type = $business_intelligence['business_type'] ?? 'business';
        $services = $business_intelligence['services'] ?? [];
        
        // 🔧 TURNKEY BLUEPRINT CHECK - Use pre-configured architecture if available
        $blueprint = $this->get_turnkey_blueprint($business_type, $business_intelligence);
        if ($blueprint) {
            error_log("✅ Using Turnkey Blueprint for: {$blueprint['name']}");
            return $this->convert_blueprint_to_architecture($blueprint, $business_intelligence);
        }
        
        // Fallback to AI-generated architecture
        $prompt = "As a website architect, plan the complete structure for this website:

BUSINESS CONTEXT:
" . json_encode($business_intelligence, JSON_PRETTY_PRINT) . "

RESEARCH INSIGHTS:
" . ($research_data['research_summary'] ?? 'No research summary available') . "

IMPORTANT: Include 'Privacy Policy', 'Terms of Service', and 'Cookie Policy' in the footer links.

ARCHITECTURE TASK:
Design a comprehensive multi-page website structure. Return ONLY valid JSON:

{
  \"total_pages\": 5,
  \"pages\": [
    {
      \"title\": \"Home\",
      \"slug\": \"home\",
      \"purpose\": \"Welcome visitors and showcase value proposition\",
      \"sections\": [
        {\"type\": \"hero\", \"content_focus\": \"Compelling headline and CTA\"},
        {\"type\": \"services\", \"content_focus\": \"Service overview\"},
        {\"type\": \"benefits\", \"content_focus\": \"Why choose us\"},
        {\"type\": \"testimonials\", \"content_focus\": \"Social proof\"},
        {\"type\": \"cta\", \"content_focus\": \"Get started\"}
      ],
      \"priority\": 1
    },
    {
      \"title\": \"About\",
      \"slug\": \"about\",
      \"purpose\": \"Build trust and credibility\",
      \"sections\": [
        {\"type\": \"story\", \"content_focus\": \"Company story\"},
        {\"type\": \"mission\", \"content_focus\": \"Mission and values\"},
        {\"type\": \"team\", \"content_focus\": \"Team members\"},
        {\"type\": \"credentials\", \"content_focus\": \"Certifications\"}
      ],
      \"priority\": 2
    }
  ],
    \"navigation\": [\"Home\", \"About\", \"Services\", \"Contact\"],
    \"footer_sections\": [\"contact\", \"social\", \"legal\"],
    \"footer_links\": [
        {\"text\": \"Privacy Policy\", \"url\": \"/privacy-policy\"},
        {\"text\": \"Terms of Service\", \"url\": \"/terms-of-service\"},
        {\"text\": \"Cookie Policy\", \"url\": \"/cookie-policy\"}
    ],
    \"conversion_goals\": [\"Goal 1\", \"Goal 2\"]
}

Create 5-7 pages optimized for this business type. Return ONLY valid JSON.";

        $response = $this->call_openai($prompt, 2500);
        
        // Parse JSON
        $response = trim($response);
        $response = preg_replace('/```json\s*/', '', $response);
        $response = preg_replace('/```\s*$/', '', $response);
        
        $architecture = json_decode($response, true);
        
        if (!$architecture) {
            error_log('❌ Failed to parse architecture, using default');
            $architecture = $this->create_default_architecture();
        }

        // Auto-inject Legal Pages
        $architecture['pages'][] = [
            'title' => 'Privacy Policy',
            'slug' => 'privacy-policy',
            'purpose' => 'Legal compliance',
            'sections' => [['type' => 'text', 'content_focus' => 'GDPR/CCPA privacy policy text']],
            'priority' => 10
        ];
        $architecture['pages'][] = [
            'title' => 'Terms of Service',
            'slug' => 'terms-of-service', 
            'purpose' => 'Legal compliance',
            'sections' => [['type' => 'text', 'content_focus' => 'Terms of service agreement']],
            'priority' => 11
        ];
        
        error_log('✅ Website architecture planned');
        return $architecture;
    }
    
    /**
     * Create comprehensive design system
     */
    private function create_design_system($business_intelligence, $research_data) {
        error_log('🎨 Creating design system...');
        
        $industry = $business_intelligence['industry'] ?? 'business';
        $brand_personality = $business_intelligence['brand_personality'] ?? 'professional';
        
        $prompt = "As a brand designer, create a comprehensive design system:

BUSINESS CONTEXT:
- Industry: {$industry}
- Brand Personality: {$brand_personality}
- Tone: " . ($business_intelligence['tone_of_voice'] ?? 'professional and approachable') . "

RESEARCH INSIGHTS:
" . ($research_data['competitor_analysis']['analysis'] ?? 'Competitor analysis not available') . "

DESIGN SYSTEM TASK:
Create a complete design system. Return ONLY valid JSON:

{
  \"colors\": {
    \"primary\": {
      \"hex\": \"#0066CC\",
      \"rgb\": \"0, 102, 204\",
      \"usage\": \"Primary buttons, headers, key elements\"
    },
    \"secondary\": {
      \"hex\": \"#FF6B35\",
      \"rgb\": \"255, 107, 53\",
      \"usage\": \"Accents, CTAs, highlights\"
    },
    \"accent\": {
      \"hex\": \"#6C757D\",
      \"rgb\": \"108, 117, 125\",
      \"usage\": \"Supporting elements\"
    },
    \"background\": {
      \"hex\": \"#FFFFFF\",
      \"rgb\": \"255, 255, 255\",
      \"usage\": \"Page background\"
    },
    \"text\": {
      \"primary\": \"#212529\",
      \"secondary\": \"#6C757D\",
      \"light\": \"#FFFFFF\"
    }
  },
  \"typography\": {
    \"heading_font\": \"Montserrat, sans-serif\",
    \"body_font\": \"Open Sans, sans-serif\",
    \"h1\": {\"size\": \"48px\", \"weight\": \"700\", \"line_height\": \"1.2\"},
    \"h2\": {\"size\": \"36px\", \"weight\": \"600\", \"line_height\": \"1.3\"},
    \"h3\": {\"size\": \"28px\", \"weight\": \"600\", \"line_height\": \"1.4\"},
    \"body\": {\"size\": \"16px\", \"weight\": \"400\", \"line_height\": \"1.6\"}
  },
  \"spacing\": {
    \"unit\": \"8px\",
    \"section_padding\": \"80px\",
    \"container_max_width\": \"1200px\"
  },
  \"buttons\": {
    \"primary\": {
      \"bg\": \"primary color\",
      \"text\": \"white\",
      \"hover\": \"darken 10%\",
      \"border_radius\": \"8px\",
      \"padding\": \"16px 32px\"
    },
    \"secondary\": {
      \"bg\": \"transparent\",
      \"text\": \"primary color\",
      \"border\": \"2px solid primary\",
      \"hover\": \"primary bg\",
      \"border_radius\": \"8px\",
      \"padding\": \"16px 32px\"
    }
  },
  \"style_notes\": \"Modern, clean, professional with friendly touches\"
}

Base colors on industry psychology and competitor analysis. Return ONLY valid JSON.";

        $response = $this->call_openai($prompt, 2000);
        
        // Parse JSON
        $response = trim($response);
        $response = preg_replace('/```json\s*/', '', $response);
        $response = preg_replace('/```\s*$/', '', $response);
        
        $design_system = json_decode($response, true);
        
        if (!$design_system) {
            error_log('❌ Failed to parse design system, using default');
            $design_system = $this->create_default_design_system();
        }
        
        error_log('✅ Design system created');
        return $design_system;
    }
    
    /**
     * Generate individual page content
     */
    private function generate_page($page_config, $business_intelligence, $research_data, $design_system) {
        error_log("📄 Generating page: {$page_config['slug']}");
        
        $business_name = $business_intelligence['business_name'] ?? 'Your Business';
        $services = json_encode($business_intelligence['services'] ?? [], JSON_PRETTY_PRINT);
        
        $prompt = "Generate complete, production-ready HTML for this page:

PAGE CONFIGURATION:
" . json_encode($page_config, JSON_PRETTY_PRINT) . "

BUSINESS INTELLIGENCE:
" . json_encode($business_intelligence, JSON_PRETTY_PRINT) . "

DESIGN SYSTEM:
" . json_encode($design_system, JSON_PRETTY_PRINT) . "

RESEARCH INSIGHTS:
" . substr($research_data['research_summary'] ?? '', 0, 500) . "

GENERATION TASK:
Create a complete, modern, responsive HTML page with:
1. Clean, semantic HTML5 structure with proper <!DOCTYPE html>
2. Include these CDN libraries in <head>:
   - Tailwind CSS: <script src=\"https://cdn.tailwindcss.com\"></script>
   - GSAP for animations: <script src=\"https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js\"></script>
   - GSAP ScrollTrigger: <script src=\"https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/ScrollTrigger.min.js\"></script>
3. Required meta tags in <head>:
   - <meta charset=\"UTF-8\">
   - <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">
   - <meta name=\"robots\" content=\"index, follow\">
   - Proper <title> and <meta name=\"description\">
4. Use Tailwind CSS classes for all styling (no inline styles except for custom brand colors)
5. Add GSAP scroll animations to sections (fade-in, slide-up effects)
6. Mobile-first responsive design with Tailwind breakpoints (sm:, md:, lg:, xl:)
7. SEO-optimized with proper heading hierarchy (one H1, structured H2/H3)
8. Compelling, conversion-focused copy (not lorem ipsum)
9. Call-to-action buttons with hover states
10. Security: Add rel=\"noopener noreferrer\" to all external links

GSAP ANIMATION EXAMPLE (include at bottom of body):
<script>
gsap.registerPlugin(ScrollTrigger);
gsap.utils.toArray('.animate-on-scroll').forEach(el => {
  gsap.fromTo(el, {opacity: 0, y: 50}, {
    opacity: 1, y: 0, duration: 0.8,
    scrollTrigger: {trigger: el, start: 'top 80%', toggleActions: 'play none none reverse'}
  });
});
</script>

IMPORTANT:
- Use Tailwind utility classes, NOT custom CSS
- Add 'animate-on-scroll' class to sections for GSAP animations
- Make buttons accessible with focus states
- Use the brand colors from design system via Tailwind custom config or inline style for accent colors only
- Return ONLY the complete HTML document, no explanations";

        $html = $this->call_openai($prompt, 4000);
        
        // Clean up response
        $html = trim($html);
        $html = preg_replace('/```html\s*/', '', $html);
        $html = preg_replace('/```\s*$/', '', $html);
        
        // Inject security meta tags if not present
        $html = $this->inject_security_headers($html);
        
        return [
            'title' => $page_config['title'],
            'slug' => $page_config['slug'],
            'content' => $html,
            'meta_description' => $this->extract_meta_description($html, $business_intelligence),
            'keywords' => $this->generate_page_keywords($page_config, $business_intelligence),
            'created_at' => current_time('mysql')
        ];
    }
    
    /**
     * Inject security headers into generated HTML
     */
    private function inject_security_headers($html) {
        $security_meta = '
    <!-- Security Headers -->
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
    <meta name="referrer" content="strict-origin-when-cross-origin">
    ';
        
        // Inject after <head> tag
        if (preg_match('/<head[^>]*>/i', $html)) {
            $html = preg_replace('/(<head[^>]*>)/i', '$1' . $security_meta, $html, 1);
        }
        
        // Ensure viewport meta exists
        if (stripos($html, 'viewport') === false) {
            $viewport = '<meta name="viewport" content="width=device-width, initial-scale=1.0">';
            $html = preg_replace('/(<head[^>]*>)/i', '$1' . "\n    " . $viewport, $html, 1);
        }
        
        // Add rel="noopener noreferrer" to external links
        $html = preg_replace_callback(
            '/<a([^>]*href=["\'](https?:\/\/[^"\']+)["\'][^>]*)>/i',
            function($matches) {
                $attrs = $matches[1];
                if (stripos($attrs, 'rel=') === false) {
                    return '<a' . $attrs . ' rel="noopener noreferrer">';
                }
                return $matches[0];
            },
            $html
        );
        
        return $html;
    }
    
    /**
     * Generate business documents
     */
    private function generate_business_documents($business_intelligence, $research_data) {
        error_log('📋 Generating business documents...');
        
        $documents = [];
        
        // 1. Business Plan
        $documents['business_plan'] = $this->generate_business_plan($business_intelligence, $research_data);
        
        // 2. Marketing Strategy
        $documents['marketing_strategy'] = $this->generate_marketing_strategy($business_intelligence, $research_data);
        
        // 3. SEO Strategy
        $documents['seo_strategy'] = $this->generate_seo_strategy($business_intelligence, $research_data);
        
        // 4. Content Calendar
        $documents['content_calendar'] = $this->generate_content_calendar($business_intelligence, $research_data);
        
        // 5. Competitive Analysis Report
        $documents['competitive_analysis'] = $research_data['competitor_analysis']['analysis'] ?? 'Not available';
        
        error_log('✅ Business documents generated');
        return $documents;
    }
    
    /**
     * Generate comprehensive business plan
     */
    private function generate_business_plan($business_intelligence, $research_data) {
        $business_name = $business_intelligence['business_name'] ?? 'Your Business';
        
        $prompt = "Create a comprehensive business plan:

BUSINESS: {$business_name}

BUSINESS INTELLIGENCE:
" . json_encode($business_intelligence, JSON_PRETTY_PRINT) . "

MARKET RESEARCH:
" . ($research_data['research_summary'] ?? '') . "

BUSINESS PLAN STRUCTURE:

# {$business_name} Business Plan

## Executive Summary
[2-3 paragraphs summarizing the business opportunity]

## Business Description
[Detailed description of the business, what it does, how it operates]

## Market Analysis
[Target market, market size, trends, customer needs]

## Competitive Analysis
[Key competitors, competitive advantages, differentiation strategy]

## Marketing & Sales Strategy
[How to reach customers, marketing channels, sales process]

## Operations Plan
[How the business will operate day-to-day]

## Financial Projections
[Revenue model, pricing strategy, growth projections]

## Goals & Milestones
[Short-term and long-term goals with timelines]

## Risk Analysis & Mitigation
[Potential challenges and how to address them]

Create a professional, comprehensive business plan in Markdown format.";

        return $this->call_openai($prompt, 4000);
    }
    
    /**
     * Generate marketing strategy document
     */
    private function generate_marketing_strategy($business_intelligence, $research_data) {
        $prompt = "Create a comprehensive digital marketing strategy:

BUSINESS INTELLIGENCE:
" . json_encode($business_intelligence, JSON_PRETTY_PRINT) . "

AUDIENCE ANALYSIS:
" . ($research_data['target_audience_analysis']['analysis'] ?? '') . "

Create a detailed marketing strategy covering:
1. Brand positioning
2. Target audience segments
3. Marketing channels (SEO, social media, email, PPC)
4. Content marketing strategy
5. Social media strategy
6. Email marketing approach
7. Paid advertising recommendations
8. Budget allocation
9. KPIs and success metrics
10. 90-day action plan

Format in Markdown with clear sections and actionable tactics.";

        return $this->call_openai($prompt, 3500);
    }
    
    /**
     * Generate SEO strategy
     */
    private function generate_seo_strategy($business_intelligence, $research_data) {
        $prompt = "Create a comprehensive SEO strategy:

BUSINESS INTELLIGENCE:
" . json_encode($business_intelligence, JSON_PRETTY_PRINT) . "

KEYWORD RESEARCH:
" . ($research_data['keyword_research']['analysis'] ?? '') . "

Create detailed SEO strategy covering:
1. On-page SEO checklist
2. Technical SEO requirements
3. Content strategy for ranking
4. Link building approach
5. Local SEO tactics
6. Keyword targeting priorities
7. Content cluster plan
8. Monthly SEO tasks
9. Success metrics and KPIs

Format in Markdown with actionable steps.";

        return $this->call_openai($prompt, 3000);
    }
    
    /**
     * Generate content calendar
     */
    private function generate_content_calendar($business_intelligence, $research_data) {
        $prompt = "Create a 90-day content calendar:

BUSINESS INTELLIGENCE:
" . json_encode($business_intelligence, JSON_PRETTY_PRINT) . "

KEYWORD RESEARCH:
" . ($research_data['keyword_research']['analysis'] ?? '') . "

Create a content calendar with:
- Blog post topics (2-3 per week for 90 days)
- Social media content themes
- Email newsletter topics
- Video content ideas
- Optimal publishing schedule

Format as a table in Markdown with: Date | Content Type | Topic | Keywords | Platform";

        return $this->call_openai($prompt, 2500);
    }
    
    /**
     * Store website in database
     */
    private function store_website($user_id, $website_package) {
        global $wpdb;
        $table = $wpdb->prefix . 'vmo_generated_websites';
        
        // Create table if needed
        $charset_collate = $wpdb->get_charset_collate();
        $sql = "CREATE TABLE IF NOT EXISTS {$table} (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            user_id bigint(20) NOT NULL,
            website_data longtext NOT NULL,
            status varchar(20) DEFAULT 'draft',
            preview_url varchar(500),
            published_url varchar(500),
            created_at datetime DEFAULT CURRENT_TIMESTAMP,
            updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY  (id),
            KEY user_id (user_id),
            KEY status (status)
        ) {$charset_collate};";
        
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
        
        // Insert website
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $wpdb->insert(
            $table,
            [
                'user_id' => $user_id,
                'website_data' => json_encode($website_package),
                'status' => 'draft'
            ],
            ['%d', '%s', '%s']
        );
        
        return $wpdb->insert_id;
    }
    
    /**
     * Create preview URL
     */
    private function create_preview($user_id, $website_id, $website_package) {
        // Store preview data in user meta for quick access
        update_user_meta($user_id, 'vmo_current_website_preview', [
            'website_id' => $website_id,
            'pages' => $website_package['pages'],
            'design_system' => $website_package['design_system']
        ]);
        
        // Return preview URL (handled by a separate endpoint)
        return home_url("/vmo-preview/?website_id={$website_id}&user_id={$user_id}");
    }
    
    /**
     * Initialize KPI tracking for the business
     */
    private function initialize_kpi_tracking($user_id, $business_intelligence) {
        global $wpdb;
        $table = $wpdb->prefix . 'vmo_business_kpis';
        
        // Create table if needed
        $charset_collate = $wpdb->get_charset_collate();
        $sql = "CREATE TABLE IF NOT EXISTS {$table} (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            user_id bigint(20) NOT NULL,
            metric_name varchar(100) NOT NULL,
            metric_value varchar(500),
            metric_type varchar(50),
            recorded_at datetime DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY  (id),
            KEY user_id (user_id),
            KEY metric_name (metric_name)
        ) {$charset_collate};";
        
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
        
        // Initialize baseline KPIs
        $initial_kpis = [
            ['metric_name' => 'website_status', 'metric_value' => 'draft', 'metric_type' => 'status'],
            ['metric_name' => 'pages_generated', 'metric_value' => '0', 'metric_type' => 'count'],
            ['metric_name' => 'consultation_completed', 'metric_value' => 'yes', 'metric_type' => 'status'],
            ['metric_name' => 'research_completed', 'metric_value' => 'yes', 'metric_type' => 'status'],
            ['metric_name' => 'business_name', 'metric_value' => $business_intelligence['business_name'] ?? '', 'metric_type' => 'info'],
        ];
        
        foreach ($initial_kpis as $kpi) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $wpdb->insert(
                $table,
                array_merge(['user_id' => $user_id], $kpi),
                ['%d', '%s', '%s', '%s']
            );
        }
        
        error_log('✅ KPI tracking initialized');
    }
    
    /**
     * Helper: Call OpenAI
     */
    private function call_openai($prompt, $max_tokens = 3000) {
        if (empty($this->api_key)) {
            return 'API key not configured';
        }
        
        // ✅ TOKEN DEDUCTION v8.1.0: Charge for website generation AI call
        $user_id = get_current_user_id();
        $token_cost = min(1500, max(300, intval($max_tokens * 0.3))); // 30% of max_tokens
        if (function_exists('vmo_deduct_tokens')) {
            if (!vmo_deduct_tokens($user_id, $token_cost, 'website_generation', 'Website content generation')) {
                return 'Insufficient tokens - Please top up your balance.';
            }
        }
        
        // ✅ FIX: Use VMO_OPENAI_MODEL and correct token parameter
        $model = defined('VMO_OPENAI_MODEL') ? VMO_OPENAI_MODEL : 'gpt-5.2';
        $token_param = function_exists('vmo_get_token_param') 
            ? vmo_get_token_param($model, $max_tokens) 
            : array('max_completion_tokens' => $max_tokens);
        
        $args = [
            'headers' => [
                'Authorization' => 'Bearer ' . $this->api_key,
                'Content-Type' => 'application/json',
            ],
            'body' => json_encode(array_merge([
                'model' => $model,
                'messages' => [
                    ['role' => 'system', 'content' => 'You are an expert website content creator and business strategist.'],
                    ['role' => 'user', 'content' => $prompt]
                ],
                'temperature' => 0.7
            ], $token_param)),
            'timeout' => 90
        ];
        
        $response = wp_remote_post('https://api.openai.com/v1/chat/completions', $args);
        
        // Fallback Logic
        if (is_wp_error($response) || wp_remote_retrieve_response_code($response) >= 400) {
            $body_d = json_decode($args['body'], true);
            $body_d['model'] = 'gpt-4o';
            $args['body'] = json_encode($body_d);
            $response = wp_remote_post('https://api.openai.com/v1/chat/completions', $args);
        }
        
        if (is_wp_error($response)) {
            error_log('OpenAI API Error: ' . $response->get_error_message());
            return 'Error generating content';
        }
        
        $body = json_decode(wp_remote_retrieve_body($response), true);
        return trim($body['choices'][0]['message']['content'] ?? 'No content generated');
    }
    
    /**
     * Fallback intelligence structure
     */
    private function create_fallback_intelligence($conversation_log) {
        return [
            'business_name' => 'Your Business',
            'business_type' => 'service business',
            'industry' => 'general',
            'description' => 'Professional services business',
            'services' => [],
            'target_market' => ['demographics' => 'General audience'],
            'location' => ['city' => 'Local', 'state' => '', 'country' => 'USA']
        ];
    }
    
    /**
     * Default website architecture
     */
    private function create_default_architecture() {
        return [
            'total_pages' => 5,
            'pages' => [
                [
                    'title' => 'Home',
                    'slug' => 'home',
                    'purpose' => 'Welcome and showcase value',
                    'sections' => [
                        ['type' => 'hero', 'content_focus' => 'Main value proposition'],
                        ['type' => 'services', 'content_focus' => 'What we offer'],
                        ['type' => 'benefits', 'content_focus' => 'Why choose us'],
                        ['type' => 'cta', 'content_focus' => 'Get started']
                    ],
                    'priority' => 1
                ],
                [
                    'title' => 'About',
                    'slug' => 'about',
                    'purpose' => 'Build trust',
                    'sections' => [
                        ['type' => 'story', 'content_focus' => 'Our story'],
                        ['type' => 'mission', 'content_focus' => 'Mission and values']
                    ],
                    'priority' => 2
                ],
                [
                    'title' => 'Services',
                    'slug' => 'services',
                    'purpose' => 'Detail offerings',
                    'sections' => [
                        ['type' => 'services_detail', 'content_focus' => 'Detailed services']
                    ],
                    'priority' => 3
                ],
                [
                    'title' => 'Contact',
                    'slug' => 'contact',
                    'purpose' => 'Enable communication',
                    'sections' => [
                        ['type' => 'contact_form', 'content_focus' => 'Contact information']
                    ],
                    'priority' => 4
                ]
            ],
            'navigation' => ['Home', 'About', 'Services', 'Contact']
        ];
    }
    
    /**
     * Default design system
     */
    private function create_default_design_system() {
        return [
            'colors' => [
                'primary' => ['hex' => '#0066CC', 'rgb' => '0, 102, 204'],
                'secondary' => ['hex' => '#FF6B35', 'rgb' => '255, 107, 53'],
                'background' => ['hex' => '#FFFFFF', 'rgb' => '255, 255, 255'],
                'text' => ['primary' => '#212529', 'secondary' => '#6C757D']
            ],
            'typography' => [
                'heading_font' => 'system-ui, sans-serif',
                'body_font' => 'system-ui, sans-serif'
            ]
        ];
    }
    
    private function extract_meta_description($html, $business_intelligence) {
        $business_name = $business_intelligence['business_name'] ?? 'Our Business';
        return "Welcome to {$business_name}. " . ($business_intelligence['description'] ?? 'Professional services you can trust.');
    }
    
    private function generate_page_keywords($page_config, $business_intelligence) {
        return [
            $business_intelligence['business_type'] ?? 'business',
            $page_config['title'],
            $business_intelligence['industry'] ?? 'services'
        ];
    }
    
    /**
     * Get matching turnkey blueprint for the business type
     * Maps various business descriptions to our pre-configured blueprints
     */
    private function get_turnkey_blueprint($business_type, $business_intelligence) {
        // Check if the blueprints class is loaded
        if (!class_exists('VMO_Turnkey_Business_Blueprints')) {
            error_log('⚠️ VMO_Turnkey_Business_Blueprints class not found');
            return null;
        }
        
        $business_type_lower = strtolower($business_type);
        $description_lower = strtolower($business_intelligence['description'] ?? '');
        $services_text = strtolower(json_encode($business_intelligence['services'] ?? []));
        $combined_text = $business_type_lower . ' ' . $description_lower . ' ' . $services_text;
        
        // Mapping keywords to blueprint types
        $blueprint_mappings = [
            'dropshipping' => ['dropshipping', 'dropship', 'drop ship', 'aliexpress', 'alibaba store', 'product reselling', 'online product store', 'ecommerce store'],
            'export_agency' => ['export', 'import', 'import/export', 'trade agency', 'commodity', 'agricultural export', 'international trade', 'b2b trade', 'sourcing agent'],
            'va_agency' => ['virtual assistant', 'va agency', 'remote assistant', 'administrative services', 'outsourcing', 'staffing agency', 'bpo', 'business process'],
            'print_on_demand' => ['print on demand', 'print-on-demand', 'pod', 't-shirt', 'custom apparel', 'merch', 'merchandise', 'custom products'],
            'content_agency' => ['content agency', 'content writing', 'copywriting', 'seo agency', 'seo services', 'digital marketing', 'blog writing', 'content marketing', 'article writing'],
            'local_service' => ['cleaning', 'lawn care', 'handyman', 'plumbing', 'electrician', 'home services', 'local service', 'field service', 'repair service', 'maintenance', 'hvac', 'landscaping', 'moving', 'painting'],
            'affiliate_marketing' => ['affiliate', 'affiliate marketing', 'review site', 'comparison site', 'niche site', 'blog monetization', 'product reviews'],
            'digital_products' => ['digital product', 'online course', 'ebook', 'template', 'digital download', 'course creator', 'info product', 'membership site', 'training program', 'coaching']
        ];
        
        foreach ($blueprint_mappings as $blueprint_type => $keywords) {
            foreach ($keywords as $keyword) {
                if (strpos($combined_text, $keyword) !== false) {
                    error_log("🎯 Matched blueprint type: {$blueprint_type} (keyword: {$keyword})");
                    return VMO_Turnkey_Business_Blueprints::get_business_blueprint($blueprint_type);
                }
            }
        }
        
        error_log("ℹ️ No turnkey blueprint matched for: {$business_type}");
        return null;
    }
    
    /**
     * Convert a turnkey blueprint to the website architecture format
     */
    private function convert_blueprint_to_architecture($blueprint, $business_intelligence) {
        $pages = [];
        $priority = 1;
        $navigation = [];
        
        // Convert each page from blueprint to architecture format
        foreach ($blueprint['website_structure']['pages'] as $page) {
            $sections = [];
            foreach ($page['sections'] as $section) {
                $sections[] = [
                    'type' => $section['type'],
                    'content_focus' => $section['description'] ?? $section['purpose'] ?? $section['type']
                ];
            }
            
            $pages[] = [
                'title' => $page['name'],
                'slug' => $page['slug'],
                'purpose' => $page['purpose'],
                'sections' => $sections,
                'priority' => $priority++
            ];
            
            // Add to navigation (limit to main pages)
            if ($priority <= 7 && !in_array($page['slug'], ['privacy-policy', 'terms-of-service', 'cookie-policy'])) {
                $navigation[] = $page['name'];
            }
        }
        
        // Build architecture
        $architecture = [
            'total_pages' => count($pages),
            'pages' => $pages,
            'navigation' => array_slice($navigation, 0, 6), // Max 6 nav items
            'footer_sections' => ['contact', 'social', 'legal', 'newsletter'],
            'conversion_goals' => $blueprint['kpis']['primary'] ?? ['Leads', 'Sales'],
            'turnkey_blueprint' => [
                'type' => $blueprint['id'] ?? 'unknown',
                'name' => $blueprint['name'],
                'email_roles' => $blueprint['email_roles'] ?? [],
                'automations' => $blueprint['automations'] ?? [],
                'legal_documents' => $blueprint['legal_documents'] ?? [],
                'daily_tasks' => $blueprint['daily_tasks'] ?? [],
                'kpis' => $blueprint['kpis'] ?? [],
                'education' => $blueprint['education'] ?? [],
                'income_potential' => $blueprint['income_potential'] ?? [],
                'startup_cost' => $blueprint['startup_cost'] ?? []
            ]
        ];
        
        error_log("✅ Converted blueprint to architecture with {$architecture['total_pages']} pages");
        return $architecture;
    }
}
