<?php

class AIService
{
    private $apiKey;
    private $model;

    public function __construct()
    {
        $this->apiKey = (string)($_ENV['OPENAI_API_KEY'] ?? '');
        $this->model  = (string)($_ENV['OPENAI_MODEL'] ?? 'gpt-3.5-turbo');
    }

    public function scoreLead($leadData)
    {
        try {
            if ($this->apiKey === '') {
                throw new Exception('OpenAI API key not configured');
            }

            $analysis = $this->analyzeLead($leadData);

            return [
                'score'      => $analysis['score'],
                'category'   => $this->categorizeScore($analysis['score']),
                'reasoning'  => implode('. ', $analysis['insights']),
                'confidence' => 0.8,
                'ai_model'   => 'rule_based',
                'timestamp'  => date('Y-m-d H:i:s'),
            ];
        } catch (Exception $e) {
            return $this->fallbackLeadScoring($leadData);
        }
    }

    public function generateEmailContent($leadData, $emailType = 'follow_up')
    {
        try {
            if ($this->apiKey === '') {
                throw new Exception('OpenAI API key not configured');
            }

            $body = $this->generateEmailResponse($leadData, 'professional');

            return [
                'subject'              => $this->getEmailSubject($emailType, $leadData),
                'body'                 => $body,
                'personalization_level' => 'medium',
                'ai_generated'         => false,
                'model'                => 'rule_based',
            ];
        } catch (Exception $e) {
            return $this->generateFallbackEmail($leadData, $emailType);
        }
    }

    public function analyzeLeadBehavior($leadData, $interactions = [])
    {
        try {
            if ($this->apiKey === '') {
                throw new Exception('OpenAI API key not configured');
            }

            $analysis = $this->analyzeLead($leadData);

            return [
                'engagement_level'   => $this->getEngagementLevel($analysis['score']),
                'recommended_actions' => $this->getRecommendedActions($analysis['priority']),
                'risk_factors'       => $this->getRiskFactors($analysis['score']),
                'next_best_contact'  => $this->getNextContactTime($analysis['priority']),
            ];
        } catch (Exception $e) {
            return $this->fallbackBehaviorAnalysis($leadData, $interactions);
        }
    }

    public function analyzeLead($leadData)
    {
        $score = 50; // base

        // Email domain signal
        if (!empty($leadData['email'])) {
            if (
                strpos($leadData['email'], 'gmail.com') !== false ||
                strpos($leadData['email'], 'yahoo.com') !== false
            ) {
                $score += 10;
            }
        }

        // Company present
        if (!empty(($leadData['company'] ?? ''))) {
            $score += 15;
        }

        // Phone present
        if (!empty(($leadData['phone'] ?? ''))) {
            $score += 10;
        }

        $score    = max(0, min(100, $score));
        $insights = $this->generateInsights($leadData, $score);

        return [
            'score'    => $score,
            'insights' => $insights,
            'priority' => $this->getPriority($score),
        ];
    }

    public function generateEmailResponse($leadData, $tone = 'professional')
    {
        $name    = $leadData['first_name'] ?? $leadData['name'] ?? 'there';
        $company = $leadData['company'] ?? 'your company';

        $templates = [
            'professional' =>
            "Hi {name},\n\n" .
                "Thank you for your interest! We've received your inquiry and will get back to you shortly.\n\n" .
                "Best regards,\nTeam",
            'friendly' =>
            "Hey {name},\n\n" .
                "Thanks for reaching out! We're excited to connect and will follow up soon.\n\n" .
                "Cheers!",
            'urgent' =>
            "Dear {name},\n\n" .
                "We've prioritized your inquiry and will contact you within the next business day.\n\n" .
                "Sincerely,\nTeam",
        ];

        $tpl = $templates[$tone] ?? $templates['professional'];
        return strtr($tpl, [
            '{name}'    => $name,
            '{company}' => $company,
        ]);
    }

    // ... include all the private helper methods from your original AIService
    private function categorizeScore($score)
    {
        if ($score >= 80) return 'Hot';
        if ($score >= 50) return 'Warm';
        return 'Cold';
    }

    private function fallbackLeadScoring($leadData)
    {
        $analysis = $this->analyzeLead($leadData);
        return [
            'score'      => $analysis['score'],
            'category'   => $this->categorizeScore($analysis['score']),
            'reasoning'  => 'Rule-based scoring (AI unavailable)',
            'confidence' => 0.7,
            'ai_model'   => 'fallback',
            'timestamp'  => date('Y-m-d H:i:s'),
        ];
    }

    private function getEmailSubject($emailType, $leadData)
    {
        $subjects = [
            'follow_up' => 'Following Up on Your Inquiry',
            'welcome'   => 'Welcome to Our Platform',
            'nurture'   => 'Staying in Touch',
            'conversion' => 'Special Offer for You',
        ];
        return $subjects[$emailType] ?? 'Follow Up Regarding Your Inquiry';
    }

    private function generateFallbackEmail($leadData, $emailType)
    {
        $firstName = $leadData['first_name'] ?? 'Valued Customer';
        $fallback = [
            'follow_up' => [
                'subject' => 'Following Up on Your Inquiry',
                'body'    => "Dear {$firstName},\n\nThank you for your interest in our services. " .
                    "We'd like to follow up on your recent inquiry.\n\nBest regards,\nThe Team",
            ],
            'welcome' => [
                'subject' => 'Welcome to Our Platform',
                'body'    => "Dear {$firstName},\n\nWelcome! We're excited to have you on board.\n\n" .
                    "Best regards,\nThe Team",
            ],
        ];
        $tpl = $fallback[$emailType] ?? $fallback['follow_up'];
        return [
            'subject'               => $tpl['subject'],
            'body'                  => $tpl['body'],
            'personalization_level' => 'medium',
            'ai_generated'          => false,
            'model'                 => 'fallback',
        ];
    }

    private function getEngagementLevel($score)
    {
        if ($score >= 80) return 'High';
        if ($score >= 50) return 'Medium';
        return 'Low';
    }

    private function getRecommendedActions($priority)
    {
        $actions = [
            'high'   => 'Immediate follow-up with personalized offer',
            'medium' => 'Follow up within 24 hours with additional information',
            'low'    => 'Add to nurture sequence for gradual engagement',
        ];
        return $actions[$priority] ?? 'Continue regular follow-up';
    }

    private function getRiskFactors($score)
    {
        if ($score < 30) return 'Low engagement signals, high risk of disinterest';
        if ($score < 60) return 'Moderate engagement, requires careful nurturing';
        return 'Strong engagement, low risk factors detected';
    }

    private function getNextContactTime($priority)
    {
        $times = [
            'high'   => 'Within 4 hours',
            'medium' => 'Within 24 hours',
            'low'    => 'Within 3 business days',
        ];
        return $times[$priority] ?? 'Within 3 business days';
    }

    private function fallbackBehaviorAnalysis($leadData, $interactions)
    {
        return [
            'engagement_level'   => 'Medium',
            'recommended_actions' => 'Continue regular follow-up based on lead interest level',
            'risk_factors'       => 'No significant risks detected in available data',
            'next_best_contact'  => 'Within 3 business days',
        ];
    }

    private function generateInsights($leadData, $score)
    {
        $insights = [];
        if ($score >= 80) {
            $insights[] = 'High-quality lead - immediate follow-up recommended';
        } elseif ($score >= 60) {
            $insights[] = 'Good potential lead - follow up within 24 hours';
        } else {
            $insights[] = 'Standard lead - follow up when possible';
        }
        if (!empty($leadData['company'])) {
            $insights[] = 'Company information provided';
        }
        return $insights;
    }

    private function getPriority($score)
    {
        if ($score >= 80) return 'high';
        if ($score >= 60) return 'medium';
        return 'low';
    }
}