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

/**
 * VMO Lead Discovery Engine & CRM Population
 * 
 * "Access and Collect" Phase:
 * 1. Analyzes Business Profile & Location
 * 2. Uses AI to identify SPECIFIC public entities (Schools, Businesses, Orgs) in that area
 * 3. Populates the CRM (wp_vmo_contacts) with these "Cold Leads"
 * 4. Prepares "Strategic Outreach" email drafts for them
 * 
 * @package VMO_AI_Builder_Manager
 */

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

class VMO_Lead_Discovery {
    
    private static $instance = null;
    
    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Triggered after Deep Research or during Setup
        * Generates 25+ high-quality "Cold Leads" using TIERED CASCADING LOGIC
     */
    public function generate_initial_leads($user_id, $profile_data) {
        global $wpdb;
        
        $business_name = $profile_data['business_name'] ?? 'Business';
        $industry = $profile_data['industry'] ?? 'General';
        $location = $profile_data['location'] ?? 'Online';
        $target_audience = $profile_data['target_audience'] ?? 'Potential Clients';
        $unique_value = $profile_data['unique_value_proposition'] ?? '';
        
        // 1. ADVANCED TIERED PROMPT
        // This instructs the AI to think like a "Volume Sales Strategist"
        // It prioritizes finding "Gatekeepers" who hold the keys to many customers.
        $prompt = "Act as a Senior Sales Strategist.
        My Business: {$business_name} ({$industry})
        Location: {$location}
        Target Audience: {$target_audience}
        Value Prop: {$unique_value}
        
        OBJECTIVE: Identify 25 high-value leads using a TIERED STRATGEGY.
        Prioritize leads that offer BULK SALES or REPEATED VALUE over single one-off sales.
        
        LOGIC STACK:
        1. ANALYZE my business model. Do I sell to individuals (B2C) or companies (B2B)?
        2. IF B2C (e.g., Photographer, Clothier):
           - DO NOT target individuals (hard to find).
           - TIER 1 (Primary): Target small groups with high immediate need (e.g., 'Sorority Chapter', 'Wedding Planning Agency').
           - TIER 2 (Secondary): Target Gatekeepers (e.g., 'School Principal', 'Event Venue Manager').
           - TIER 3 (Tertiary): Target Large Institutions (e.g., 'University of X', 'Church of Y').
           - Focus on who has the BUDGET and the AUTHORITY to book for a group.
        3. IF B2B (e.g., Consultant, SaaS):
           - TIER 1: Direct Decision Makers at Ideal Companies.
           - TIER 2: Industry Associations or Partners.
        
        QUALIFICATION YARDSTICKS (Source from Public Data):
        - PRIORITY: Entities with PUBLISHED financial data (Annual Reports, Form 990s, Public Budgets).
        - Look for declared Marketing/Operational spend in financial statements or budget approvals.
        - Use Staff Headcount from LinkedIn/About Us pages as a proxy for revenue tier.
        - Check for Press Releases announcing Funding, Expansion, or New Department budgets.
        - For Non-Profits/Universities/Gov: Look for specific grant allocations or department budgets.
        
        RETURN JSON ARRAY of 25 Leads:
        [
          {
            \"name\": \"Organization Name\",
            \"role\": \"Specific Job Title to Contact (e.g. Social Chair, Office Mgr)\",
            \"email\": \"Likely email address or best-guess format (e.g. info@company.com) or 'Check Website'\",
            \"phone\": \"Published phone number if available, or empty string\",
            \"address\": \"Physical address if publicly listed, or empty string\",
            \"website\": \"Organization website URL if known, or empty string\",
            \"tier\": \"Tier 1/2/3\",
            \"rationale\": \"Why them? (e.g. 'Controls budget for 500 students')\",
            \"strategy\": \"The angle: 'Partner for bulk student discounts'\"
          }
        ]";
        
        // Call OpenAI (using Mini for speed/cost or 5.2 for depth - using 5.2 as this is high-value data)
        // DEDUCT TOKENS: Finding real leads is a high-value action ~1500 tokens
        // SECURITY FIX: Enforce token availability before execution to prevent financial loss.
        if (function_exists('vmo_deduct_tokens')) {
            $deducted = vmo_deduct_tokens($user_id, 1500, 'lead_discovery', 'AI Strategic Lead Discovery');
            if (!$deducted) {
                // Insufficient tokens - Do not proceed with OpenAI call
                error_log("VMO Lead Discovery halted: Insufficient tokens for user ID $user_id");
                return 0;
            }
        }
        
        $ai_response = $this->call_openai_api($prompt, 2500);
        
        // 🚨 FALLBACK MECHANISM: Ensure leads are generated "No Matter What"
        // If AI fails (content filter, json error, or timeout), generate synthetic/representative leads
        // so the user has a starting point in their CRM.
        if (!$ai_response || empty($ai_response)) {
            error_log("VMO Lead Discovery: AI failed to return valid JSON. Generating fallback leads.");
            $ai_response = $this->generate_fallback_leads($industry, $location);
        }

        // 2. Populate CRM
        $contacts_table = $wpdb->prefix . 'vmo_contacts';
        $inserted_count = 0;
        
        foreach ($ai_response as $lead) {
            // Normalize email key: accept both 'email' and legacy 'email_pattern'
            $lead_email = $lead['email'] ?? $lead['email_pattern'] ?? '';
            $lead_phone = $lead['phone'] ?? '';
            $lead_address = $lead['address'] ?? '';
            $lead_website = $lead['website'] ?? '';

            // Check duplications
            $exists = $wpdb->get_var($wpdb->prepare(
                "SELECT id FROM $contacts_table WHERE user_id = %d AND (company = %s OR email = %s)", 
                $user_id, 
                $lead['name'], 
                $lead_email
            ));
            
            if (!$exists) {
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                $wpdb->insert($contacts_table, [
                    'user_id' => $user_id,
                    'full_name' => $lead['role'], // e.g. "The Principal" or "Owner"
                    'company' => $lead['name'],
                    'email' => $this->sanitize_lead_email($lead_email),
                    'phone' => sanitize_text_field($lead_phone),
                    'lifecycle_stage' => 'lead', // Cold Lead
                    'source' => 'vmo_ai_discovery',
                    'notes' => 'AI Strategy: ' . ($lead['strategy'] ?? '') . ($lead_address ? "\nAddress: " . $lead_address : '') . ($lead_website ? "\nWebsite: " . $lead_website : ''),
                    'created_at' => current_time('mysql'),
                    'updated_at' => current_time('mysql')
                ]);
                $inserted_count++;
            }
        }
        
        return $inserted_count;
    }

    /**
     * Generate Strategic Cold Email Content for these specific leads
     */
    public function generate_cold_outreach_campaign($user_id, $leads, $profile_data) {
        // Logic to create a "Draft Campaign" in vmo_email_campaigns
        // tailored specifically to "Schools" or "Local Businesses" found above.
        // Returns the Campaign ID.
        // Implementation similar to VMO_AI_Email_Campaign_Generator but specialized for "Cold Outreach"
        
        $campaign_generator = new VMO_AI_Email_Campaign_Generator();
        // ... (Would call specific generator method)
    }

    /**
     * Generate fallback lead templates when AI fails.
     * These are prospect archetypes, not fabricated real contacts.
     */
    private function generate_fallback_leads($industry, $location) {
        $fallbacks = [];
        $types = ['Direct', 'Gatekeeper', 'Partner'];
        
        // Create 5 representative lead templates without fake contact details
        for ($i = 1; $i <= 5; $i++) {
            $fallbacks[] = [
                'name' => "Potential {$industry} Prospect Type #{$i} ({$location})",
                'role' => 'Owner/Manager',
                'email' => '',
                'strategy' => "This is a prospect template for your sector in {$location}. Replace it with a verified real contact from public sources before outreach.",
                'type' => $types[array_rand($types)]
            ];
        }
        return $fallbacks;
    }

    private function call_openai_api($prompt, $max_tokens = 1500) {
        // Optional user-supplied Semrush enhancement only. This is never a default dependency.
        $semrush_key = get_user_meta(get_current_user_id(), 'vmo_semrush_api_key', true);
        $extra_context = '';
        
        // If a user connected their own Semrush account, note that premium SEO data may be available.
        if ($semrush_key) {
            $extra_context = ' [SYSTEM NOTE: User connected an optional Semrush account. Use Semrush-style keyword and intent reasoning only if that user-provided integration is active.]';
            $prompt .= $extra_context;
        }

        $api_key = get_option('vmo_openai_api_key');
        if (!$api_key) return [];
        
        // ✅ FIX: GPT-5.2 requires max_completion_tokens, not max_tokens
        $_ld_model = 'gpt-5.2-2025-12-11'; // High IQ for finding real places
        $_ld_body = array_merge([
            'model' => $_ld_model,
            'messages' => [
                ['role' => 'system', 'content' => 'You are a Lead Generation Expert. Return only valid JSON.'],
                ['role' => 'user', 'content' => $prompt]
            ],
            'temperature' => 0.7,
            'store' => false
        ], function_exists('vmo_get_token_param') ? vmo_get_token_param($_ld_model, $max_tokens) : ['max_tokens' => $max_tokens]);
        $args = [
            'body' => json_encode($_ld_body),
            'headers' => [
                'Authorization' => 'Bearer ' . $api_key,
                'Content-Type' => 'application/json'
            ],
            'timeout' => 45
        ];
        
        $response = wp_remote_post('https://api.openai.com/v1/chat/completions', $args);
        
        if (is_wp_error($response)) return [];
        
        $body = json_decode(wp_remote_retrieve_body($response), true);
        $content = $body['choices'][0]['message']['content'] ?? '[]';
        
        // Clean JSON markdown
        $content = str_replace('```json', '', $content);
        $content = str_replace('```', '', $content);
        
        return json_decode($content, true);
    }
    
    private function sanitize_lead_email($email) {
        if (strpos($email, '@') === false) return '';
        if ($email === 'N/A') return '';
        return sanitize_email($email);
    }
}
