<?php
/**
 * Contrôleur Twilio
 * Gestion des webhooks pour les appels vocaux
 */

namespace App\Controllers;

use Core\Controller;
use App\Services\TwilioVoiceService;
use App\Services\TwilioClientService;
use App\Services\AIVoiceAgent;
use App\Models\Entreprise;
use App\Models\Client;
use App\Models\Conversation;

require_once APP_PATH . '/Services/TwilioVoiceService.php';
require_once APP_PATH . '/Services/TwilioClientService.php';
require_once APP_PATH . '/Services/AIVoiceAgent.php';
require_once APP_PATH . '/Models/Entreprise.php';
require_once APP_PATH . '/Models/Client.php';
require_once APP_PATH . '/Models/Conversation.php';

class TwilioController extends Controller
{
    private TwilioVoiceService $twilioService;
    private TwilioClientService $clientService;
    private AIVoiceAgent $aiAgent;
    private Entreprise $entrepriseModel;
    private Client $clientModel;
    private Conversation $conversationModel;
    
    public function __construct()
    {
        parent::__construct();
        $this->twilioService = new TwilioVoiceService();
        $this->clientService = new TwilioClientService();
        $this->aiAgent = new AIVoiceAgent();
        $this->entrepriseModel = new Entreprise();
        $this->clientModel = new Client();
        $this->conversationModel = new Conversation();
    }
    
    /**
     * Webhook: Appel entrant
     */
    public function voice(): void
    {
        header('Content-Type: text/xml');
        
        $from = $_POST['From'] ?? '';
        $to = $_POST['To'] ?? '';
        $callSid = $_POST['CallSid'] ?? '';
        
        // Trouver l'entreprise par numéro Twilio
        $entreprise = $this->findEntrepriseByTwilioNumber($to);
        
        if (!$entreprise) {
            echo $this->twilioService->generateGoodbyeResponse('fr');
            return;
        }
        
        // Déterminer la langue
        $langue = $this->detectLanguage($entreprise);
        
        // Créer ou récupérer le client
        $client = $this->getOrCreateClient($entreprise['id'], $from);
        
        // Créer la conversation
        $conversationId = $this->createVoiceConversation($entreprise['id'], $client['id'], $callSid, $from);
        
        // Vérifier si le mode IA est activé pour cette entreprise
        $aiMode = $this->isAIModeEnabled($entreprise);
        
        // Stocker les infos dans la session Twilio (via cookies ou DB)
        $this->storeCallContext($callSid, [
            'entreprise_id' => $entreprise['id'],
            'client_id' => $client['id'],
            'conversation_id' => $conversationId,
            'langue' => $langue,
            'ai_mode' => $aiMode,
            'ai_history' => []
        ]);
        
        // Générer le message de bienvenue
        if ($aiMode && $this->aiAgent->isConfigured()) {
            echo $this->generateAIWelcomeResponse($entreprise, $langue);
        } else {
            echo $this->twilioService->generateWelcomeResponse($entreprise, $langue);
        }
    }
    
    /**
     * Webhook: Traitement des choix utilisateur (DTMF ou parole)
     */
    public function gather(): void
    {
        header('Content-Type: text/xml');
        
        $callSid = $_POST['CallSid'] ?? '';
        $digits = $_POST['Digits'] ?? '';
        $speechResult = $_POST['SpeechResult'] ?? '';
        
        $context = $this->getCallContext($callSid);
        $langue = $context['langue'] ?? 'fr';
        $entrepriseId = $context['entreprise_id'] ?? 0;
        $aiMode = $context['ai_mode'] ?? false;
        
        // Mode IA activé : traiter avec GPT
        if ($aiMode && $this->aiAgent->isConfigured() && !empty($speechResult)) {
            echo $this->handleAIConversation($callSid, $speechResult, $entrepriseId, $langue);
            return;
        }
        
        // Mode classique : menu DTMF
        $choice = $this->parseUserInput($digits, $speechResult);
        
        switch ($choice) {
            case 'agent':
                // Transférer à un agent disponible
                $agent = $this->findAvailableAgent($entrepriseId);
                if ($agent && !empty($agent['telephone'])) {
                    echo $this->twilioService->generateTransferResponse($agent['telephone'], $langue);
                } else {
                    echo $this->twilioService->generateVoicemailResponse($langue);
                }
                break;
                
            case 'message':
                // Enregistrer un message
                echo $this->twilioService->generateRecordResponse($langue);
                break;
                
            case 'hours':
                // Horaires d'ouverture
                echo $this->generateHoursResponse($langue);
                break;
                
            default:
                // Répéter le menu
                $entreprise = $this->entrepriseModel->find($entrepriseId);
                echo $this->twilioService->generateWelcomeResponse($entreprise ?: [], $langue);
        }
    }
    
    /**
     * Webhook: Enregistrement terminé
     */
    public function recording(): void
    {
        header('Content-Type: text/xml');
        
        $callSid = $_POST['CallSid'] ?? '';
        $recordingUrl = $_POST['RecordingUrl'] ?? '';
        $recordingSid = $_POST['RecordingSid'] ?? '';
        $recordingDuration = $_POST['RecordingDuration'] ?? 0;
        
        $context = $this->getCallContext($callSid);
        $langue = $context['langue'] ?? 'fr';
        $conversationId = $context['conversation_id'] ?? 0;
        
        if ($conversationId && $recordingUrl) {
            // Sauvegarder l'enregistrement dans les messages
            $this->saveVoiceMessage($conversationId, $recordingUrl, $recordingSid, (int)$recordingDuration);
        }
        
        // Message de confirmation et fin
        $messages = $this->getConfirmationMessages($langue);
        
        $twiml = '<?xml version="1.0" encoding="UTF-8"?>';
        $twiml .= '<Response>';
        $twiml .= '<Say voice="alice" language="' . ($langue === 'en' ? 'en-US' : 'fr-FR') . '">' . $messages['saved'] . '</Say>';
        $twiml .= '<Hangup />';
        $twiml .= '</Response>';
        
        echo $twiml;
    }
    
    /**
     * Webhook: Messagerie vocale
     */
    public function voicemail(): void
    {
        header('Content-Type: text/xml');
        
        $callSid = $_POST['CallSid'] ?? '';
        $context = $this->getCallContext($callSid);
        $langue = $context['langue'] ?? 'fr';
        
        echo $this->twilioService->generateVoicemailResponse($langue);
    }
    
    /**
     * Webhook: Messagerie vocale sauvegardée
     */
    public function voicemailSaved(): void
    {
        header('Content-Type: text/xml');
        
        $callSid = $_POST['CallSid'] ?? '';
        $recordingUrl = $_POST['RecordingUrl'] ?? '';
        $recordingSid = $_POST['RecordingSid'] ?? '';
        $recordingDuration = $_POST['RecordingDuration'] ?? 0;
        
        $context = $this->getCallContext($callSid);
        $langue = $context['langue'] ?? 'fr';
        $conversationId = $context['conversation_id'] ?? 0;
        
        if ($conversationId && $recordingUrl) {
            $this->saveVoiceMessage($conversationId, $recordingUrl, $recordingSid, (int)$recordingDuration, 'voicemail');
        }
        
        echo $this->twilioService->generateGoodbyeResponse($langue);
    }
    
    /**
     * Webhook: Transcription reçue
     */
    public function transcription(): void
    {
        $callSid = $_POST['CallSid'] ?? '';
        $recordingSid = $_POST['RecordingSid'] ?? '';
        $transcriptionText = $_POST['TranscriptionText'] ?? '';
        $transcriptionStatus = $_POST['TranscriptionStatus'] ?? '';
        
        if ($transcriptionStatus === 'completed' && !empty($transcriptionText)) {
            // Mettre à jour le message avec la transcription
            $this->updateMessageTranscription($recordingSid, $transcriptionText);
        }
        
        // Réponse vide (webhook de notification)
        http_response_code(200);
        echo 'OK';
    }
    
    /**
     * Webhook: Statut du dial (transfert)
     */
    public function dialStatus(): void
    {
        header('Content-Type: text/xml');
        
        $callSid = $_POST['CallSid'] ?? '';
        $dialCallStatus = $_POST['DialCallStatus'] ?? '';
        
        $context = $this->getCallContext($callSid);
        $langue = $context['langue'] ?? 'fr';
        
        // Si l'agent n'a pas répondu, proposer la messagerie
        if (in_array($dialCallStatus, ['no-answer', 'busy', 'failed', 'canceled'])) {
            echo $this->twilioService->generateVoicemailResponse($langue);
        } else {
            echo $this->twilioService->generateGoodbyeResponse($langue);
        }
    }
    
    /**
     * Webhook: Statut de l'appel (fin d'appel)
     */
    public function status(): void
    {
        $callSid = $_POST['CallSid'] ?? '';
        $callStatus = $_POST['CallStatus'] ?? '';
        $callDuration = $_POST['CallDuration'] ?? 0;
        
        // Mettre à jour la conversation
        $context = $this->getCallContext($callSid);
        if (!empty($context['conversation_id'])) {
            $this->updateConversationStatus($context['conversation_id'], $callStatus, (int)$callDuration);
        }
        
        // Nettoyer le contexte
        $this->clearCallContext($callSid);
        
        http_response_code(200);
        echo 'OK';
    }
    
    // ==========================================
    // MÉTHODES PRIVÉES
    // ==========================================
    
    private function findEntrepriseByTwilioNumber(string $number): ?array
    {
        // Chercher l'entreprise qui a ce numéro Twilio configuré
        $sql = "SELECT * FROM entreprises WHERE is_active = 1 AND twilio_phone_number = :phone LIMIT 1";
        $result = $this->db->fetch($sql, ['phone' => $number]);
        
        if (!$result) {
            // Fallback: première entreprise avec canal voice actif
            $sql = "SELECT * FROM entreprises WHERE is_active = 1 AND canaux_actifs LIKE '%voice%' LIMIT 1";
            $result = $this->db->fetch($sql, []);
        }
        
        return $result ?: null;
    }
    
    private function detectLanguage(array $entreprise): string
    {
        $langues = json_decode($entreprise['langues_actives'] ?? '["fr"]', true);
        return $langues[0] ?? 'fr';
    }
    
    private function getOrCreateClient(int $entrepriseId, string $phone): array
    {
        $client = $this->clientModel->findByPhone($entrepriseId, $phone);
        
        if (!$client) {
            $clientId = $this->clientModel->create([
                'entreprise_id' => $entrepriseId,
                'telephone' => $phone,
                'nom' => 'Client Voice ' . substr($phone, -4)
            ]);
            $client = $this->clientModel->find($clientId);
        }
        
        return $client;
    }
    
    private function createVoiceConversation(int $entrepriseId, int $clientId, string $callSid, string $phone): int
    {
        return $this->conversationModel->create([
            'entreprise_id' => $entrepriseId,
            'client_id' => $clientId,
            'canal' => 'voice',
            'sujet' => 'Appel vocal du ' . date('d/m/Y H:i'),
            'statut' => 'open',
            'metadata' => json_encode([
                'call_sid' => $callSid,
                'caller_phone' => $phone,
                'started_at' => date('Y-m-d H:i:s')
            ])
        ]);
    }
    
    private function storeCallContext(string $callSid, array $context): void
    {
        // Stocker en base (table temporaire ou cache)
        $sql = "INSERT INTO voice_call_context (call_sid, context_data, created_at) 
                VALUES (:sid, :data, NOW())
                ON DUPLICATE KEY UPDATE context_data = :data";
        $this->db->query($sql, [
            'sid' => $callSid,
            'data' => json_encode($context)
        ]);
    }
    
    private function getCallContext(string $callSid): array
    {
        $sql = "SELECT context_data FROM voice_call_context WHERE call_sid = :sid";
        $result = $this->db->fetch($sql, ['sid' => $callSid]);
        
        return $result ? json_decode($result['context_data'], true) : [];
    }
    
    private function clearCallContext(string $callSid): void
    {
        $sql = "DELETE FROM voice_call_context WHERE call_sid = :sid";
        $this->db->query($sql, ['sid' => $callSid]);
    }
    
    private function parseUserInput(string $digits, string $speech): string
    {
        // DTMF
        if ($digits === '1') return 'agent';
        if ($digits === '2') return 'message';
        if ($digits === '3') return 'hours';
        
        // Reconnaissance vocale
        $speech = strtolower($speech);
        if (strpos($speech, 'agent') !== false || strpos($speech, 'conseiller') !== false || strpos($speech, 'parler') !== false) {
            return 'agent';
        }
        if (strpos($speech, 'message') !== false || strpos($speech, 'laisser') !== false || strpos($speech, 'enregistrer') !== false) {
            return 'message';
        }
        if (strpos($speech, 'horaire') !== false || strpos($speech, 'heure') !== false || strpos($speech, 'ouvert') !== false) {
            return 'hours';
        }
        
        return 'unknown';
    }
    
    private function findAvailableAgent(int $entrepriseId): ?array
    {
        $sql = "SELECT * FROM users 
                WHERE entreprise_id = :eid 
                AND role IN ('agent', 'admin_entreprise') 
                AND is_active = 1 
                AND is_online = 1 
                AND telephone IS NOT NULL AND telephone != ''
                ORDER BY last_login DESC
                LIMIT 1";
        
        return $this->db->fetch($sql, ['eid' => $entrepriseId]) ?: null;
    }
    
    private function generateHoursResponse(string $langue): string
    {
        $messages = [
            'fr' => "Nos horaires d'ouverture sont du lundi au vendredi de 8h à 18h.",
            'en' => "Our opening hours are Monday to Friday from 8am to 6pm."
        ];
        
        $message = $messages[$langue] ?? $messages['fr'];
        $lang = $langue === 'en' ? 'en-US' : 'fr-FR';
        
        $twiml = '<?xml version="1.0" encoding="UTF-8"?>';
        $twiml .= '<Response>';
        $twiml .= '<Say voice="alice" language="' . $lang . '">' . $message . '</Say>';
        $twiml .= '<Redirect>' . TWILIO_WEBHOOK_BASE_URL . '/api/twilio/voice</Redirect>';
        $twiml .= '</Response>';
        
        return $twiml;
    }
    
    private function saveVoiceMessage(int $conversationId, string $recordingUrl, string $recordingSid, int $duration, string $type = 'recording'): void
    {
        $sql = "INSERT INTO messages (conversation_id, sender_type, contenu, type_message, fichier_url, metadata, created_at)
                VALUES (:cid, 'client', :contenu, 'audio', :url, :meta, NOW())";
        
        $this->db->query($sql, [
            'cid' => $conversationId,
            'contenu' => $type === 'voicemail' ? '[Messagerie vocale]' : '[Message vocal]',
            'url' => $recordingUrl . '.mp3',
            'meta' => json_encode([
                'recording_sid' => $recordingSid,
                'duration' => $duration,
                'type' => $type
            ])
        ]);
    }
    
    private function updateMessageTranscription(string $recordingSid, string $transcription): void
    {
        $sql = "UPDATE messages SET contenu = :contenu 
                WHERE metadata LIKE :pattern";
        
        $this->db->query($sql, [
            'contenu' => $transcription,
            'pattern' => '%"recording_sid":"' . $recordingSid . '"%'
        ]);
    }
    
    private function updateConversationStatus(int $conversationId, string $callStatus, int $duration): void
    {
        $statut = in_array($callStatus, ['completed', 'busy', 'no-answer']) ? 'closed' : 'open';
        
        $sql = "UPDATE conversations SET 
                statut = :statut,
                metadata = JSON_SET(COALESCE(metadata, '{}'), '$.call_status', :call_status, '$.call_duration', :duration),
                closed_at = IF(:statut = 'closed', NOW(), closed_at),
                updated_at = NOW()
                WHERE id = :id";
        
        $this->db->query($sql, [
            'id' => $conversationId,
            'statut' => $statut,
            'call_status' => $callStatus,
            'duration' => $duration
        ]);
    }
    
    private function getConfirmationMessages(string $langue): array
    {
        return [
            'fr' => ['saved' => 'Votre message a bien été enregistré. Nous vous recontacterons rapidement. Au revoir.'],
            'en' => ['saved' => 'Your message has been recorded. We will contact you shortly. Goodbye.']
        ][$langue] ?? ['saved' => 'Votre message a bien été enregistré. Au revoir.'];
    }
    
    // ==========================================
    // MÉTHODES IA
    // ==========================================
    
    /**
     * Vérifier si le mode IA est activé pour l'entreprise
     */
    private function isAIModeEnabled(array $entreprise): bool
    {
        // Vérifier la config IA de l'entreprise
        if (!empty($entreprise['ia_config'])) {
            $config = json_decode($entreprise['ia_config'], true);
            if (isset($config['voice_ai_enabled']) && $config['voice_ai_enabled']) {
                return true;
            }
        }
        
        // Vérifier la config voice
        if (!empty($entreprise['voice_config'])) {
            $config = json_decode($entreprise['voice_config'], true);
            if (isset($config['ai_mode']) && $config['ai_mode']) {
                return true;
            }
        }
        
        // Par défaut, activer si OpenAI est configuré globalement
        return defined('OPENAI_API_KEY') && !empty(OPENAI_API_KEY) && OPENAI_API_KEY !== 'your_openai_api_key_here';
    }
    
    /**
     * Générer le message de bienvenue en mode IA
     */
    private function generateAIWelcomeResponse(array $entreprise, string $langue): string
    {
        $messages = [
            'fr' => "Bonjour et bienvenue chez " . ($entreprise['nom'] ?? 'notre service client') . ". Je suis votre assistant virtuel. Comment puis-je vous aider aujourd'hui?",
            'en' => "Hello and welcome to " . ($entreprise['nom'] ?? 'our customer service') . ". I am your virtual assistant. How may I help you today?"
        ];
        
        $welcomeMessage = $entreprise['voice_welcome'] ?? ($messages[$langue] ?? $messages['fr']);
        $lang = $langue === 'en' ? 'en-US' : 'fr-FR';
        
        $twiml = '<?xml version="1.0" encoding="UTF-8"?>';
        $twiml .= '<Response>';
        $twiml .= '<Say voice="alice" language="' . $lang . '">' . htmlspecialchars($welcomeMessage) . '</Say>';
        $twiml .= '<Gather input="speech" timeout="' . TWILIO_INPUT_TIMEOUT . '" ';
        $twiml .= 'speechTimeout="auto" ';
        $twiml .= 'action="' . TWILIO_WEBHOOK_BASE_URL . '/api/twilio/gather" method="POST" ';
        $twiml .= 'language="' . $lang . '">';
        $twiml .= '</Gather>';
        $twiml .= '<Say voice="alice" language="' . $lang . '">' . ($langue === 'en' ? "I didn't hear anything. Goodbye." : "Je n'ai rien entendu. Au revoir.") . '</Say>';
        $twiml .= '</Response>';
        
        return $twiml;
    }
    
    /**
     * Traiter une conversation IA
     */
    private function handleAIConversation(string $callSid, string $userMessage, int $entrepriseId, string $langue): string
    {
        // Analyser l'intention
        $intent = $this->aiAgent->analyzeIntent($userMessage);
        
        // Si l'utilisateur veut un humain, transférer
        if ($intent['intent'] === 'transfer_human') {
            $agent = $this->findAvailableAgent($entrepriseId);
            if ($agent && !empty($agent['telephone'])) {
                return $this->twilioService->generateTransferResponse($agent['telephone'], $langue);
            } else {
                return $this->twilioService->generateVoicemailResponse($langue);
            }
        }
        
        // Si fin de conversation
        if ($intent['intent'] === 'end_conversation') {
            return $this->twilioService->generateGoodbyeResponse($langue);
        }
        
        // Générer une réponse IA
        $aiResponse = $this->aiAgent->generateResponse($entrepriseId, $userMessage, $callSid, $langue);
        
        // Sauvegarder dans la conversation
        $context = $this->getCallContext($callSid);
        if (!empty($context['conversation_id'])) {
            $this->saveAIMessage($context['conversation_id'], $userMessage, $aiResponse);
        }
        
        // Générer TwiML avec la réponse IA et continuer l'écoute
        return $this->generateAIResponseTwiML($aiResponse, $langue);
    }
    
    /**
     * Générer TwiML pour une réponse IA
     */
    private function generateAIResponseTwiML(string $response, string $langue): string
    {
        $lang = $langue === 'en' ? 'en-US' : 'fr-FR';
        
        $twiml = '<?xml version="1.0" encoding="UTF-8"?>';
        $twiml .= '<Response>';
        $twiml .= '<Say voice="alice" language="' . $lang . '">' . htmlspecialchars($response) . '</Say>';
        $twiml .= '<Gather input="speech" timeout="' . TWILIO_INPUT_TIMEOUT . '" ';
        $twiml .= 'speechTimeout="auto" ';
        $twiml .= 'action="' . TWILIO_WEBHOOK_BASE_URL . '/api/twilio/gather" method="POST" ';
        $twiml .= 'language="' . $lang . '">';
        $twiml .= '</Gather>';
        $twiml .= '<Say voice="alice" language="' . $lang . '">' . ($langue === 'en' ? "I didn't catch that. Is there anything else I can help with?" : "Je n'ai pas compris. Y a-t-il autre chose que je puisse faire pour vous?") . '</Say>';
        $twiml .= '<Gather input="speech" timeout="3" ';
        $twiml .= 'action="' . TWILIO_WEBHOOK_BASE_URL . '/api/twilio/gather" method="POST" ';
        $twiml .= 'language="' . $lang . '">';
        $twiml .= '</Gather>';
        $twiml .= '<Say voice="alice" language="' . $lang . '">' . ($langue === 'en' ? "Thank you for calling. Goodbye." : "Merci de votre appel. Au revoir.") . '</Say>';
        $twiml .= '</Response>';
        
        return $twiml;
    }
    
    /**
     * Sauvegarder les messages IA dans la conversation
     */
    private function saveAIMessage(int $conversationId, string $userMessage, string $aiResponse): void
    {
        // Message utilisateur
        $this->db->query(
            "INSERT INTO messages (conversation_id, sender_type, contenu, type_message, created_at)
             VALUES (:cid, 'client', :contenu, 'text', NOW())",
            ['cid' => $conversationId, 'contenu' => $userMessage]
        );
        
        // Réponse IA
        $this->db->query(
            "INSERT INTO messages (conversation_id, sender_type, contenu, type_message, metadata, created_at)
             VALUES (:cid, 'agent', :contenu, 'text', :meta, NOW())",
            [
                'cid' => $conversationId, 
                'contenu' => $aiResponse,
                'meta' => json_encode(['ai_generated' => true])
            ]
        );
    }
    
    // ==========================================
    // MÉTHODES WEBRTC
    // ==========================================
    
    /**
     * API: Générer un token pour Twilio Client (WebRTC)
     */
    public function getToken(): void
    {
        header('Content-Type: application/json');
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: POST, OPTIONS');
        header('Access-Control-Allow-Headers: Content-Type, Authorization');
        
        if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
            exit(0);
        }
        
        // Récupérer l'entreprise via API key ou token
        $apiKey = $_POST['api_key'] ?? $_GET['api_key'] ?? '';
        $token = $_POST['token'] ?? $_GET['token'] ?? '';
        
        $entreprise = null;
        if (!empty($apiKey)) {
            $entreprise = $this->entrepriseModel->findByApiKey($apiKey);
        } elseif (!empty($token)) {
            $entreprise = $this->entrepriseModel->findByToken($token);
        }
        
        if (!$entreprise) {
            echo json_encode(['success' => false, 'error' => 'Entreprise non trouvée']);
            return;
        }
        
        // Vérifier que le canal voice est activé
        $canaux = json_decode($entreprise['canaux_actifs'] ?? '[]', true);
        if (!in_array('voice', $canaux)) {
            echo json_encode(['success' => false, 'error' => 'Canal vocal non activé']);
            return;
        }
        
        // Vérifier que WebRTC est configuré
        if (!$this->clientService->isConfigured()) {
            echo json_encode(['success' => false, 'error' => 'WebRTC non configuré']);
            return;
        }
        
        // Générer l'identité et le token
        $identity = $this->clientService->generateClientIdentity($entreprise['id']);
        $accessToken = $this->clientService->generateAccessToken($identity, $entreprise['id']);
        
        echo json_encode([
            'success' => true,
            'token' => $accessToken,
            'identity' => $identity,
            'entreprise_id' => $entreprise['id']
        ]);
    }
    
    /**
     * Webhook: Appel entrant depuis WebRTC (TwiML App)
     */
    public function webrtcVoice(): void
    {
        header('Content-Type: text/xml');
        
        // Récupérer l'entreprise_id depuis les paramètres
        $entrepriseId = (int)($_POST['entreprise_id'] ?? $_REQUEST['entreprise_id'] ?? 0);
        $caller = $_POST['Caller'] ?? 'client:anonymous';
        $callSid = $_POST['CallSid'] ?? '';
        
        if ($entrepriseId <= 0) {
            echo $this->twilioService->generateGoodbyeResponse('fr');
            return;
        }
        
        $entreprise = $this->entrepriseModel->find($entrepriseId);
        
        if (!$entreprise) {
            echo $this->twilioService->generateGoodbyeResponse('fr');
            return;
        }
        
        // Déterminer la langue
        $langue = $this->detectLanguage($entreprise);
        
        // Créer ou récupérer le client (à partir de l'identité WebRTC)
        $clientData = $this->parseWebRTCIdentity($caller, $entrepriseId);
        $client = $this->getOrCreateClient($entrepriseId, $clientData['phone'] ?? 'webrtc-' . uniqid());
        
        // Créer la conversation
        $conversationId = $this->createVoiceConversation($entrepriseId, $client['id'], $callSid, 'WebRTC');
        
        // Vérifier si le mode IA est activé
        $aiMode = $this->isAIModeEnabled($entreprise);
        
        // Stocker le contexte
        $this->storeCallContext($callSid, [
            'entreprise_id' => $entrepriseId,
            'client_id' => $client['id'],
            'conversation_id' => $conversationId,
            'langue' => $langue,
            'ai_mode' => $aiMode,
            'ai_history' => [],
            'source' => 'webrtc'
        ]);
        
        // Générer le message de bienvenue
        if ($aiMode && $this->aiAgent->isConfigured()) {
            echo $this->generateAIWelcomeResponse($entreprise, $langue);
        } else {
            echo $this->twilioService->generateWelcomeResponse($entreprise, $langue);
        }
    }
    
    /**
     * Parser l'identité WebRTC pour extraire les infos client
     */
    private function parseWebRTCIdentity(string $caller, int $entrepriseId): array
    {
        // Format: client:visitor_123_abc ou client:client_123_456
        if (strpos($caller, 'client:') === 0) {
            $identity = substr($caller, 7);
            $parts = explode('_', $identity);
            
            if (count($parts) >= 3 && $parts[0] === 'client') {
                return [
                    'type' => 'known',
                    'client_id' => (int)$parts[2]
                ];
            }
        }
        
        return ['type' => 'visitor'];
    }
}
