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

/**
 * VMO Business Document Generator
 * Generates professional business documents in various formats
 */

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

class VMO_Document_Generator {
    
    private $api_key;
    
    public function __construct() {
        $this->api_key = get_option('vmo_openai_api_key');
        
        // AJAX endpoints for Executive Report
        add_action('wp_ajax_vmo_get_executive_report', array($this, 'ajax_get_executive_report'));
    }
    
    /**
     * Generate all business documents and store them
     */
    public function generate_all_documents($user_id, $business_intelligence, $research_data) {
        error_log('📄 Generating context-aware business documents...');
        
        // 1. Determine which documents are crucial for this business
        $needed_documents_list = $this->determine_needed_documents($business_intelligence, $research_data);
        
        $documents = [];

        // Always include the Core Business Plan
        $documents[] = [
            'type' => 'business_plan',
            'title' => 'Business Plan',
            'content' => $this->generate_business_plan($business_intelligence, $research_data),
            'format' => 'markdown',
            'icon' => 'file-text',
            'description' => 'Comprehensive business plan with market analysis and strategy',
            'category' => 'Planning'
        ];

        // Generate the AI-determined documents
        foreach ($needed_documents_list as $doc_req) {
            // Skip business plan as we already did it
            if ($doc_req['type'] === 'business_plan') continue;

            $content = $this->generate_specific_document($doc_req, $business_intelligence, $research_data);
            
            if (!empty($content)) {
                $documents[] = [
                    'type' => $doc_req['type'],
                    'title' => $doc_req['title'],
                    'content' => $content,
                    'format' => 'markdown',
                    'icon' => $doc_req['icon'] ?? 'file-text',
                    'description' => $doc_req['description'] ?? 'Generated business document',
                    'category' => $doc_req['category'] ?? 'General'
                ];
            }
        }
        
        // Store documents in database
        $this->store_documents($user_id, $documents);
        
        error_log('✅ All business documents generated and stored (' . count($documents) . ' docs)');
        
        return $documents;
    }

    /**
     * Ask AI to determine which documents are needed based on business type
     */
    private function determine_needed_documents($business_intelligence, $research_data) {
        $prompt = "You are an expert business consultant. Analyze this business and create a list of crucial documents they need.
        
BUSINESS: " . json_encode($business_intelligence) . "
TYPE: " . ($business_intelligence['business_type'] ?? 'General') . "
CONTEXT: " . substr($research_data['research_summary'] ?? '', 0, 500) . "

Available Document Categories:
1. Legal / Governance (Incorporation, Bylaws, Operating Agreements)
2. Contracts (Service Agreements, NDAs, Employment)
3. Financial (Projections, Cash Flow, Budgets)
4. Operations (SOPs, Safety Manuals, policies)
5. Sales/Marketing (Plans, Proposals, Case Studies)
6. HR (Handbooks, Reviews)

Return a JSON array of objects with keys: 'type' (slug), 'title', 'category', 'description', 'icon' (feather icon name).
Select 5-10 CRITICAL documents for this specific business type. Do not just list generic ones.
Example JSON:
[
    {\"type\": \"service_agreement\", \"title\": \"Client Service Agreement\", \"category\": \"Legal\", \"description\": \"Standard contract for services\", \"icon\": \"file-text\"}
]";

        // Call OpenAI (Mocking the call wrapper here since I don't see the helper method in this class, using raw wp_remote_post or assuming a helper exists)
        // I'll reuse the logic from generate_image or similar if available, otherwise write the call.
        // Since I don't see a `call_ai` helper in the previous read, I'll implement a basic one or look for one.
        // Actually the class has `api_key` in constructor so it expects to call.
        
        $response = $this->call_openai_json($prompt);
        if (is_array($response)) {
            return $response;
        }

        // Fallback default list if AI fails
        return [
            ['type' => 'marketing_strategy', 'title' => 'Marketing Strategy', 'category' => 'Marketing', 'icon' => 'trending-up'],
            ['type' => 'financial_projections', 'title' => 'Financial Projections', 'category' => 'Finance', 'icon' => 'dollar-sign'],
            ['type' => 'operating_agreement', 'title' => 'Operating Agreement', 'category' => 'Legal', 'icon' => 'shield'],
            ['type' => 'service_contract', 'title' => 'Service Contract Template', 'category' => 'Legal', 'icon' => 'pen-tool'],
            ['type' => 'brand_guidelines', 'title' => 'Brand Guidelines', 'category' => 'Brand', 'icon' => 'award']
        ];
    }

    /**
     * Generate content for a specific document type
     */
    private function generate_specific_document($doc_req, $business_intelligence, $research_data) {
        $prompt = "Create a professional business document.
        
DOCUMENT TYPE: {$doc_req['title']} ({$doc_req['description']})
BUSINESS: " . json_encode($business_intelligence) . "

Write the full document in Markdown format. Be professional, detailed, and legally/operationally sound (as a draft).
Include necessary placeholders like [Date], [Signatures] where appropriate.
";
        
        $content = $this->call_openai_text($prompt);
        return $content ?: "# {$doc_req['title']}\n\n(Generation failed. Please try again.)";
    }

    /**
     * Helper to call OpenAI for JSON
     */
    private function call_openai_json($prompt) {
        if (empty($this->api_key)) return false;
        
        // ✅ TOKEN DEDUCTION v8.1.0: Charge for document generation AI call
        $user_id = get_current_user_id();
        if (function_exists('vmo_deduct_tokens')) {
            if (!vmo_deduct_tokens($user_id, 400, 'document', 'Document generation AI call')) {
                error_log('VMO Document Generator: Insufficient tokens for user ' . $user_id);
                return false;
            }
        }
        
        $body = [
            'model' => 'gpt-4o', // or gpt-4-turbo
            'messages' => [
                ['role' => 'system', 'content' => 'You are a JSON generator. Return only valid JSON.'],
                ['role' => 'user', 'content' => $prompt]
            ],
            'response_format' => ['type' => 'json_object']
        ];
        
        $response = wp_remote_post('https://api.openai.com/v1/chat/completions', [
            'headers' => ['Authorization' => 'Bearer ' . $this->api_key, 'Content-Type' => 'application/json'],
            'body' => json_encode($body),
            'timeout' => 60
        ]);
        
        if (is_wp_error($response)) return false;
        $data = json_decode(wp_remote_retrieve_body($response), true);
        $content = $data['choices'][0]['message']['content'] ?? '';
        $json = json_decode($content, true);
        return $json['documents'] ?? $json; // Handle if wrapped in key
    }

    /**
     * Helper to call OpenAI for Text
     */
    private function call_openai_text($prompt) {
        if (empty($this->api_key)) return false;
        
        // ✅ TOKEN DEDUCTION v8.1.0: Charge for document text generation
        $user_id = get_current_user_id();
        if (function_exists('vmo_deduct_tokens')) {
            if (!vmo_deduct_tokens($user_id, 500, 'document', 'Document text generation')) {
                error_log('VMO Document Generator: Insufficient tokens for user ' . $user_id);
                return false;
            }
        }
        
        $body = [
            'model' => 'gpt-4o',
            'messages' => [
                ['role' => 'system', 'content' => 'You are a professional business consultant.'],
                ['role' => 'user', 'content' => $prompt]
            ]
        ];
        
        $response = wp_remote_post('https://api.openai.com/v1/chat/completions', [
            'headers' => ['Authorization' => 'Bearer ' . $this->api_key, 'Content-Type' => 'application/json'],
            'body' => json_encode($body),
            'timeout' => 120
        ]);
        
        if (is_wp_error($response)) return false;
        $data = json_decode(wp_remote_retrieve_body($response), true);
        return $data['choices'][0]['message']['content'] ?? '';
    }
    
    /**
     * Store documents in database
     */
    private function store_documents($user_id, $documents) {
        global $wpdb;
        $table = $wpdb->prefix . 'vmo_business_documents';
        
        // 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,
            doc_type varchar(100) NOT NULL,
            title varchar(255) NOT NULL,
            content longtext,
            format varchar(50) DEFAULT 'markdown',
            icon varchar(50),
            description text,
            category varchar(100),
            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 doc_type (doc_type),
            KEY category (category)
        ) {$charset_collate};";
        
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
        
        // Delete existing documents for this user (fresh start)
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $wpdb->delete($table, ['user_id' => $user_id], ['%d']);
        
        // Insert new documents
        foreach ($documents as $doc) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $wpdb->insert(
                $table,
                [
                    'user_id' => $user_id,
                    'doc_type' => $doc['type'],
                    'title' => $doc['title'],
                    'content' => $doc['content'],
                    'format' => $doc['format'],
                    'icon' => $doc['icon'],
                    'description' => $doc['description'],
                    'category' => $doc['category']
                ],
                ['%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s']
            );
        }
    }
    
    /**
     * Get documents for a user
     */
    public function get_user_documents($user_id, $category = null) {
        global $wpdb;
        $table = $wpdb->prefix . 'vmo_business_documents';
        
        if ($category) {
            return $wpdb->get_results($wpdb->prepare(
                "SELECT * FROM {$table} WHERE user_id = %d AND category = %s ORDER BY created_at DESC",
                $user_id,
                $category
            ));
        }
        
        return $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM {$table} WHERE user_id = %d ORDER BY category, title",
            $user_id
        ));
    }
    
    /**
     * Get single document
     */
    public function get_document($document_id, $user_id) {
        global $wpdb;
        $table = $wpdb->prefix . 'vmo_business_documents';
        
        return $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM {$table} WHERE id = %d AND user_id = %d",
            $document_id,
            $user_id
        ));
    }
    
    /**
     * Generate document content using AI
     */
    private function generate_business_plan($business_intelligence, $research_data) {
        $business_name = $business_intelligence['business_name'] ?? 'Your Business';
        
        $prompt = "Create a comprehensive, professional business plan:

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

MARKET RESEARCH:
" . ($research_data['research_summary'] ?? 'Market research summary not available') . "

COMPETITIVE LANDSCAPE:
" . substr($research_data['competitor_analysis']['analysis'] ?? '', 0, 1000) . "

Generate a complete business plan in Markdown format with these sections:

# {$business_name} - Business Plan

## Executive Summary
Write a compelling 2-3 paragraph summary of the business opportunity, value proposition, and key success factors.

## Business Description
- What we do
- How we operate
- Our unique approach
- Why we exist

## Market Analysis
- Target market size and demographics
- Market trends and growth potential
- Customer needs and pain points
- Market opportunities

## Competitive Analysis
- Key competitors
- Our competitive advantages
- Market positioning
- Differentiation strategy

## Marketing & Sales Strategy
- Customer acquisition strategy
- Marketing channels and tactics
- Sales process and conversion strategy
- Pricing and positioning

## Operations Plan
- Service/product delivery process
- Technology and tools
- Team structure and roles
- Quality assurance

## Financial Plan
- Revenue model
- Pricing strategy
- Cost structure
- Growth projections (Year 1-3)

## Goals & Milestones
### Short-term (0-6 months)
- Specific, measurable goals

### Medium-term (6-12 months)
- Growth targets

### Long-term (1-3 years)
- Strategic objectives

## Risk Analysis
- Potential challenges
- Mitigation strategies
- Contingency plans

Make it professional, detailed, and actionable. Use specific data from the research where available.";

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

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

TARGET AUDIENCE:
" . ($research_data['target_audience_analysis']['analysis'] ?? 'Audience data not available') . "

Generate a detailed marketing strategy in Markdown:

# Digital Marketing Strategy

## Brand Positioning
- Market position
- Unique value proposition
- Brand personality and voice

## Target Audience Segments
- Primary audience
- Secondary audiences
- Persona details

## Marketing Channels

### SEO (Search Engine Optimization)
- On-page optimization
- Content strategy
- Link building approach
- Local SEO tactics

### Content Marketing
- Blog strategy
- Video content
- Lead magnets
- Content distribution

### Social Media Marketing
- Platform selection
- Content themes
- Posting frequency
- Engagement strategy

### Email Marketing
- List building strategy
- Campaign types
- Automation workflows
- Segmentation approach

### Paid Advertising
- Google Ads strategy
- Social media ads
- Budget allocation
- Targeting approach

## Budget Allocation
Recommended monthly marketing budget distribution across channels

## KPIs & Success Metrics
- Website traffic goals
- Conversion rate targets
- Lead generation goals
- ROI expectations

## 90-Day Action Plan
Specific tasks and priorities for the first 90 days

Make it actionable with specific tactics and timelines.";

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

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

KEYWORD RESEARCH:
" . ($research_data['keyword_research']['analysis'] ?? 'Keyword data not available') . "

Generate detailed SEO strategy in Markdown:

# SEO Strategy & Implementation Plan

## SEO Goals
- Ranking objectives
- Traffic targets
- Conversion goals

## Keyword Strategy
### Primary Keywords (10-15)
Target keywords with search volume and difficulty ratings

### Secondary Keywords (20-30)
Supporting keywords for content

### Long-tail Keywords (15-20)
Low-competition opportunities

## On-Page SEO Checklist
- Title tag optimization
- Meta description best practices
- Header tag structure
- Content optimization
- Image optimization
- Internal linking
- Schema markup

## Technical SEO
- Site speed optimization
- Mobile responsiveness
- SSL certificate
- XML sitemap
- Robots.txt
- Core Web Vitals

## Content Strategy
### Content Pillars
5-7 main topic areas

### Content Calendar
Blog post topics mapped to keywords

### Content Types
- How-to guides
- Service pages
- FAQs
- Case studies
- Local pages

## Link Building Strategy
- Guest posting targets
- Local directory listings
- Industry partnerships
- Content promotion

## Local SEO (if applicable)
- Google Business Profile optimization
- Local citations
- Review management
- Local content

## Measurement & Reporting
- KPIs to track
- Tools to use
- Reporting frequency

## Monthly SEO Tasks
Checklist of ongoing activities

Provide specific, actionable recommendations.";

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

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

KEYWORDS:
" . ($research_data['keyword_research']['analysis'] ?? 'Keyword data not available') . "

Generate content calendar in Markdown table format:

# 90-Day Content Calendar

## Month 1

### Week 1
| Date | Type | Title | Primary Keyword | Platform | Notes |
|------|------|-------|----------------|----------|-------|
| [Date] | Blog | [Title] | [Keyword] | Website | [Purpose] |
| [Date] | Social | [Topic] | - | Instagram | [Theme] |

[Continue for 12 weeks]

## Content Themes by Week
- Week 1: [Theme]
- Week 2: [Theme]
[Continue...]

## Social Media Content
### Daily Posting Schedule
- Monday: [Type of post]
- Tuesday: [Type of post]
[Continue...]

### Content Mix
- 40% Educational
- 30% Promotional
- 20% Engaging/Entertainment
- 10% User-generated content

## Email Newsletter Topics
Monthly email themes and topics

Make it detailed with specific topics, not generic placeholders.";

        return $this->call_openai($prompt, 2500);
    }
    
    private function generate_brand_guidelines($business_intelligence) {
        $prompt = "Create brand guidelines document:

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

Generate comprehensive brand guidelines in Markdown:

# Brand Guidelines

## Brand Overview
- Brand story
- Mission statement
- Vision statement
- Core values

## Brand Personality
- Personality traits
- Brand archetype
- Emotional connection

## Visual Identity
### Logo Usage
- Primary logo
- Logo variations
- Clear space requirements
- Minimum sizes
- Incorrect usage examples

### Color Palette
- Primary colors (with HEX codes)
- Secondary colors
- Accent colors
- Color meanings and usage

### Typography
- Heading fonts
- Body fonts
- Font pairings
- Size hierarchy

### Imagery Style
- Photography style
- Illustration approach
- Image treatments
- What to avoid

## Brand Voice & Tone
### Voice Characteristics
- Professional yet approachable
- [Additional traits]

### Tone Variations
- Marketing materials: [Tone]
- Customer service: [Tone]
- Social media: [Tone]
- Formal communications: [Tone]

### Writing Style
- Sentence structure
- Word choices
- Grammar rules
- Formatting preferences

## Messaging Framework
### Value Proposition
One-sentence statement

### Key Messages
3-5 core messages

### Tagline
Brand tagline

## Application Examples
Examples of brand applied across materials

Make it comprehensive and professional.";

        return $this->call_openai($prompt, 2500);
    }
    
    private function generate_social_media_strategy($business_intelligence, $research_data) {
        $prompt = "Create platform-specific social media strategy:

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

TARGET AUDIENCE:
" . ($research_data['target_audience_analysis']['analysis'] ?? 'Audience data not available') . "

Generate social media strategy in Markdown:

# Social Media Strategy

## Platform Selection & Priority
- Platform 1: [Name] - Primary (Why?)
- Platform 2: [Name] - Secondary (Why?)
- Platform 3: [Name] - Tertiary (Why?)

## Platform-Specific Strategies

### [Primary Platform] Strategy
- Profile optimization
- Content themes
- Posting frequency
- Best posting times
- Content formats
- Hashtag strategy
- Engagement tactics
- Growth strategy

[Repeat for each platform]

## Content Pillars
1. [Pillar 1]: [Description]
2. [Pillar 2]: [Description]
3. [Pillar 3]: [Description]
4. [Pillar 4]: [Description]

## Content Mix
- Educational: 40%
- Entertaining: 20%
- Promotional: 20%
- Engaging: 20%

## Community Management
- Response time goals
- Engagement tactics
- Crisis management
- User-generated content strategy

## Social Media Advertising
- Ad objectives
- Targeting strategy
- Budget recommendations
- Creative approach

## Metrics & Analytics
KPIs for each platform

Provide specific, actionable strategies for each platform.";

        return $this->call_openai($prompt, 3000);
    }
    
    private function generate_email_marketing_plan($business_intelligence, $research_data) {
        $prompt = "Create email marketing strategy:

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

Generate email marketing plan in Markdown:

# Email Marketing Strategy

## List Building Strategy
- Lead magnets
- Opt-in forms placement
- Landing pages
- Growth tactics

## Email Campaigns

### Welcome Series (5-7 emails)
1. Email 1: Welcome & expectations
2. Email 2: Value delivery
3. Email 3: Social proof
[Continue...]

### Newsletter Strategy
- Frequency
- Content themes
- Structure
- Call-to-actions

### Promotional Campaigns
- Product launches
- Special offers
- Seasonal campaigns
- Event promotions

### Nurture Sequences
- Lead nurturing
- Post-purchase
- Re-engagement
- Abandoned cart (if e-commerce)

## Segmentation Strategy
- Segment 1: [Criteria and approach]
- Segment 2: [Criteria and approach]
[Continue...]

## Email Design
- Template structure
- Mobile optimization
- Brand consistency
- CTA placement

## Automation Workflows
Detailed workflows for key scenarios

## Testing & Optimization
- A/B testing plan
- Metrics to track
- Optimization process

## Compliance
- GDPR/CAN-SPAM compliance
- Privacy policy
- Unsubscribe process

Provide detailed, actionable email strategies.";

        return $this->call_openai($prompt, 2500);
    }
    
    private function generate_financial_projections($business_intelligence, $research_data) {
        $prompt = "Create financial projections and budget:

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

PRICING ANALYSIS:
" . ($research_data['pricing_analysis']['analysis'] ?? 'Pricing data not available') . "

Generate financial projections in Markdown:

# Financial Projections

## Revenue Model
- Revenue streams
- Pricing structure
- Unit economics

## Year 1 Projections

### Monthly Breakdown
| Month | Revenue | Expenses | Profit | Notes |
|-------|---------|----------|--------|-------|
[12 months of projections]

### Revenue Assumptions
- Customer acquisition rate
- Average transaction value
- Customer lifetime value
- Churn rate

## Cost Structure

### Startup Costs
- Initial investments
- Equipment/software
- Marketing launch
- Legal/administrative

### Monthly Operating Costs
- Fixed costs
- Variable costs
- Marketing budget
- Technology/tools
- Professional services

## Break-Even Analysis
- Break-even point
- Path to profitability
- Key milestones

## 3-Year Growth Projection
- Year 1: [Target]
- Year 2: [Target]
- Year 3: [Target]

## Budget Recommendations
Detailed budget allocation across departments

## Financial KPIs
Key metrics to track monthly

Provide realistic, detailed financial projections.";

        return $this->call_openai($prompt, 2500);
    }
    
    /**
     * Call OpenAI API
     */
    private function call_openai($prompt, $max_tokens = 3000) {
        if (empty($this->api_key)) {
            return '# Document Generation Unavailable\n\nOpenAI API key not configured.';
        }
        
        // ✅ TOKEN DEDUCTION v8.1.0: Charge for document generation (proportional to max_tokens)
        $user_id = get_current_user_id();
        $token_cost = min(1500, max(300, intval($max_tokens * 0.3))); // 30% of max_tokens, min 300, max 1500
        if (function_exists('vmo_deduct_tokens')) {
            if (!vmo_deduct_tokens($user_id, $token_cost, 'document', 'Document AI generation')) {
                return '# Insufficient Tokens\n\nPlease top up your token balance to generate documents.';
            }
        }
        
        // ✅ FIX: GPT-5.2 requires max_completion_tokens, not max_tokens
        $_dg_model = 'gpt-5.2-2025-12-11';
        $request_payload = array_merge([
            'model' => $_dg_model,
            'messages' => [
                [
                    'role' => 'system',
                    'content' => 'You are an expert business consultant and document creator. Generate professional, detailed, actionable business documents in Markdown format.'
                ],
                [
                    'role' => 'user',
                    'content' => $prompt
                ]
            ],
            'temperature' => 0.7
        ], function_exists('vmo_get_token_param') ? vmo_get_token_param($_dg_model, $max_tokens) : ['max_tokens' => $max_tokens]);
        
        $args = [
            'headers' => [
                'Authorization' => 'Bearer ' . $this->api_key,
                'Content-Type' => 'application/json',
            ],
            'body' => json_encode($request_payload),
            '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) {
            $request_payload['model'] = 'gpt-4o';
            // ✅ FIX: Swap max_completion_tokens back to max_tokens for gpt-4o
            if (isset($request_payload['max_completion_tokens'])) {
                $request_payload['max_tokens'] = $request_payload['max_completion_tokens'];
                unset($request_payload['max_completion_tokens']);
            }
            $args['body'] = json_encode($request_payload);
            $response = wp_remote_post('https://api.openai.com/v1/chat/completions', $args);
        }
        
        if (is_wp_error($response)) {
            error_log('Document Generator API Error: ' . $response->get_error_message());
            return '# Error\n\nFailed to generate document content.';
        }
        
        $body = json_decode(wp_remote_retrieve_body($response), true);
        return trim($body['choices'][0]['message']['content'] ?? '# Error\n\nNo content generated');
    }

    /**
     * AJAX Handler: Get Executive Report Data
     */
    public function ajax_get_executive_report() {
        check_ajax_referer('vmo_backend_nonce', 'nonce');
        
        $report = $this->generate_executive_report_data();
        
        if ($report) {
            wp_send_json_success($report);
        } else {
            wp_send_json_error(['message' => 'Could not generate report data']);
        }
    }

    /**
     * Gather all business intelligence for the Executive Report
     */
    public function generate_executive_report_data() {
        global $wpdb;
        $user_id = get_current_user_id();

        // Get Date Range (or default to last 30)
        $start_date = isset($_POST['start_date']) ? sanitize_text_field(wp_unslash($_POST['start_date'])) : date('Y-m-d', strtotime('-30 days'));
        $end_date = isset($_POST['end_date']) ? sanitize_text_field(wp_unslash($_POST['end_date'])) : date('Y-m-d');
        
        // Ensure valid stamps
        $start_ts = strtotime($start_date);
        $end_ts = strtotime($end_date . ' 23:59:59');
        
        // 1. FINANCIALS (Filtered by Date)
        $financials = [
            'total_revenue' => 0,
            'orders_count' => 0,
            'revenue_trend' => [],
            'revenue_labels' => []
        ];
        
        // Orders Logic
        $orders_table = $wpdb->prefix . 'vmo_store_orders';
        $table_check = $wpdb->get_var("SHOW TABLES LIKE '$orders_table'");
        if ($table_check === $orders_table) {
             $rows = $wpdb->get_results($wpdb->prepare(
                 "SELECT * FROM $orders_table 
                  WHERE user_id = %d 
                  AND status = 'paid' 
                  AND created_at BETWEEN %s AND %s
                  ORDER BY created_at ASC", 
                 $user_id,
                 $start_date . ' 00:00:00',
                 $end_date . ' 23:59:59'
             ), ARRAY_A);
             
             if ($rows) {
                 $financials['orders_count'] = count($rows);
                 $financials['total_revenue'] = array_sum(array_column($rows, 'amount_total')); 
                 
                 // Trend logic changes based on range duration
                 // If range > 3 months, group by Month. Else group by Day.
                 $days_diff = ($end_ts - $start_ts) / (60 * 60 * 24);
                 $group_by_month = $days_diff > 90;

                 $trend_data = [];
                 
                 foreach ($rows as $row) {
                     $d = strtotime($row['created_at']);
                     $key = $group_by_month ? date('M Y', $d) : date('M j', $d);
                     if (!isset($trend_data[$key])) $trend_data[$key] = 0;
                     $trend_data[$key] += (int)$row['amount_total'];
                 }
                 
                 $financials['revenue_trend'] = array_values($trend_data);
                 $financials['revenue_labels'] = array_keys($trend_data);
             }
        }

        // 2. TRAFFIC (Visits, Conversions, SEO)
        $traffic = [
            'visits_total' => 0,
            'conversion_rate' => 0,
            'traffic_trend' => [],
            'traffic_labels' => [],
            'conversion_trend' => [],
            'conversion_labels' => [],
            'seo_trend' => [],
            'seo_labels' => []
        ];
        
        $interactions_table = $wpdb->prefix . 'vmo_contact_interactions';
        $interactions_check = $wpdb->get_var("SHOW TABLES LIKE '$interactions_table'");
        if ($interactions_check === $interactions_table) {
            // Visits Total in Range
            $traffic['visits_total'] = $wpdb->get_var($wpdb->prepare(
                "SELECT COUNT(*) FROM $interactions_table 
                 WHERE user_id = %d 
                 AND interaction_type = 'website_visit' 
                 AND created_at BETWEEN %s AND %s",
                $user_id,
                $start_date . ' 00:00:00',
                $end_date . ' 23:59:59'
            ));
            
            // Daily Trend (Group by day always for simplicity, or bucket if huge)
            // We use the same grouping logic as revenue ideally, but let's stick to daily for granular charts
            // unless > 90 days.
            $days_diff = ($end_ts - $start_ts) / (60 * 60 * 24);
            $group_format = ($days_diff > 90) ? '%Y-%m' : '%Y-%m-%d';
            $php_format = ($days_diff > 90) ? 'M Y' : 'M j';

            $visit_rows = $wpdb->get_results($wpdb->prepare(
                "SELECT DATE_FORMAT(created_at, %s) as period, COUNT(*) as count 
                 FROM $interactions_table 
                 WHERE user_id = %d 
                 AND interaction_type = 'website_visit' 
                 AND created_at BETWEEN %s AND %s
                 GROUP BY period
                 ORDER BY period ASC",
                $group_format,
                $user_id,
                $start_date . ' 00:00:00',
                $end_date . ' 23:59:59'
            ));
            
            $trend_map = [];
            foreach ($visit_rows as $row) {
                // If grouped by month in SQL, period is 'YYYY-MM'. If day, 'YYYY-MM-DD'.
                // Convert to label
                $ts = strtotime($row->period . ($days_diff > 90 ? '-01' : '')); 
                $label = date($php_format, $ts);
                $trend_map[$label] = (int)$row->count;
            }
            
            $traffic['traffic_trend'] = array_values($trend_map);
            $traffic['traffic_labels'] = array_keys($trend_map);
            
            // Calculate SEO Trend (Proxy: Referrer = Google/Bing)
            // We'll query just for search engine referrers
            $seo_rows = $wpdb->get_results($wpdb->prepare(
                "SELECT DATE_FORMAT(created_at, %s) as period, COUNT(*) as count 
                 FROM $interactions_table 
                 WHERE user_id = %d 
                 AND interaction_type = 'website_visit' 
                 AND (full_details LIKE '%google%' OR full_details LIKE '%bing%' OR full_details LIKE '%yahoo%')
                 AND created_at BETWEEN %s AND %s
                 GROUP BY period
                 ORDER BY period ASC",
                $group_format,
                $user_id,
                $start_date . ' 00:00:00',
                $end_date . ' 23:59:59'
            ));
             
            $seo_map = [];
            // Initialize SEO map keys with traffic keys to keep alignment
            foreach(array_keys($trend_map) as $k) $seo_map[$k] = 0;
            
            foreach ($seo_rows as $row) {
                $ts = strtotime($row->period . ($days_diff > 90 ? '-01' : '')); 
                $label = date($php_format, $ts);
                if (isset($seo_map[$label])) $seo_map[$label] = (int)$row->count;
            }
            $traffic['seo_trend'] = array_values($seo_map);
            $traffic['seo_labels'] = array_keys($seo_map);

            // Calculate Conversion Rate Logic (Proxy: Leads + Sales / Visits)
            // This is complex to correlate perfectly by day without valid timestamps on everything.
            // We will do a rough "Global Conversion Rate" per period bucket from the traffic map.
            // Orders per period
            $conversions_map = []; 
            foreach(array_keys($trend_map) as $k) $conversions_map[$k] = 0;
            
            // If we have orders loaded, bucket them
            if (!empty($rows)) { // $rows is orders
                foreach($rows as $order) {
                    $d = strtotime($order['created_at']);
                    $key = date($php_format, $d);
                    if(isset($conversions_map[$key])) $conversions_map[$key]++;
                }
            }
            
            // Calculate %
            $final_conversion_trend = [];
            foreach ($trend_map as $period => $visits) {
                $orders = $conversions_map[$period] ?? 0;
                $rate = ($visits > 0) ? round(($orders / $visits) * 100, 2) : 0;
                $final_conversion_trend[] = $rate;
            }
            $traffic['conversion_trend'] = $final_conversion_trend;
            $traffic['conversion_labels'] = array_keys($trend_map);
            
            // Total Conversion Rate
            $traffic['conversion_rate'] = ($traffic['visits_total'] > 0) ? round(($financials['orders_count'] / $traffic['visits_total']) * 100, 2) : 0;
        }

        // 3. LEADS (Total)
        $leads = [
            'total_leads' => 0,
            'recent_lead' => 'None',
        ];
        
        $contacts_table = $wpdb->prefix . 'vmo_contacts';
        $contacts_check = $wpdb->get_var("SHOW TABLES LIKE '$contacts_table'");
        if ($contacts_check === $contacts_table) {
            $leads['total_leads'] = $wpdb->get_var($wpdb->prepare(
                "SELECT COUNT(*) FROM $contacts_table WHERE user_id = %d", 
                $user_id
            ));
        }

        // 4. VISION / DOCUMENTS
        $docs_table = $wpdb->prefix . 'vmo_business_documents';
        $vision_score = 0;
        $docs_check = $wpdb->get_var("SHOW TABLES LIKE '$docs_table'");
        if ($docs_check === $docs_table) {
            $doc_count = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM $docs_table WHERE user_id = %d", $user_id));
            // Arbitrary scoring: 5 docs = 100% vision documented
            $vision_score = min(100, ($doc_count * 20));
        }

        return [
            'business_name' => get_bloginfo('name'),
            'date' => date('F j, Y'),
            'period_start' => $start_date,
            'period_end' => $end_date,
            'financials' => $financials,
            'traffic' => $traffic,
            'leads' => $leads,
            'vision_score' => $vision_score
        ];
    }
}
