<?php

namespace App\Http\Controllers\FrontUser;

use App\Http\Controllers\Controller;
use App\Models\Contact;
use App\Models\Conversation;
use App\Models\ConversationMessage;
use App\Models\AIInsight;
use App\Services\AI\Phi3Service;
use App\Services\AI\CRMIntelligenceService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class CRMController extends Controller
{
    private $phi3Service;
    private $crmIntelligenceService;

    public function __construct(Phi3Service $phi3Service, CRMIntelligenceService $crmIntelligenceService)
    {
        $this->phi3Service = $phi3Service;
        $this->crmIntelligenceService = $crmIntelligenceService;
    }

    /**
     * Display the CRM dashboard
     */
    public function index()
    {
        $user = Auth::user();
        
        // Get CRM statistics
        $stats = $this->getCRMStats($user->id);
        
        // Get recent contacts
        $recentContacts = Contact::where('user_id', $user->id)
            ->with(['conversations' => function($query) {
                $query->latest()->limit(1);
            }])
            ->orderBy('created_at', 'desc')
            ->limit(10)
            ->get();

        // Get recent conversations
        $recentConversations = Conversation::where('user_id', $user->id)
            ->with(['contact', 'messages' => function($query) {
                $query->latest()->limit(1);
            }])
            ->orderBy('created_at', 'desc')
            ->limit(10)
            ->get();

        // Get AI insights
        $insights = $this->getCRMInsights($user->id);

        return view('FrontUser.crm.dashboard', compact('stats', 'recentContacts', 'recentConversations', 'insights'));
    }

    /**
     * Get CRM statistics
     */
    private function getCRMStats(int $userId): array
    {
        $contacts = Contact::where('user_id', $userId);
        $conversations = Conversation::where('user_id', $userId);
        
        return [
            'total_contacts' => $contacts->count(),
            'total_conversations' => $conversations->count(),
            'active_conversations' => $conversations->where('status', 'active')->count(),
            'completed_conversations' => $conversations->where('status', 'completed')->count(),
            'avg_satisfaction' => $conversations->whereNotNull('satisfaction_score')->avg('satisfaction_score') ?? 0,
            'conversion_rate' => $this->calculateConversionRate($userId)
        ];
    }

    /**
     * Calculate conversion rate
     */
    private function calculateConversionRate(int $userId): float
    {
        $totalConversations = Conversation::where('user_id', $userId)->count();
        $successfulConversations = Conversation::where('user_id', $userId)
            ->where('outcome', 'success')
            ->count();

        return $totalConversations > 0 ? round(($successfulConversations / $totalConversations) * 100, 1) : 0;
    }

    /**
     * Get CRM insights
     */
    private function getCRMInsights(int $userId): array
    {
        $insights = AIInsight::whereHas('conversation', function($query) use ($userId) {
            $query->where('user_id', $userId);
        })
        ->selectRaw('insight_type, COUNT(*) as count, AVG(confidence_score) as avg_confidence')
        ->groupBy('insight_type')
        ->get();

        $sentimentBreakdown = ConversationMessage::whereHas('conversation', function($query) use ($userId) {
            $query->where('user_id', $userId);
        })
        ->whereNotNull('sentiment')
        ->selectRaw('sentiment, COUNT(*) as count')
        ->groupBy('sentiment')
        ->get();

        return [
            'insights' => $insights,
            'sentiment_breakdown' => $sentimentBreakdown
        ];
    }

    /**
     * Start a new conversation
     */
    public function startConversation(Request $request)
    {
        $request->validate([
            'type' => 'required|string|in:sales,support,follow_up,qualification,demo,general',
            'contact_id' => 'nullable|exists:contacts,id',
            'context' => 'nullable|array'
        ]);

        $user = Auth::user();
        
        $conversation = Conversation::create([
            'user_id' => $user->id,
            'contact_id' => $request->contact_id,
            'type' => $request->type,
            'status' => 'active',
            'context_data' => $request->context ?? [],
            'ai_model' => 'gemma:2b',
            'started_at' => now()
        ]);

        // Add initial system message
        $conversation->messages()->create([
            'role' => 'system',
            'content' => "Conversation started: {$request->type}",
            'timestamp' => now()
        ]);

        return response()->json([
            'success' => true,
            'conversation' => $conversation->load('contact', 'messages'),
            'message' => 'Conversation started successfully'
        ]);
    }

    /**
     * Send a message in a conversation
     */
    public function sendMessage(Request $request, $conversationId)
    {
        $request->validate([
            'message' => 'required|string|max:2000',
            'metadata' => 'nullable|array'
        ]);

        $user = Auth::user();
        $conversation = Conversation::where('user_id', $user->id)
            ->where('id', $conversationId)
            ->firstOrFail();

        // Add user message
        $userMessage = $conversation->messages()->create([
            'role' => 'user',
            'content' => $request->message,
            'metadata' => $request->metadata ?? [],
            'timestamp' => now()
        ]);

        // Generate AI response
        $startTime = microtime(true);
        $aiResponse = $this->phi3Service->generateResponse($request->message, [], $conversation->type);
        $processingTime = round((microtime(true) - $startTime) * 1000);

        if ($aiResponse['success']) {
            // Add AI message
            $aiMessage = $conversation->messages()->create([
                'role' => 'assistant',
                'content' => $aiResponse['response'],
                'processing_time_ms' => $processingTime,
                'timestamp' => now()
            ]);

            // Analyze sentiment
            $sentiment = $this->analyzeSentiment($request->message);
            if ($sentiment) {
                $userMessage->update(['sentiment' => $sentiment]);
            }

            // Extract insights
            $insights = $this->extractInsights($request->message, $conversation);
            
            // Update conversation
            $conversation->increment('total_messages');

            return response()->json([
                'success' => true,
                'data' => [
                    'ai_message' => $aiMessage,
                    'insights' => $insights,
                    'processing_time' => $processingTime
                ]
            ]);
        }

        return response()->json([
            'success' => false,
            'message' => 'Failed to generate AI response'
        ], 500);
    }

    /**
     * Get conversation details
     */
    public function getConversation($conversationId)
    {
        $user = Auth::user();
        $conversation = Conversation::where('user_id', $user->id)
            ->with(['contact', 'messages', 'insights'])
            ->findOrFail($conversationId);

        return response()->json([
            'success' => true,
            'data' => $conversation
        ]);
    }

    /**
     * Get user conversations
     */
    public function getUserConversations()
    {
        $user = Auth::user();
        $conversations = Conversation::where('user_id', $user->id)
            ->with(['contact', 'messages' => function($query) {
                $query->latest()->limit(1);
            }])
            ->orderBy('created_at', 'desc')
            ->paginate(20);

        return response()->json([
            'success' => true,
            'data' => $conversations
        ]);
    }

    /**
     * Complete a conversation
     */
    public function completeConversation(Request $request, $conversationId)
    {
        $request->validate([
            'outcome' => 'nullable|string',
            'summary' => 'nullable|string',
            'satisfaction_score' => 'nullable|numeric|min:0|max:1'
        ]);

        $user = Auth::user();
        $conversation = Conversation::where('user_id', $user->id)
            ->findOrFail($conversationId);

        $conversation->update([
            'status' => 'completed',
            'outcome' => $request->outcome,
            'summary' => $request->summary,
            'satisfaction_score' => $request->satisfaction_score,
            'ended_at' => now()
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Conversation completed successfully'
        ]);
    }

    /**
     * Test AI connection
     */
    public function testConnection()
    {
        $result = $this->phi3Service->testConnection();
        
        return response()->json($result);
    }

    /**
     * Analyze sentiment
     */
    private function analyzeSentiment(string $message): ?string
    {
        try {
            $result = $this->phi3Service->analyzeSentiment($message);
            return $result['success'] ? $result['sentiment'] : null;
        } catch (\Exception $e) {
            return null;
        }
    }

    /**
     * Extract insights from message
     */
    private function extractInsights(string $message, Conversation $conversation): array
    {
        try {
            $result = $this->phi3Service->extractInsights($message);
            
            if ($result['success'] && isset($result['insights'])) {
                $insights = [];
                foreach ($result['insights'] as $type => $content) {
                    if (is_array($content)) {
                        foreach ($content as $item) {
                            $insights[] = AIInsight::create([
                                'conversation_id' => $conversation->id,
                                'insight_type' => $type,
                                'content' => is_string($item) ? $item : json_encode($item),
                                'confidence_score' => 0.8
                            ]);
                        }
                    } else {
                        $insights[] = AIInsight::create([
                            'conversation_id' => $conversation->id,
                            'insight_type' => $type,
                            'content' => is_string($content) ? $content : json_encode($content),
                            'confidence_score' => 0.8
                        ]);
                    }
                }
                return $insights;
            }
        } catch (\Exception $e) {
            // Log error but don't fail the request
        }

        return [];
    }

    /**
     * Get CRM analytics
     */
    public function getAnalytics()
    {
        $user = Auth::user();
        
        // Sentiment analysis data
        $sentimentData = ConversationMessage::whereHas('conversation', function($query) use ($user) {
            $query->where('user_id', $user->id);
        })
        ->whereNotNull('sentiment')
        ->selectRaw('sentiment, COUNT(*) as count')
        ->groupBy('sentiment')
        ->get();

        // Conversation types data
        $conversationTypes = Conversation::where('user_id', $user->id)
            ->selectRaw('type, COUNT(*) as count')
            ->groupBy('type')
            ->get();

        // Daily conversation count for the last 30 days
        $dailyConversations = Conversation::where('user_id', $user->id)
            ->where('created_at', '>=', now()->subDays(30))
            ->selectRaw('DATE(created_at) as date, COUNT(*) as count')
            ->groupBy('date')
            ->orderBy('date')
            ->get();

        return response()->json([
            'success' => true,
            'data' => [
                'sentiment' => $sentimentData,
                'conversation_types' => $conversationTypes,
                'daily_conversations' => $dailyConversations
            ]
        ]);
    }

    /**
     * Get lead scoring
     */
    public function getLeadScoring($contactId)
    {
        $user = Auth::user();
        $contact = Contact::where('user_id', $user->id)->findOrFail($contactId);
        
        $result = $this->crmIntelligenceService->generateLeadScore($user->id, [
            'contact_id' => $contactId
        ]);

        return response()->json($result);
    }

    /**
     * Get customer behavior analysis
     */
    public function getCustomerBehavior($contactId)
    {
        $user = Auth::user();
        $contact = Contact::where('user_id', $user->id)->findOrFail($contactId);
        
        $result = $this->crmIntelligenceService->analyzeCustomerBehavior($user->id, [
            'contact_id' => $contactId
        ]);

        return response()->json($result);
    }
}
