<?php
/**
 * Controller API Chat - Widget client
 * mySupport - Plateforme de Service Client Intelligent
 */

namespace App\Controllers;

use Core\Controller;
use Core\OpenAIService;
use App\Models\Entreprise;
use App\Models\Client;
use App\Models\Conversation;
use App\Models\Message;
use App\Services\EscalationService;
use App\Services\CSATService;
use App\Services\AutoTaggingService;

require_once ROOT_PATH . '/config/ai.php';
require_once ROOT_PATH . '/core/OpenAIService.php';
require_once ROOT_PATH . '/core/GoogleTTSService.php';
require_once APP_PATH . '/Models/Entreprise.php';
require_once APP_PATH . '/Models/Client.php';
require_once APP_PATH . '/Models/Conversation.php';
require_once APP_PATH . '/Models/Message.php';
require_once APP_PATH . '/Services/EscalationService.php';
require_once APP_PATH . '/Services/CSATService.php';
require_once APP_PATH . '/Services/AutoTaggingService.php';

class ChatApiController extends Controller
{
    private Entreprise $entrepriseModel;
    private Client $clientModel;
    private Conversation $conversationModel;
    private Message $messageModel;
    private OpenAIService $aiService;
    private EscalationService $escalationService;
    private CSATService $csatService;
    private AutoTaggingService $autoTaggingService;

    public function __construct()
    {
        parent::__construct();
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
        header('Access-Control-Allow-Headers: Content-Type, Authorization');
        
        if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
            exit(0);
        }
        
        $this->entrepriseModel = new Entreprise();
        $this->clientModel = new Client();
        $this->conversationModel = new Conversation();
        $this->messageModel = new Message();
        $this->aiService = new OpenAIService();
        $this->escalationService = new EscalationService();
        $this->csatService = new CSATService();
        $this->autoTaggingService = new AutoTaggingService();
    }

    public function startConversation(): void
    {
        $input = json_decode(file_get_contents('php://input'), true);
        
        $token = $input['token'] ?? '';
        $entreprise = $this->entrepriseModel->findByToken($token);
        
        if (!$entreprise || !$entreprise['is_active']) {
            $this->json(['error' => 'Entreprise non trouvée ou inactive'], 404);
            return;
        }

        $clientData = [
            'nom' => $input['nom'] ?? 'Visiteur',
            'email' => $input['email'] ?? null,
            'telephone' => $input['telephone'] ?? null,
            'langue_preferee' => $input['langue'] ?? 'fr'
        ];
        
        $clientId = $this->clientModel->findOrCreate($entreprise['id'], $clientData);

        $conversationId = $this->conversationModel->create([
            'entreprise_id' => $entreprise['id'],
            'client_id' => $clientId,
            'canal' => 'web',
            'sujet' => $input['sujet'] ?? 'Nouvelle conversation',
            'source_langue' => $clientData['langue_preferee'],
            'statut' => 'open'
        ]);

        $widgetConfig = json_decode($entreprise['widget_config'] ?? '{}', true);
        $messageBienvenue = $widgetConfig['message_bienvenue'] ?? 'Bonjour! Comment puis-je vous aider?';
        
        $this->messageModel->addMessage(
            $conversationId,
            'bot',
            null,
            $messageBienvenue,
            ['langue' => $clientData['langue_preferee']]
        );

        $this->json([
            'success' => true,
            'conversation_id' => $conversationId,
            'client_id' => $clientId,
            'message' => $messageBienvenue
        ]);
    }

    public function sendMessage(): void
    {
        $input = json_decode(file_get_contents('php://input'), true);
        
        $conversationId = $input['conversation_id'] ?? 0;
        $message = trim($input['message'] ?? '');
        $type = $input['type'] ?? 'text';
        
        if (empty($conversationId) || empty($message)) {
            $this->json(['error' => 'Données manquantes'], 400);
            return;
        }

        $conversation = $this->conversationModel->find($conversationId);
        
        if (!$conversation) {
            $this->json(['error' => 'Conversation non trouvée'], 404);
            return;
        }

        $messageId = $this->messageModel->addMessage(
            $conversationId,
            'client',
            $conversation['client_id'],
            $message,
            ['type_message' => $type, 'langue' => $conversation['source_langue']]
        );

        // Auto-tagging du message
        $tags = $this->autoTaggingService->analyzeAndTag($conversationId, $message, true);

        $botResponse = $this->processBotResponse($conversation['entreprise_id'], $message, $conversationId);
        
        if ($botResponse) {
            $this->messageModel->addMessage(
                $conversationId,
                'bot',
                null,
                $botResponse['message'],
                ['langue' => $conversation['source_langue']]
            );
            
            if ($botResponse['escalate']) {
                $this->conversationModel->escalate($conversationId, 'Demande complexe détectée par IA');
            }
        }

        $this->json([
            'success' => true,
            'message_id' => $messageId,
            'bot_response' => $botResponse,
            'tags' => $tags
        ]);
    }

    public function getMessages(string $conversationId): void
    {
        $conversation = $this->conversationModel->find((int) $conversationId);
        
        if (!$conversation) {
            $this->json(['error' => 'Conversation non trouvée'], 404);
            return;
        }

        $lastId = $this->input('last_id', 0);
        
        $sql = "SELECT * FROM messages 
                WHERE conversation_id = :cid";
        $params = ['cid' => $conversationId];
        
        if ($lastId > 0) {
            $sql .= " AND id > :last_id";
            $params['last_id'] = $lastId;
        }
        
        $sql .= " ORDER BY created_at ASC";
        
        $messages = $this->db->fetchAll($sql, $params);

        $this->json([
            'success' => true,
            'messages' => $messages,
            'conversation_status' => $conversation['statut']
        ]);
    }

    public function closeConversation(): void
    {
        $input = json_decode(file_get_contents('php://input'), true);
        
        $conversationId = $input['conversation_id'] ?? 0;
        $satisfaction = $input['satisfaction'] ?? null;
        $comment = $input['comment'] ?? null;
        
        $conversation = $this->conversationModel->find($conversationId);
        
        if (!$conversation) {
            $this->json(['error' => 'Conversation non trouvée'], 404);
            return;
        }

        $data = ['statut' => 'closed', 'closed_at' => date('Y-m-d H:i:s')];
        
        if ($satisfaction !== null) {
            $data['satisfaction_score'] = (int) $satisfaction;
        }
        if ($comment) {
            $data['satisfaction_comment'] = $comment;
        }
        
        $this->conversationModel->update($conversationId, $data);

        $this->json(['success' => true]);
    }

    private function processBotResponse(int $entrepriseId, string $message, int $conversationId): ?array
    {
        // 1. Utiliser l'IA en priorité (elle a accès aux FAQs dans son contexte)
        if ($this->aiService->isConfigured()) {
            return $this->getAIResponse($entrepriseId, $message, $conversationId);
        }

        // 2. Si pas d'IA, chercher dans la FAQ avec correspondance stricte
        $faqResponse = $this->searchFAQ($entrepriseId, $message);
        if ($faqResponse) {
            return $faqResponse;
        }

        // 3. Fallback si pas d'IA ni FAQ
        return $this->getFallbackResponse($message);
    }

    private function searchFAQ(int $entrepriseId, string $message): ?array
    {
        // Recherche améliorée: score de pertinence basé sur le nombre de mots-clés correspondants
        $keywords = array_filter(explode(' ', strtolower($message)), fn($w) => strlen($w) > 3);
        
        if (empty($keywords)) {
            return null;
        }

        // Récupérer toutes les FAQs actives
        $faqs = $this->db->fetchAll(
            "SELECT * FROM faq WHERE entreprise_id = :eid AND is_active = TRUE",
            ['eid' => $entrepriseId]
        );

        $bestMatch = null;
        $bestScore = 0;
        $minScore = max(2, count($keywords) * 0.5); // Au moins 50% des mots-clés ou 2 minimum

        foreach ($faqs as $faq) {
            $score = 0;
            $questionLower = strtolower($faq['question']);
            $keywordsJson = json_decode($faq['keywords'] ?? '[]', true) ?: [];
            
            foreach ($keywords as $keyword) {
                // +2 points si le mot-clé est dans la question
                if (strpos($questionLower, $keyword) !== false) {
                    $score += 2;
                }
                // +3 points si le mot-clé est dans les keywords définis
                foreach ($keywordsJson as $faqKeyword) {
                    if (strpos(strtolower($faqKeyword), $keyword) !== false || 
                        strpos($keyword, strtolower($faqKeyword)) !== false) {
                        $score += 3;
                    }
                }
            }
            
            if ($score > $bestScore && $score >= $minScore) {
                $bestScore = $score;
                $bestMatch = $faq;
            }
        }
        
        if ($bestMatch) {
            $this->db->query(
                "UPDATE faq SET views_count = views_count + 1 WHERE id = :id",
                ['id' => $bestMatch['id']]
            );
            
            return [
                'message' => $bestMatch['reponse'],
                'escalate' => false,
                'source' => 'faq',
                'score' => $bestScore
            ];
        }

        return null;
    }

    private function getAIResponse(int $entrepriseId, string $message, int $conversationId): array
    {
        // Récupérer le contexte de l'entreprise
        $entreprise = $this->entrepriseModel->find($entrepriseId);
        $iaConfig = json_decode($entreprise['ia_config'] ?? '{}', true);
        
        // Récupérer l'historique de la conversation
        $history = $this->db->fetchAll(
            "SELECT sender_type, contenu FROM messages 
             WHERE conversation_id = :cid 
             ORDER BY created_at DESC LIMIT 10",
            ['cid' => $conversationId]
        );
        $history = array_reverse($history);

        // Récupérer les FAQ pour enrichir le contexte
        $faqs = $this->db->fetchAll(
            "SELECT question, reponse FROM faq 
             WHERE entreprise_id = :eid AND is_active = TRUE LIMIT 10",
            ['eid' => $entrepriseId]
        );

        // Récupérer les documents de la base de connaissances
        $documents = $this->db->fetchAll(
            "SELECT titre, description, contenu_extrait FROM ia_documents 
             WHERE entreprise_id = :eid AND is_active = TRUE",
            ['eid' => $entrepriseId]
        );

        // Construire le contexte enrichi
        $context = [
            'entreprise_nom' => $entreprise['nom'] ?? 'Notre entreprise',
            'entreprise_contexte' => $iaConfig['contexte'] ?? ($entreprise['secteur'] ?? 'Service client'),
            'ton' => $iaConfig['ton'] ?? 'professionnel',
            'instructions' => $iaConfig['instructions'] ?? '',
            'history' => $history,
            'faq' => $faqs,
            'documents' => $documents
        ];

        // Appeler l'IA
        $aiResponse = $this->aiService->generateResponse($message, $context);

        if ($aiResponse['success']) {
            // Analyser le sentiment du message client
            $sentiment = $this->aiService->analyzeSentiment($message);
            
            // Logger les tokens utilisés (pour monitoring)
            $this->logAIUsage($entrepriseId, $aiResponse['tokens_used'] ?? 0);

            return [
                'message' => $aiResponse['message'],
                'escalate' => $aiResponse['should_escalate'] ?? false,
                'source' => 'ai',
                'sentiment' => $sentiment
            ];
        }

        // Si l'IA échoue, utiliser le fallback
        return $this->getFallbackResponse($message);
    }

    private function getFallbackResponse(string $message): array
    {
        $escalateKeywords = ['urgent', 'plainte', 'réclamation', 'problème grave', 'parler humain', 'agent', 'responsable'];
        $messageLower = strtolower($message);
        
        foreach ($escalateKeywords as $keyword) {
            if (strpos($messageLower, $keyword) !== false) {
                return [
                    'message' => "Je comprends que votre demande nécessite une attention particulière. Un agent va prendre en charge votre demande dans les plus brefs délais.",
                    'escalate' => true,
                    'source' => 'escalation'
                ];
            }
        }

        return [
            'message' => "Merci pour votre message. Je le transmets à notre équipe qui vous répondra rapidement.",
            'escalate' => false,
            'source' => 'default'
        ];
    }

    private function logAIUsage(int $entrepriseId, int $tokensUsed): void
    {
        try {
            $this->db->insert('ai_usage_logs', [
                'entreprise_id' => $entrepriseId,
                'tokens_used' => $tokensUsed,
                'created_at' => date('Y-m-d H:i:s')
            ]);
        } catch (\Exception $e) {
            // Silently fail - table might not exist yet
        }
    }
    
    /**
     * Synthèse vocale via Google Cloud TTS
     */
    public function synthesizeSpeech(): void
    {
        header('Content-Type: application/json');
        
        $data = json_decode(file_get_contents('php://input'), true);
        $text = $data['text'] ?? '';
        $lang = $data['lang'] ?? 'fr-FR';
        
        if (empty($text)) {
            echo json_encode(['success' => false, 'error' => 'Texte requis']);
            return;
        }
        
        // Check if Google TTS is enabled
        if (!defined('GOOGLE_TTS_ENABLED') || !GOOGLE_TTS_ENABLED) {
            echo json_encode(['success' => false, 'error' => 'Google TTS non configuré', 'fallback' => true]);
            return;
        }
        
        $ttsService = new \GoogleTTSService();
        
        if (!$ttsService->isConfigured()) {
            echo json_encode(['success' => false, 'error' => 'Clé API Google TTS manquante', 'fallback' => true]);
            return;
        }
        
        $audioContent = $ttsService->synthesize($text, $lang);
        
        if ($audioContent) {
            echo json_encode([
                'success' => true,
                'audio' => $audioContent, // Base64 MP3
                'format' => 'mp3'
            ]);
        } else {
            echo json_encode(['success' => false, 'error' => 'Erreur de synthèse', 'fallback' => true]);
        }
    }

    /**
     * Créer un ticket de support (escalade)
     */
    public function createTicket(): void
    {
        $input = json_decode(file_get_contents('php://input'), true);
        
        $conversationId = $input['conversation_id'] ?? null;
        $token = $input['token'] ?? '';
        
        if (!$conversationId || !$token) {
            $this->json(['error' => 'Paramètres manquants'], 400);
            return;
        }

        $entreprise = $this->entrepriseModel->findByToken($token);
        if (!$entreprise) {
            $this->json(['error' => 'Entreprise non trouvée'], 404);
            return;
        }

        $conversation = $this->conversationModel->find($conversationId);
        if (!$conversation || $conversation['entreprise_id'] != $entreprise['id']) {
            $this->json(['error' => 'Conversation non trouvée'], 404);
            return;
        }

        // Créer le ticket
        $result = $this->escalationService->createTicket([
            'entreprise_id' => $entreprise['id'],
            'conversation_id' => $conversationId,
            'client_id' => $conversation['client_id'],
            'sujet' => $input['sujet'] ?? 'Demande d\'assistance via chat',
            'description' => $input['description'] ?? '',
            'categorie' => $input['categorie'] ?? 'support',
            'priorite' => $input['priorite'] ?? 'medium',
            'source' => 'chat_escalation'
        ]);

        // Envoyer message de confirmation dans le chat
        $ticketMessage = "✅ **Ticket créé avec succès!**\n\n";
        $ticketMessage .= "📋 **Numéro de suivi:** `{$result['ticket_number']}`\n\n";
        $ticketMessage .= "Conservez ce numéro pour suivre l'avancement de votre demande. ";
        $ticketMessage .= "Un agent va traiter votre ticket dans les plus brefs délais.\n\n";
        $ticketMessage .= "Vous recevrez une notification dès qu'il y aura une mise à jour.";

        $this->messageModel->create([
            'conversation_id' => $conversationId,
            'sender_type' => 'bot',
            'contenu' => $ticketMessage,
            'type_message' => 'text'
        ]);

        $this->json([
            'success' => true,
            'ticket_id' => $result['ticket_id'],
            'ticket_number' => $result['ticket_number'],
            'message' => $ticketMessage
        ]);
    }

    /**
     * Demander un chat en temps réel avec un agent
     */
    public function requestLiveChat(): void
    {
        $input = json_decode(file_get_contents('php://input'), true);
        
        $conversationId = $input['conversation_id'] ?? null;
        $token = $input['token'] ?? '';
        
        if (!$conversationId || !$token) {
            $this->json(['error' => 'Paramètres manquants'], 400);
            return;
        }

        $entreprise = $this->entrepriseModel->findByToken($token);
        if (!$entreprise) {
            $this->json(['error' => 'Entreprise non trouvée'], 404);
            return;
        }

        $conversation = $this->conversationModel->find($conversationId);
        if (!$conversation || $conversation['entreprise_id'] != $entreprise['id']) {
            $this->json(['error' => 'Conversation non trouvée'], 404);
            return;
        }

        // Créer la demande de chat en direct
        $result = $this->escalationService->createLiveRequest([
            'entreprise_id' => $entreprise['id'],
            'conversation_id' => $conversationId,
            'client_id' => $conversation['client_id'],
            'reason' => $input['reason'] ?? 'Demande de chat en direct'
        ]);

        // Message selon le statut
        if ($result['status'] === 'already_waiting') {
            $message = "⏳ Vous êtes déjà dans la file d'attente.\n\n";
            $message .= "**Position:** {$result['position']} dans la file\n\n";
            $message .= "Un agent va vous répondre très prochainement. Merci de patienter.";
        } else {
            $message = "🎯 **Demande de chat en direct enregistrée!**\n\n";
            $message .= "**Position dans la file:** {$result['position']}\n\n";
            $message .= "Un agent va prendre en charge votre conversation très prochainement. ";
            $message .= "Restez connecté, vous serez notifié dès qu'un agent est disponible.";
        }

        $this->messageModel->create([
            'conversation_id' => $conversationId,
            'sender_type' => 'bot',
            'contenu' => $message,
            'type_message' => 'text'
        ]);

        $this->json([
            'success' => true,
            'request_id' => $result['request_id'],
            'status' => $result['status'],
            'position' => $result['position'],
            'message' => $message
        ]);
    }

    /**
     * Vérifier le statut d'escalade
     */
    public function checkEscalationStatus(): void
    {
        $conversationId = $_GET['conversation_id'] ?? null;
        $token = $_GET['token'] ?? '';
        
        if (!$conversationId || !$token) {
            $this->json(['error' => 'Paramètres manquants'], 400);
            return;
        }

        $entreprise = $this->entrepriseModel->findByToken($token);
        if (!$entreprise) {
            $this->json(['error' => 'Entreprise non trouvée'], 404);
            return;
        }

        $conversation = $this->conversationModel->find($conversationId);
        if (!$conversation || $conversation['entreprise_id'] != $entreprise['id']) {
            $this->json(['error' => 'Conversation non trouvée'], 404);
            return;
        }

        $response = [
            'escalation_type' => $conversation['escalation_type'] ?? 'none',
            'is_escalated' => (bool)$conversation['is_escalated'],
            'agent_assigned' => !empty($conversation['agent_id'])
        ];

        // Vérifier le statut du ticket si existe
        if ($conversation['escalation_type'] === 'ticket') {
            $ticket = $this->escalationService->getTicketByConversation($conversationId);
            if ($ticket) {
                $response['ticket'] = [
                    'number' => $ticket['ticket_number'],
                    'status' => $ticket['statut'],
                    'agent' => $ticket['agent_nom'] ? $ticket['agent_prenom'] . ' ' . $ticket['agent_nom'] : null
                ];
            }
        }

        // Vérifier le statut de la demande live si existe
        if ($conversation['escalation_type'] === 'live_chat') {
            $liveRequest = $this->escalationService->checkLiveRequestStatus($conversationId);
            if ($liveRequest) {
                $response['live_request'] = [
                    'status' => $liveRequest['statut'],
                    'position' => $liveRequest['statut'] === 'waiting' 
                        ? $this->escalationService->getQueuePosition($entreprise['id'], $liveRequest['id']) 
                        : 0,
                    'agent' => $liveRequest['agent_nom'] ? $liveRequest['agent_prenom'] . ' ' . $liveRequest['agent_nom'] : null
                ];

                // Si un agent est assigné, envoyer un message
                if ($liveRequest['statut'] === 'assigned' && $liveRequest['agent_nom']) {
                    $response['agent_connected'] = true;
                    $response['agent_name'] = $liveRequest['agent_prenom'] . ' ' . $liveRequest['agent_nom'];
                }
            }
        }

        $this->json($response);
    }

    /**
     * Proposer les options d'escalade (appelé par l'IA ou automatiquement)
     */
    public function getEscalationOptions(): void
    {
        $this->json([
            'show_options' => true,
            'message' => "Je vois que vous avez besoin d'une assistance supplémentaire. Choisissez l'option qui vous convient le mieux:",
            'options' => [
                [
                    'id' => 'ticket',
                    'label' => '📋 Créer un ticket',
                    'description' => 'Recevez un numéro de suivi et un agent traitera votre demande',
                    'action' => 'create_ticket'
                ],
                [
                    'id' => 'live_chat',
                    'label' => '💬 Chat en direct',
                    'description' => 'Parlez immédiatement avec un agent disponible',
                    'action' => 'request_live_chat'
                ]
            ]
        ]);
    }

    // ==========================================
    // CSAT - Enquête de satisfaction
    // ==========================================

    /**
     * Soumettre une réponse CSAT
     */
    public function submitCSAT(): void
    {
        $input = json_decode(file_get_contents('php://input'), true);
        
        $conversationId = $input['conversation_id'] ?? null;
        $score = $input['score'] ?? null;
        $comment = $input['comment'] ?? null;
        $token = $input['token'] ?? '';

        if (!$conversationId || !$score) {
            $this->json(['success' => false, 'error' => 'Données manquantes'], 400);
            return;
        }

        // Vérifier le token
        $entreprise = $this->entrepriseModel->findByToken($token);
        if (!$entreprise) {
            $this->json(['success' => false, 'error' => 'Token invalide'], 403);
            return;
        }

        // Vérifier que la conversation appartient à l'entreprise
        $conversation = $this->conversationModel->find($conversationId);
        if (!$conversation || $conversation['entreprise_id'] != $entreprise['id']) {
            $this->json(['success' => false, 'error' => 'Conversation non trouvée'], 404);
            return;
        }

        $result = $this->csatService->submitResponse([
            'conversation_id' => $conversationId,
            'score' => $score,
            'comment' => $comment,
            'source' => 'widget'
        ]);

        $this->json($result);
    }

    /**
     * Vérifier le statut d'une conversation (pour déclencher CSAT)
     */
    public function getConversationStatus(): void
    {
        $conversationId = $_GET['id'] ?? null;
        $token = $_GET['token'] ?? '';

        if (!$conversationId) {
            $this->json(['error' => 'ID manquant'], 400);
            return;
        }

        $entreprise = $this->entrepriseModel->findByToken($token);
        if (!$entreprise) {
            $this->json(['error' => 'Token invalide'], 403);
            return;
        }

        $conversation = $this->conversationModel->find($conversationId);
        if (!$conversation || $conversation['entreprise_id'] != $entreprise['id']) {
            $this->json(['error' => 'Conversation non trouvée'], 404);
            return;
        }

        $this->json([
            'status' => $conversation['statut'],
            'csat_sent' => (bool) ($conversation['csat_score'] ?? false),
            'csat_enabled' => (bool) ($entreprise['csat_enabled'] ?? true)
        ]);
    }

    /**
     * Page de feedback via lien email
     */
    public function feedbackPage(string $token): void
    {
        $tokenData = $this->csatService->validateToken($token);
        
        if (!$tokenData) {
            // Token invalide ou expiré
            echo $this->renderFeedbackError();
            return;
        }

        echo $this->renderFeedbackForm($tokenData, $token);
    }

    /**
     * Soumettre feedback via lien email
     */
    public function submitFeedback(string $token): void
    {
        $score = $_POST['score'] ?? null;
        $comment = $_POST['comment'] ?? null;

        if (!$score) {
            $this->json(['success' => false, 'error' => 'Score requis'], 400);
            return;
        }

        $result = $this->csatService->submitViaToken($token, (int)$score, $comment);
        
        if ($result['success']) {
            echo $this->renderFeedbackThankYou();
        } else {
            echo $this->renderFeedbackError($result['error']);
        }
    }

    private function renderFeedbackForm(array $data, string $token): string
    {
        $entreprise = htmlspecialchars($data['entreprise_nom']);
        $sujet = htmlspecialchars($data['sujet'] ?? '');
        
        return <<<HTML
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Votre avis - {$entreprise}</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style>body { font-family: 'Inter', sans-serif; }</style>
</head>
<body class="bg-gradient-to-br from-purple-50 to-indigo-100 min-h-screen flex items-center justify-center p-4">
    <div class="bg-white rounded-2xl shadow-xl max-w-md w-full p-8">
        <div class="text-center mb-8">
            <div class="w-16 h-16 bg-gradient-to-br from-purple-500 to-indigo-500 rounded-full flex items-center justify-center mx-auto mb-4">
                <svg class="w-8 h-8 text-white" fill="currentColor" viewBox="0 0 20 20">
                    <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z"/>
                </svg>
            </div>
            <h1 class="text-2xl font-bold text-gray-800">Votre avis compte !</h1>
            <p class="text-gray-500 mt-2">{$entreprise}</p>
        </div>
        
        <form action="/feedback/{$token}" method="POST">
            <p class="text-center text-gray-700 mb-6">Comment évaluez-vous notre service ?</p>
            
            <div class="flex justify-center gap-3 mb-6" id="stars">
                <input type="hidden" name="score" id="score-input" required>
                <button type="button" onclick="setScore(1)" class="star-btn w-12 h-12 rounded-full border-2 border-gray-200 hover:border-yellow-400 transition flex items-center justify-center text-2xl" data-score="1">⭐</button>
                <button type="button" onclick="setScore(2)" class="star-btn w-12 h-12 rounded-full border-2 border-gray-200 hover:border-yellow-400 transition flex items-center justify-center text-2xl" data-score="2">⭐</button>
                <button type="button" onclick="setScore(3)" class="star-btn w-12 h-12 rounded-full border-2 border-gray-200 hover:border-yellow-400 transition flex items-center justify-center text-2xl" data-score="3">⭐</button>
                <button type="button" onclick="setScore(4)" class="star-btn w-12 h-12 rounded-full border-2 border-gray-200 hover:border-yellow-400 transition flex items-center justify-center text-2xl" data-score="4">⭐</button>
                <button type="button" onclick="setScore(5)" class="star-btn w-12 h-12 rounded-full border-2 border-gray-200 hover:border-yellow-400 transition flex items-center justify-center text-2xl" data-score="5">⭐</button>
            </div>
            
            <div class="flex justify-between text-xs text-gray-400 mb-6 px-2">
                <span>Très insatisfait</span>
                <span>Très satisfait</span>
            </div>
            
            <div class="mb-6">
                <label class="block text-sm font-medium text-gray-700 mb-2">Un commentaire ? (optionnel)</label>
                <textarea name="comment" rows="3" class="w-full px-4 py-3 border border-gray-200 rounded-xl focus:ring-2 focus:ring-purple-500 focus:border-purple-500 resize-none" placeholder="Dites-nous en plus..."></textarea>
            </div>
            
            <button type="submit" class="w-full py-3 bg-gradient-to-r from-purple-500 to-indigo-500 text-white font-semibold rounded-xl hover:from-purple-600 hover:to-indigo-600 transition">
                Envoyer mon avis
            </button>
        </form>
    </div>
    
    <script>
        function setScore(score) {
            document.getElementById('score-input').value = score;
            document.querySelectorAll('.star-btn').forEach((btn, idx) => {
                if (idx < score) {
                    btn.classList.add('border-yellow-400', 'bg-yellow-50');
                    btn.classList.remove('border-gray-200');
                } else {
                    btn.classList.remove('border-yellow-400', 'bg-yellow-50');
                    btn.classList.add('border-gray-200');
                }
            });
        }
    </script>
</body>
</html>
HTML;
    }

    private function renderFeedbackThankYou(): string
    {
        return <<<HTML
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Merci !</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gradient-to-br from-green-50 to-emerald-100 min-h-screen flex items-center justify-center p-4">
    <div class="bg-white rounded-2xl shadow-xl max-w-md w-full p-8 text-center">
        <div class="w-20 h-20 bg-gradient-to-br from-green-500 to-emerald-500 rounded-full flex items-center justify-center mx-auto mb-6">
            <svg class="w-10 h-10 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/>
            </svg>
        </div>
        <h1 class="text-3xl font-bold text-gray-800 mb-4">Merci ! 🎉</h1>
        <p class="text-gray-600 mb-6">Votre avis a bien été enregistré.<br>Il nous aide à nous améliorer !</p>
        <p class="text-sm text-gray-400">Vous pouvez fermer cette page.</p>
    </div>
</body>
</html>
HTML;
    }

    private function renderFeedbackError(?string $message = null): string
    {
        $error = $message ?? 'Ce lien est invalide ou a expiré.';
        return <<<HTML
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Lien expiré</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gradient-to-br from-red-50 to-orange-100 min-h-screen flex items-center justify-center p-4">
    <div class="bg-white rounded-2xl shadow-xl max-w-md w-full p-8 text-center">
        <div class="w-20 h-20 bg-gradient-to-br from-red-500 to-orange-500 rounded-full flex items-center justify-center mx-auto mb-6">
            <svg class="w-10 h-10 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"/>
            </svg>
        </div>
        <h1 class="text-2xl font-bold text-gray-800 mb-4">Oups !</h1>
        <p class="text-gray-600">{$error}</p>
    </div>
</body>
</html>
HTML;
    }
}
