<?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')) {
            $token_cost = function_exists('vmo_get_token_cost') ? (int) vmo_get_token_cost('lead_discovery') : 1500;
            $deducted = vmo_deduct_tokens($user_id, $token_cost, '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);
        
        if (!$ai_response || empty($ai_response)) {
            error_log("VMO Lead Discovery: AI failed to return valid JSON. Template leads were not saved to CRM.");
            return 0;
        }

        // 2. Populate CRM
        if (!function_exists('vmo_crm_upsert_contact') || !function_exists('vmo_crm_log_interaction')) {
            error_log('VMO Lead Discovery: Central CRM helpers are unavailable. Leads were not saved.');
            return 0;
        }

        $contacts_table = $wpdb->prefix . 'vmo_contacts';
        if ($wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $contacts_table)) !== $contacts_table) {
            error_log('VMO Lead Discovery: Contacts table does not exist. Leads were not saved.');
            return 0;
        }
        $this->ensure_lead_tracking_columns($contacts_table);
        $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'] ?? '';
            $lead_source = $this->normalize_lead_tier($lead['tier'] ?? 'primary');

            $contact = vmo_crm_upsert_contact($user_id, array(
                'full_name' => sanitize_text_field($lead['role'] ?? ''),
                'company' => sanitize_text_field($lead['name'] ?? ''),
                'email' => $this->sanitize_lead_email($lead_email),
                'phone' => sanitize_text_field($lead_phone),
            ), array(
                'source' => 'lead_generation',
                'primary_category' => 'lead',
                'secondary_category' => $lead_source,
                'lifecycle_stage' => 'new',
                'job_title' => sanitize_text_field($lead['role'] ?? ''),
                'address' => sanitize_textarea_field($lead_address),
                'lead_score' => $lead_source === 'primary' ? 75 : ($lead_source === 'secondary' ? 60 : 45),
                'priority_level' => $lead_source === 'primary' ? 'high' : 'medium',
                'tags' => array('ai_lead_discovery', 'cold_lead', $lead_source),
                'notes' => 'AI Strategy: ' . sanitize_textarea_field($lead['strategy'] ?? '') . ($lead_address ? "\nAddress: " . sanitize_textarea_field($lead_address) : '') . ($lead_website ? "\nWebsite: " . esc_url_raw($lead_website) : ''),
                'acquisition_details' => array(
                    'generated_from' => 'lead_discovery',
                    'lead_source' => $lead_source,
                    'lead_verified' => true,
                    'tier' => sanitize_text_field($lead['tier'] ?? ''),
                    'website' => esc_url_raw($lead_website),
                    'rationale' => sanitize_textarea_field($lead['rationale'] ?? ''),
                ),
                'engagement_strategy' => array(
                    'recommended_angle' => sanitize_textarea_field($lead['strategy'] ?? ''),
                    'rationale' => sanitize_textarea_field($lead['rationale'] ?? ''),
                ),
            ));

            if (!empty($contact['contact_id'])) {
                vmo_crm_log_interaction($user_id, (string) $contact['contact_id'], array(
                    'interaction_type' => 'automated_engagement',
                    'subtype' => 'lead_discovery',
                    'direction' => 'outbound',
                    'subject' => 'AI lead discovered: ' . sanitize_text_field($lead['name'] ?? 'Prospect'),
                    'summary' => sanitize_textarea_field($lead['rationale'] ?? 'AI Lead Discovery identified this prospect.'),
                    'next_action' => sanitize_text_field($lead['strategy'] ?? 'Review and approve outreach before contacting.'),
                    'outcome' => 'needs_follow_up',
                    'metadata' => array(
                        'lead_source' => $lead_source,
                        'tier' => sanitize_text_field($lead['tier'] ?? ''),
                        'website' => esc_url_raw($lead_website),
                    ),
                ));
                $inserted_count++;
            }
        }
        
        return $inserted_count;
    }

    private function normalize_lead_tier($tier) {
        $tier = strtolower((string) $tier);
        if (strpos($tier, '1') !== false || strpos($tier, 'primary') !== false) {
            return 'primary';
        }
        if (strpos($tier, '2') !== false || strpos($tier, 'secondary') !== false) {
            return 'secondary';
        }
        return 'tertiary';
    }

    private function ensure_lead_tracking_columns($contacts_table) {
        global $wpdb;
        $columns = $wpdb->get_col("SHOW COLUMNS FROM {$contacts_table}", 0);
        if (!is_array($columns)) {
            return;
        }
        if (!in_array('lead_source', $columns, true)) {
            $wpdb->query("ALTER TABLE {$contacts_table} ADD COLUMN lead_source ENUM('primary','secondary','tertiary') DEFAULT NULL AFTER secondary_category");
        }
        if (!in_array('lead_verified', $columns, true)) {
            $wpdb->query("ALTER TABLE {$contacts_table} ADD COLUMN lead_verified TINYINT(1) DEFAULT 0 AFTER lead_source");
        }
    }

    /**
     * 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: Use centralized model registry — strategic for lead research
        $_ld_model = function_exists('vmo_get_model') ? vmo_get_model('strategic') : (defined('VMO_OPENAI_MODEL') ? VMO_OPENAI_MODEL : 'gpt-5.5');
        $_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);
    }
}
