<?php

namespace App\Services;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class EmailProcessingService
{
    /**
     * Log file for email processing
     */
    private $logFile;

    public function __construct()
    {
        $this->logFile = storage_path('app/email_processing.log');
    }

    /**
     * Extract company name from email subject using OpenAI
     *
     * @param string $subject
     * @return string|null
     */
    public function extractCompanyFromSubject($subject)
    {
        try {
            $this->logToFile("Extracting company from subject: {$subject}");

            $prompt = "Analyze this email subject and extract the company name if present.\n";
            $prompt .= "Subject: \"{$subject}\"\n\n";
            $prompt .= "Return ONLY the company name, or \"NONE\" if no company is mentioned.\n";
            $prompt .= "Do not include any explanation or additional text.";

            $response = Http::withHeaders([
                'Authorization' => 'Bearer ' . env('OPENAI_API_KEY'),
                'Content-Type' => 'application/json',
            ])->timeout(30)->post('https://api.openai.com/v1/chat/completions', [
                'model' => 'gpt-4',
                'messages' => [
                    ['role' => 'user', 'content' => $prompt]
                ],
                'max_tokens' => 100,
                'temperature' => 0.3,
            ]);

            if ($response->successful()) {
                $companyName = trim($response->json()['choices'][0]['message']['content']);

                if (strtoupper($companyName) === 'NONE' || empty($companyName)) {
                    $this->logToFile("No company found in subject");
                    return null;
                }

                $this->logToFile("✓ Company extracted: {$companyName}");
                return $companyName;
            } else {
                $this->logToFile("❌ OpenAI API error: " . $response->body());
                return null;
            }
        } catch (\Exception $e) {
            $this->logToFile("❌ Exception in extractCompanyFromSubject: " . $e->getMessage());
            return null;
        }
    }

    /**
     * Find lender by email address (matches against all email fields)
     *
     * @param string $email
     * @param string $database
     * @return object|null
     */
    public function findLenderByEmail($email, $database = 'mysql_3')
    {
        try {
            $this->logToFile("Searching for lender with email: {$email}");

            $lender = DB::connection($database)
                ->table('crm_lender')
                ->where(function ($query) use ($email) {
                    $query->where('email', $email)
                        ->orWhere('secondary_email', $email)
                        ->orWhere('secondary_email2', $email)
                        ->orWhere('secondary_email3', $email)
                        ->orWhere('secondary_email4', $email);
                })
                ->where('status', '1')
                ->first();

            if ($lender) {
                $this->logToFile("✓ Lender found - ID: {$lender->id}, Name: {$lender->lender_name}");
            } else {
                $this->logToFile("⊘ No lender found with email: {$email}");
            }

            return $lender;
        } catch (\Exception $e) {
            $this->logToFile("❌ Exception in findLenderByEmail: " . $e->getMessage());
            return null;
        }
    }

    /**
     * Find leads by company name
     *
     * @param string $companyName
     * @param string $database
     * @return \Illuminate\Support\Collection
     */
    public function findLeadsByCompanyName($companyName, $database = 'mysql_3')
    {
        try {
            $this->logToFile("Searching for leads with company: {$companyName}");

            $leads = DB::connection($database)
                ->table('crm_lead_data')
                ->where('company_name', 'LIKE', "%{$companyName}%")
                ->where('is_deleted', 0)
                ->get();

            $this->logToFile("✓ Found " . $leads->count() . " matching lead(s) by company name");
            return $leads;
        } catch (\Exception $e) {
            $this->logToFile("❌ Exception in findLeadsByCompanyName: " . $e->getMessage());
            return collect();
        }
    }

    /**
     * Create link between email and lead
     *
     * @param int $emailId
     * @param int $leadId
     * @param int|null $lenderId
     * @param string|null $companyName
     * @param string|null $matchedEmail
     * @param string $database
     * @return bool
     */
    public function createEmailLeadLink($emailId, $leadId, $lenderId = null, $companyName = null, $matchedEmail = null, $database = 'mysql_3')
    {
        try {
            // Check if link already exists
            $exists = DB::connection($database)
                ->table('email_lead_links')
                ->where('email_id', $emailId)
                ->where('lead_id', $leadId)
                ->exists();

            if ($exists) {
                $this->logToFile("⊘ Link already exists for email_id: {$emailId}, lead_id: {$leadId}");
                return false;
            }

            DB::connection($database)->table('email_lead_links')->insert([
                'email_id' => $emailId,
                'lead_id' => $leadId,
                'lender_id' => $lenderId,
                'company_name' => $companyName,
                'matched_email' => $matchedEmail,
                'processed_at' => date('Y-m-d H:i:s'),
            ]);

            $this->logToFile("✓ Link created - Email ID: {$emailId}, Lead ID: {$leadId}");
            return true;
        } catch (\Exception $e) {
            $this->logToFile("❌ Exception in createEmailLeadLink: " . $e->getMessage());
            return false;
        }
    }

    /**
     * Process a single email to create lead links
     *
     * @param object $email
     * @param string $database
     * @return array
     */
    public function processEmail($email, $database = 'mysql_3')
    {
        $this->logToFile("\n=== Processing Email ID: {$email->id} ===");
        $this->logToFile("From: {$email->from_email}");
        $this->logToFile("Subject: {$email->subject}");

        $results = [
            'email_id' => $email->id,
            'lender_found' => false,
            'company_found' => false,
            'leads_found' => 0,
            'links_created' => 0,
        ];

        // Step 1: Find lender by from_email
        $lender = $this->findLenderByEmail($email->from_email, $database);
        if (!$lender) {
            $this->logToFile("=== Email Processing Complete (No lender found) ===\n");
            return $results;
        }
        $results['lender_found'] = true;

        // Step 2: Extract company name from subject
        $companyName = $this->extractCompanyFromSubject($email->subject);
        if (!$companyName) {
            $this->logToFile("=== Email Processing Complete (No company found) ===\n");
            return $results;
        }
        $results['company_found'] = true;

        // Step 3: Find leads by company name
        $leads = $this->findLeadsByCompanyName($companyName, $database);
        $results['leads_found'] = $leads->count();

        // Step 4: Create links
        foreach ($leads as $lead) {
            $created = $this->createEmailLeadLink(
                $email->id,
                $lead->id,
                $lender->id,
                $companyName,
                $email->from_email,  // Store the from_email that matched
                $database
            );

            if ($created) {
                $results['links_created']++;
            }
        }

        $this->logToFile("=== Email Processing Complete - Links created: {$results['links_created']} ===\n");
        return $results;
    }

    /**
     * Log message to file
     *
     * @param string $message
     */
    private function logToFile($message)
    {
        $timestamp = date('Y-m-d H:i:s');
        $logMessage = "[{$timestamp}] {$message}\n";
        file_put_contents($this->logFile, $logMessage, FILE_APPEND);
    }
}
