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

/**
 * VMO AI Email Campaign Generator
 * 
 * Ultra-competitive email marketing system that BEATS Mailchimp by using:
 * - Weekly Deep Research for market intelligence
 * - GPT-5.5 for personalized content generation
 * - Dynamic product recommendations
 * - Behavioral targeting
 * - A/B testing with AI optimization
 * 
 * Cost: 600 tokens per campaign (AI work at 70% profit margin)
 * Sending: 2 tokens per email
 * 
 * @package VMO_AI_Builder_Manager
 * @version 2.0.0
 */

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

class VMO_AI_Email_Campaign_Generator {
    
    /**
     * OpenAI API key
     */
    private $openai_api_key;
    private $campaign_token_charge_suspended = false;
    
    /**
     * Constructor
     */
    public function __construct() {
        $this->openai_api_key = defined('OPENAI_API_KEY') ? OPENAI_API_KEY : get_option('vmo_openai_api_key', '');
    }
    
    /**
     * Generate complete AI-powered email campaign
     * 
     * This is the MAIN function that makes VMO ultra-competitive with Mailchimp
     * 
     * @param string $install_id User's installation ID
     * @param array $campaign_data Campaign parameters
     * @return array Campaign content ready to send
     */
    public function generate_campaign($install_id, $campaign_data) {
        // Extract campaign parameters
        $business_data = isset($campaign_data['business_data']) ? $campaign_data['business_data'] : [];
        $campaign_type = isset($campaign_data['type']) ? $campaign_data['type'] : 'promotional';
        $audience = isset($campaign_data['audience']) ? $campaign_data['audience'] : 'all';
        $products = isset($campaign_data['products']) ? $campaign_data['products'] : [];
        $charge_tokens = !isset($campaign_data['charge_tokens']) || $campaign_data['charge_tokens'] !== false;
        $token_cost = function_exists('vmo_get_token_cost') ? (int) vmo_get_token_cost('email_campaign') : 945;
        $tokens_charged = false;

        if ($charge_tokens && function_exists('vmo_deduct_tokens')) {
            $user_id = get_current_user_id();
            if (!vmo_deduct_tokens($user_id, $token_cost, 'email_campaign', 'Email campaign AI generation')) {
                return ['success' => false, 'error' => 'Insufficient tokens. Please top up your balance.'];
            }
            $tokens_charged = true;
        }

        $previous_suspended = $this->campaign_token_charge_suspended;
        $this->campaign_token_charge_suspended = true;
        try {
            // Step 1: Get Deep Research insights (integrates with weekly research)
            $research_insights = $this->get_deep_research_insights($install_id, $business_data);
            
            // Step 2: Generate AI-powered content using GPT-5.5
            $campaign_content = $this->generate_ai_content($business_data, $campaign_type, $audience, $research_insights, $products);
            
            // Step 3: Create beautiful HTML email template
            $html_content = $this->build_email_html($campaign_content, $products);
            
            // Step 4: Generate A/B test variants (subject lines)
            $ab_test_subjects = $this->generate_ab_test_subjects($campaign_content['subject'], $business_data);
        } finally {
            $this->campaign_token_charge_suspended = $previous_suspended;
        }
        
        return [
            'success' => true,
            'campaign_id' => $this->generate_campaign_id(),
            'subject' => $campaign_content['subject'],
            'ab_test_subjects' => $ab_test_subjects,
            'html_content' => $html_content,
            'plain_text' => $campaign_content['plain_text'],
            'preview_text' => $campaign_content['preview_text'],
            'research_insights' => $research_insights,
            'personalization_data' => $campaign_content['personalization'],
            'estimated_engagement' => $this->predict_engagement($campaign_content),
            'tokens_charged' => $tokens_charged,
            'tokens_used' => $tokens_charged ? $token_cost : 0,
        ];
    }
    
    /**
     * Get Deep Research insights from weekly research system
     * 
     * @param string $install_id Installation ID
     * @param array $business_data Business information
     * @return array Research insights
     */
    private function get_deep_research_insights($install_id, $business_data) {
        global $wpdb;
        
        // Get latest weekly deep research data
        $research_table = $wpdb->prefix . 'vmo_manager_research';
        $latest_research = $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM $research_table 
             WHERE install_id = %s 
             ORDER BY created_at DESC 
             LIMIT 1",
            $install_id
        ));
        
        if ($latest_research) {
            $research_data = json_decode($latest_research->research_data, true);
            
            return [
                'market_trends' => isset($research_data['market_trends']) ? $research_data['market_trends'] : [],
                'competitor_analysis' => isset($research_data['competitors']) ? $research_data['competitors'] : [],
                'industry_news' => isset($research_data['news']) ? $research_data['news'] : [],
                'customer_insights' => isset($research_data['customer_behavior']) ? $research_data['customer_behavior'] : [],
                'recommended_topics' => isset($research_data['content_ideas']) ? $research_data['content_ideas'] : []
            ];
        }
        
        // Fallback: Generate fresh insights using AI
        return $this->generate_fresh_insights($business_data);
    }
    
    /**
     * Generate fresh market insights using AI (if no Deep Research data available)
     * 
     * @param array $business_data Business information
     * @return array Fresh insights
     */
    private function generate_fresh_insights($business_data) {
        $business_name = isset($business_data['business_name']) ? $business_data['business_name'] : 'your business';
        $industry = isset($business_data['industry']) ? $business_data['industry'] : 'general';
        
        $prompt = "Analyze the current market for a {$industry} business called '{$business_name}'. 
        
Provide:
1. Top 3 market trends right now
2. Key customer pain points
3. 3 email campaign ideas that would resonate
4. Recommended tone and messaging approach

Keep it concise and actionable. Format as JSON.";
        
        $response = $this->call_openai_api($prompt, function_exists('vmo_get_model') ? vmo_get_model('mini') : 'gpt-5.5-mini', 500);
        
        if ($response['success']) {
            $insights = json_decode($response['content'], true);
            return $insights ? $insights : ['market_trends' => [], 'campaign_ideas' => []];
        }
        
        return ['market_trends' => [], 'campaign_ideas' => []];
    }
    
    /**
     * Generate AI-powered campaign content using GPT-5.5
     * 
     * This is where the MAGIC happens - creates content that BEATS manual templates
     * 
     * @param array $business_data Business information
     * @param string $campaign_type Type of campaign (promotional, newsletter, announcement, etc.)
     * @param string $audience Target audience
     * @param array $research_insights Research data
     * @param array $products Products to feature
     * @return array Campaign content
     */
    private function generate_ai_content($business_data, $campaign_type, $audience, $research_insights, $products) {
        $business_name = isset($business_data['business_name']) ? $business_data['business_name'] : 'our business';
        $industry = isset($business_data['industry']) ? $business_data['industry'] : 'general';
        $brand_voice = isset($business_data['brand_voice']) ? $business_data['brand_voice'] : 'professional and friendly';
        
        // Build comprehensive prompt
        $prompt = $this->build_content_generation_prompt(
            $business_name,
            $industry,
            $brand_voice,
            $campaign_type,
            $audience,
            $research_insights,
            $products
        );
        
        // Call AI for content generation
        $response = $this->call_openai_api($prompt, function_exists('vmo_get_model') ? vmo_get_model('mini') : 'gpt-5.5-mini', 1500);
        
        if ($response['success']) {
            $content = json_decode($response['content'], true);
            
            if ($content) {
                return [
                    'subject' => isset($content['subject']) ? $content['subject'] : "Update from {$business_name}",
                    'preview_text' => isset($content['preview']) ? $content['preview'] : '',
                    'headline' => isset($content['headline']) ? $content['headline'] : '',
                    'body' => isset($content['body']) ? $content['body'] : '',
                    'cta_text' => isset($content['cta']) ? $content['cta'] : 'Learn More',
                    'cta_url' => isset($content['cta_url']) ? $content['cta_url'] : '#',
                    'plain_text' => isset($content['plain_text']) ? $content['plain_text'] : '',
                    'personalization' => isset($content['personalization_tags']) ? $content['personalization_tags'] : [],
                    'tone' => isset($content['tone']) ? $content['tone'] : 'friendly'
                ];
            }
        }
        
        // Fallback content
        return [
            'subject' => "Update from {$business_name}",
            'preview_text' => "You won't want to miss this...",
            'headline' => "Great News!",
            'body' => "We have something special to share with you.",
            'cta_text' => 'Learn More',
            'cta_url' => '#',
            'plain_text' => "Update from {$business_name}\n\nWe have something special to share with you.",
            'personalization' => [],
            'tone' => 'friendly'
        ];
    }
    
    /**
     * Build comprehensive prompt for GPT-5.5 content generation
     * 
     * @param string $business_name Business name
     * @param string $industry Industry
     * @param string $brand_voice Brand voice
     * @param string $campaign_type Campaign type
     * @param string $audience Audience
     * @param array $research_insights Research data
     * @param array $products Products
     * @return string GPT-5.5 prompt
     */
    private function build_content_generation_prompt($business_name, $industry, $brand_voice, $campaign_type, $audience, $research_insights, $products) {
        $products_text = '';
        if (!empty($products)) {
            $products_text = "\n\nProducts to feature:\n";
            foreach ($products as $product) {
                $products_text .= sprintf(
                    "- %s: %s (Price: %s)\n",
                    isset($product['name']) ? $product['name'] : 'Product',
                    isset($product['description']) ? $product['description'] : '',
                    isset($product['price']) ? $product['price'] : 'Contact for pricing'
                );
            }
        }
        
        $research_text = '';
        if (!empty($research_insights['market_trends'])) {
            $research_text = "\n\nMarket Insights:\n" . implode("\n", array_slice($research_insights['market_trends'], 0, 3));
        }
        
        return "You are an expert email marketing copywriter. Create a high-converting {$campaign_type} email campaign.

BUSINESS DETAILS:
- Business: {$business_name}
- Industry: {$industry}
- Brand Voice: {$brand_voice}
- Target Audience: {$audience}
{$research_text}
{$products_text}

CREATE:
1. Compelling subject line (under 50 characters, creates urgency/curiosity)
2. Preview text (80-100 characters, complements subject)
3. Attention-grabbing headline
4. Engaging body copy (3-4 paragraphs, focus on benefits not features)
5. Strong call-to-action
6. Plain text version
7. Personalization tags ({{first_name}}, {{company}}, {{last_purchase}}, etc.)

GOALS:
- Hook reader in first 3 seconds
- Address a specific pain point
- Create emotional connection
- Drive action (click/purchase/reply)
- Sound human, not corporate

Return as JSON with keys: subject, preview, headline, body, cta, cta_url, plain_text, personalization_tags, tone";
    }
    
    /**
     * Build beautiful HTML email template with glassmorphism design
     * 
     * @param array $content Campaign content
     * @param array $products Products to feature
     * @return string HTML email
     */
    private function build_email_html($content, $products = []) {
        // Load glassy email templates for consistent branding
        require_once dirname(__FILE__) . '/class-vmo-glassy-email-templates.php';
        $glassy = new VMO_Glassy_Email_Templates();
        
        $headline = isset($content['headline']) ? $content['headline'] : '';
        $body = isset($content['body']) ? $content['body'] : '';
        $cta_text = isset($content['cta_text']) ? $content['cta_text'] : 'Learn More';
        $cta_url = isset($content['cta_url']) ? $content['cta_url'] : '#';
        
        // Build product cards HTML (if products included)
        $product_cards_html = '';
        if (!empty($products)) {
            $product_cards_html = $this->build_product_cards_html($products);
        }
        
        // Build complete email HTML
        $html = '
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>' . esc_html($content['subject']) . '</title>
    <style>
        ' . $this->get_email_css() . '
    </style>
</head>
<body>
    <div class="email-wrapper">
        <div class="email-container">
            
            <!-- Header -->
            <div class="email-header">
                <img src="' . plugins_url('../assets/vmo-icon.svg', __FILE__) . '" alt="VMO" class="logo">
            </div>
            
            <!-- Main Content -->
            <div class="email-content">
                <h1 class="headline">' . esc_html($headline) . '</h1>
                <div class="body-text">
                    ' . wpautop($body) . '
                </div>
                
                <!-- Product Cards (if any) -->
                ' . $product_cards_html . '
                
                <!-- CTA Button -->
                <div class="cta-container">
                    <a href="' . esc_url($cta_url) . '" class="cta-button">' . esc_html($cta_text) . '</a>
                </div>
            </div>
            
            <!-- Footer -->
            <div class="email-footer">
                <p>You received this email because you subscribed to updates.</p>
                <p><a href="{{unsubscribe_url}}">Unsubscribe</a> | <a href="{{manage_preferences_url}}">Manage Preferences</a></p>
            </div>
            
        </div>
    </div>
</body>
</html>';
        
        return $html;
    }
    
    /**
     * Build HTML product cards for in-email shopping
     * 
     * Creates beautiful product displays with Stripe Payment Links
     * 
     * @param array $products Array of products
     * @return string HTML product cards
     */
    private function build_product_cards_html($products) {
        $html = '<div class="product-grid">';
        
        foreach ($products as $product) {
            $name = isset($product['name']) ? $product['name'] : 'Product';
            $description = isset($product['description']) ? $product['description'] : '';
            $price = isset($product['price']) ? $product['price'] : '$0.00';
            $image = isset($product['image']) ? $product['image'] : '';
            $stripe_payment_link = isset($product['stripe_payment_link']) ? $product['stripe_payment_link'] : '#';
            
            $html .= '
            <div class="product-card">
                ' . ($image ? '<img src="' . esc_url($image) . '" alt="' . esc_attr($name) . '" class="product-image">' : '') . '
                <h3 class="product-name">' . esc_html($name) . '</h3>
                <p class="product-description">' . esc_html($description) . '</p>
                <div class="product-footer">
                    <span class="product-price">' . esc_html($price) . '</span>
                    <a href="' . esc_url($stripe_payment_link) . '" class="product-buy-button">Buy Now</a>
                </div>
            </div>';
        }
        
        $html .= '</div>';
        
        return $html;
    }
    
    /**
     * Get CSS styles for email (inline-friendly)
     * 
     * @return string CSS styles
     */
    private function get_email_css() {
        return '
        body {
            margin: 0;
            padding: 0;
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        .email-wrapper {
            padding: 40px 20px;
        }
        .email-container {
            max-width: 600px;
            margin: 0 auto;
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(20px);
            border-radius: 20px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
            overflow: hidden;
        }
        .email-header {
            text-align: center;
            padding: 30px 20px;
            background: linear-gradient(135deg, #0fe1ff 0%, #7c5cff 100%);
        }
        .logo {
            height: 60px;
            filter: drop-shadow(0 4px 8px rgba(0, 0, 0, 0.2));
        }
        .email-content {
            padding: 40px 30px;
        }
        .headline {
            font-size: 32px;
            font-weight: 700;
            color: #1a1a2e;
            margin: 0 0 20px 0;
            line-height: 1.3;
        }
        .body-text {
            font-size: 16px;
            color: #4a4a4a;
            line-height: 1.6;
            margin-bottom: 30px;
        }
        .product-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin: 30px 0;
        }
        .product-card {
            background: #f8f9fa;
            border-radius: 12px;
            padding: 20px;
            text-align: center;
        }
        .product-image {
            width: 100%;
            height: 200px;
            object-fit: cover;
            border-radius: 8px;
            margin-bottom: 15px;
        }
        .product-name {
            font-size: 20px;
            font-weight: 600;
            color: #1a1a2e;
            margin: 0 0 10px 0;
        }
        .product-description {
            font-size: 14px;
            color: #666;
            margin: 0 0 15px 0;
        }
        .product-footer {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .product-price {
            font-size: 24px;
            font-weight: 700;
            color: #7c5cff;
        }
        .product-buy-button {
            background: linear-gradient(135deg, #0fe1ff 0%, #7c5cff 100%);
            color: white;
            padding: 10px 20px;
            border-radius: 8px;
            text-decoration: none;
            font-weight: 600;
            transition: transform 0.2s;
        }
        .product-buy-button:hover {
            transform: scale(1.05);
        }
        .cta-container {
            text-align: center;
            margin: 40px 0;
        }
        .cta-button {
            display: inline-block;
            background: linear-gradient(135deg, #0fe1ff 0%, #7c5cff 100%);
            color: white;
            padding: 16px 40px;
            border-radius: 12px;
            text-decoration: none;
            font-size: 18px;
            font-weight: 600;
            box-shadow: 0 8px 20px rgba(124, 92, 255, 0.3);
            transition: transform 0.2s;
        }
        .cta-button:hover {
            transform: translateY(-2px);
        }
        .email-footer {
            background: #f8f9fa;
            padding: 30px;
            text-align: center;
            font-size: 12px;
            color: #999;
        }
        .email-footer a {
            color: #7c5cff;
            text-decoration: none;
        }
        
        /* Mobile responsive */
        @media only screen and (max-width: 600px) {
            .email-wrapper {
                padding: 20px 10px;
            }
            .email-content {
                padding: 30px 20px;
            }
            .headline {
                font-size: 24px;
            }
            .product-grid {
                grid-template-columns: 1fr;
            }
        }
        ';
    }
    
    /**
     * Generate A/B test subject line variants
     * 
     * @param string $original_subject Original subject line
     * @param array $business_data Business data
     * @return array Array of subject line variants
     */
    private function generate_ab_test_subjects($original_subject, $business_data) {
        $prompt = "Generate 3 A/B test variants for this email subject line: '{$original_subject}'

Requirements:
- Each variant should test a different approach (urgency, curiosity, benefit, personalization)
- Keep under 50 characters
- Maintain the core message
- Make them distinct enough to learn from

Return as JSON array: ['variant1', 'variant2', 'variant3']";
        
        $response = $this->call_openai_api($prompt, function_exists('vmo_get_model') ? vmo_get_model('nano') : 'gpt-5.5-nano', 200);
        
        if ($response['success']) {
            $variants = json_decode($response['content'], true);
            if (is_array($variants)) {
                return $variants;
            }
        }
        
        // Fallback variants
        return [
            $original_subject,
            $original_subject . " (Limited Time)",
            "Quick Question: " . $original_subject
        ];
    }
    
    /**
     * Predict engagement score using AI
     * 
     * @param array $content Campaign content
     * @return array Engagement prediction
     */
    private function predict_engagement($content) {
        // Simple heuristic scoring (can be enhanced with ML model later)
        $score = 50; // Base score
        
        // Subject line analysis
        $subject = isset($content['subject']) ? $content['subject'] : '';
        if (strlen($subject) < 50) $score += 10;
        if (preg_match('/\?/', $subject)) $score += 5; // Questions increase open rate
        if (preg_match('/\d/', $subject)) $score += 5; // Numbers increase engagement
        
        // Body analysis
        $body = isset($content['body']) ? $content['body'] : '';
        $word_count = str_word_count($body);
        if ($word_count >= 100 && $word_count <= 300) $score += 15; // Ideal length
        
        // CTA analysis
        $cta = isset($content['cta_text']) ? $content['cta_text'] : '';
        if (strlen($cta) < 25) $score += 10; // Clear, concise CTAs work better
        
        return [
            'score' => min(100, $score),
            'predicted_open_rate' => min(100, $score * 0.4),
            'predicted_click_rate' => min(100, $score * 0.1),
            'confidence' => 'medium'
        ];
    }
    
    /**
     * Generate custom email content based on user intent
     */
    public function generate_custom_email($prompt, $format) {
        $response = $this->call_openai_api($prompt, function_exists('vmo_get_model') ? vmo_get_model('mini') : 'gpt-5.5-mini', 1500);
        
        if (!$response['success']) {
            return ['error' => $response['error']];
        }
        
        $content = $response['content'];
        // Extract JSON if wrapped in code blocks
        if (preg_match('/```json\s*(.*?)\s*```/s', $content, $matches)) {
            $content = $matches[1];
        }
        
        $data = json_decode($content, true);
        if (!$data) {
            // Fallback if JSON parsing fails
            return [
                'subject' => 'Generated Email',
                'plain_body' => $content,
                'html_body' => $format === 'html' ? nl2br($content) : null
            ];
        }
        
        return $data;
    }

    /**
     * Call OpenAI API
     * 
     * @param string $prompt Prompt to send
     * @param string $model Model to use (defaults to VMO_OPENAI_MODEL)
     * @param int $max_tokens Max tokens
     * @return array API response
     */
    private function call_openai_api($prompt, $model = null, $max_tokens = 1000) {
        if (empty($this->openai_api_key)) {
            return ['success' => false, 'error' => 'AI API key not configured'];
        }
        
        // ✅ TOKEN DEDUCTION v8.1.0: Charge for email campaign AI generation
        $user_id = get_current_user_id();
        if (!$this->campaign_token_charge_suspended && function_exists('vmo_deduct_tokens')) {
            $token_cost = function_exists('vmo_get_token_cost') ? (int) vmo_get_token_cost('email_campaign') : 945;
            if (!vmo_deduct_tokens($user_id, $token_cost, 'email_campaign', 'Email campaign AI generation')) {
                return ['success' => false, 'error' => 'Insufficient tokens. Please top up your balance.'];
            }
        }
        
        // Use centralized model registry
        if ($model === null || strpos((string) $model, 'gpt-4') !== false || strpos((string) $model, 'gpt-5.2') !== false) {
            $model = function_exists('vmo_get_model') ? vmo_get_model('mini') : (defined('VMO_OPENAI_MODEL') ? VMO_OPENAI_MODEL : 'gpt-5.5-mini');
        }
        
        $args = [
            'timeout' => 90,
            'headers' => [
                'Authorization' => 'Bearer ' . $this->openai_api_key,
                'Content-Type' => 'application/json'
            ],
            // ✅ FIX: GPT-5.x requires max_completion_tokens, not max_tokens
            'body' => json_encode(array_merge([
                'model' => $model,
                'messages' => [
                    ['role' => 'system', 'content' => 'You are an expert email marketing copywriter who creates high-converting campaigns.'],
                    ['role' => 'user', 'content' => $prompt]
                ],
                'temperature' => 0.7
            ], function_exists('vmo_get_token_param') ? vmo_get_token_param($model, $max_tokens) : ['max_tokens' => $max_tokens]))
        ];

        $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_data = json_decode($args['body'], true);
            $body_data['model'] = function_exists('vmo_get_model') ? vmo_get_model('fallback') : 'gpt-5.5-nano';
            $args['body'] = json_encode($body_data);
            $response = wp_remote_post('https://api.openai.com/v1/chat/completions', $args);
        }
        
        if (is_wp_error($response)) {
            return ['success' => false, 'error' => $response->get_error_message()];
        }
        
        $body = json_decode(wp_remote_retrieve_body($response), true);
        
        if (isset($body['choices'][0]['message']['content'])) {
            return [
                'success' => true,
                'content' => $body['choices'][0]['message']['content']
            ];
        }
        
        return ['success' => false, 'error' => 'Invalid API response'];
    }
    
    /**
     * Generate unique campaign ID
     * 
     * @return string Campaign ID
     */
    private function generate_campaign_id() {
        return 'vmo_campaign_' . time() . '_' . wp_generate_password(8, false);
    }
}
