<?php
/**
 * Controller Admin Entreprise
 * mySupport - Plateforme de Service Client Intelligent
 */

namespace App\Controllers;

use Core\Controller;
use App\Models\Entreprise;
use App\Models\User;
use App\Models\Conversation;
use App\Models\Alerte;
use App\Models\Client;
use App\Services\CSATService;

require_once APP_PATH . '/Models/Entreprise.php';
require_once APP_PATH . '/Models/User.php';
require_once APP_PATH . '/Models/Conversation.php';
require_once APP_PATH . '/Models/Alerte.php';
require_once APP_PATH . '/Models/Client.php';
require_once APP_PATH . '/Services/CSATService.php';

class AdminController extends Controller
{
    private Entreprise $entrepriseModel;
    private User $userModel;
    private Conversation $conversationModel;
    private Alerte $alerteModel;
    private Client $clientModel;
    private CSATService $csatService;
    private int $entrepriseId;

    public function __construct()
    {
        parent::__construct();
        $this->requireRole(ROLE_ADMIN_ENTREPRISE);
        
        $this->entrepriseId = $_SESSION['entreprise_id'];
        
        $this->entrepriseModel = new Entreprise();
        $this->userModel = new User();
        $this->conversationModel = new Conversation();
        $this->alerteModel = new Alerte();
        $this->clientModel = new Client();
        $this->csatService = new CSATService();
    }

    public function dashboard(): void
    {
        $entreprise = $this->entrepriseModel->find($this->entrepriseId);
        $stats = $this->conversationModel->getStatistiques($this->entrepriseId);
        $conversationsRecentes = $this->conversationModel->getByEntreprise($this->entrepriseId, null, 10);
        $alertes = $this->alerteModel->getByEntreprise($this->entrepriseId, true);
        $agents = $this->userModel->getAgentsByEntreprise($this->entrepriseId);
        
        $cxIndex = $this->calculateCxIndex($stats);
        
        // Stats CSAT
        $csatStats = $this->csatService->getStats($this->entrepriseId, '30days');
        $csatRecent = $this->csatService->getLatestResponses($this->entrepriseId, 5);
        
        $this->view('admin/dashboard', [
            'entreprise' => $entreprise,
            'stats' => $stats,
            'conversations' => $conversationsRecentes,
            'alertes' => $alertes,
            'agents' => $agents,
            'cxIndex' => $cxIndex,
            'csatStats' => $csatStats,
            'csatRecent' => $csatRecent,
            'user' => $this->currentUser()
        ]);
    }

    public function agents(): void
    {
        $agents = $this->userModel->getAgentsByEntreprise($this->entrepriseId);
        $entreprise = $this->entrepriseModel->find($this->entrepriseId);
        
        $this->view('admin/agents/index', [
            'agents' => $agents,
            'entreprise' => $entreprise,
            'user' => $this->currentUser()
        ]);
    }

    public function createAgent(): void
    {
        $entreprise = $this->entrepriseModel->find($this->entrepriseId);
        $currentAgents = $this->userModel->countAgents($this->entrepriseId);
        
        if ($currentAgents >= $entreprise['max_agents']) {
            $_SESSION['flash_error'] = 'Nombre maximum d\'agents atteint pour votre abonnement.';
            $this->redirect('/admin/agents');
            return;
        }
        
        $this->view('admin/agents/create', [
            'csrf_token' => $this->generateCsrf(),
            'user' => $this->currentUser()
        ]);
    }

    public function storeAgent(): void
    {
        if (!$this->isPost() || !$this->validateCsrf()) {
            $this->redirect('/admin/agents');
            return;
        }

        $entreprise = $this->entrepriseModel->find($this->entrepriseId);
        $currentAgents = $this->userModel->countAgents($this->entrepriseId);
        
        if ($currentAgents >= $entreprise['max_agents']) {
            $_SESSION['flash_error'] = 'Nombre maximum d\'agents atteint.';
            $this->redirect('/admin/agents');
            return;
        }

        $email = $this->sanitize($this->input('email'));
        
        if ($this->userModel->exists('email', $email)) {
            $_SESSION['flash_error'] = 'Cet email est déjà utilisé.';
            $this->redirect('/admin/agents/create');
            return;
        }

        $this->userModel->createUser([
            'entreprise_id' => $this->entrepriseId,
            'email' => $email,
            'password' => $this->input('password'),
            'nom' => $this->sanitize($this->input('nom')),
            'prenom' => $this->sanitize($this->input('prenom')),
            'telephone' => $this->sanitize($this->input('telephone')),
            'role' => ROLE_AGENT
        ]);

        $_SESSION['flash_success'] = 'Agent créé avec succès.';
        $this->redirect('/admin/agents');
    }

    public function editAgent(string $id): void
    {
        $agent = $this->userModel->find((int) $id);
        
        if (!$agent || $agent['entreprise_id'] != $this->entrepriseId) {
            $this->redirect('/admin/agents');
            return;
        }

        $this->view('admin/agents/edit', [
            'agent' => $agent,
            'csrf_token' => $this->generateCsrf(),
            'user' => $this->currentUser()
        ]);
    }

    public function updateAgent(string $id): void
    {
        if (!$this->isPost() || !$this->validateCsrf()) {
            $this->redirect('/admin/agents/' . $id);
            return;
        }

        $agent = $this->userModel->find((int) $id);
        
        if (!$agent || $agent['entreprise_id'] != $this->entrepriseId) {
            $this->redirect('/admin/agents');
            return;
        }

        $data = [
            'nom' => $this->sanitize($this->input('nom')),
            'prenom' => $this->sanitize($this->input('prenom')),
            'telephone' => $this->sanitize($this->input('telephone')),
            'is_active' => $this->input('is_active') ? true : false
        ];

        $newPassword = $this->input('password');
        if (!empty($newPassword)) {
            $data['password'] = password_hash($newPassword, PASSWORD_DEFAULT);
        }

        $this->userModel->update((int) $id, $data);
        
        $_SESSION['flash_success'] = 'Agent mis à jour avec succès.';
        $this->redirect('/admin/agents');
    }

    public function deleteAgent(string $id): void
    {
        if (!$this->isPost()) {
            $this->redirect('/admin/agents');
            return;
        }

        $agent = $this->userModel->find((int) $id);
        
        if ($agent && $agent['entreprise_id'] == $this->entrepriseId && $agent['role'] == ROLE_AGENT) {
            $this->userModel->delete((int) $id);
            $_SESSION['flash_success'] = 'Agent supprimé avec succès.';
        }

        if ($this->isAjax()) {
            $this->json(['success' => true]);
        } else {
            $this->redirect('/admin/agents');
        }
    }

    public function conversations(): void
    {
        $statut = $this->input('statut');
        $conversations = $this->conversationModel->getByEntreprise($this->entrepriseId, $statut, 100);
        
        $this->view('admin/conversations/index', [
            'conversations' => $conversations,
            'currentStatut' => $statut,
            'user' => $this->currentUser()
        ]);
    }
    
    public function viewConversation(string $id): void
    {
        $conversation = $this->conversationModel->getConversationWithMessages((int) $id);
        
        if (!$conversation || $conversation['entreprise_id'] != $this->entrepriseId) {
            $this->redirect('/admin/conversations');
            return;
        }
        
        $client = null;
        if ($conversation['client_id']) {
            $client = $this->clientModel->find($conversation['client_id']);
        }
        
        $agents = $this->userModel->getAgentsByEntreprise($this->entrepriseId);
        
        $this->view('admin/conversations/view', [
            'conversation' => $conversation,
            'client' => $client,
            'agents' => $agents,
            'user' => $this->currentUser()
        ]);
    }

    public function statistiques(): void
    {
        $dateFrom = $this->input('from', date('Y-m-01'));
        $dateTo = $this->input('to', date('Y-m-d'));
        
        $stats = $this->conversationModel->getStatistiques($this->entrepriseId, $dateFrom, $dateTo);
        $byCanal = $this->conversationModel->countByCanal($this->entrepriseId);
        
        $this->view('admin/statistiques', [
            'stats' => $stats,
            'byCanal' => $byCanal,
            'dateFrom' => $dateFrom,
            'dateTo' => $dateTo,
            'user' => $this->currentUser()
        ]);
    }

    public function cxIndex(): void
    {
        $stats = $this->conversationModel->getStatistiques($this->entrepriseId);
        $cxData = $this->calculateCxIndex($stats);
        
        $sql = "SELECT * FROM cx_index_daily 
                WHERE entreprise_id = :eid 
                ORDER BY date DESC LIMIT 30";
        $historique = $this->db->fetchAll($sql, ['eid' => $this->entrepriseId]);
        
        $this->view('admin/cx-index', [
            'cxData' => $cxData,
            'stats' => $stats,
            'historique' => $historique,
            'user' => $this->currentUser()
        ]);
    }

    public function alertes(): void
    {
        $alertes = $this->alerteModel->getByEntreprise($this->entrepriseId);
        
        $this->view('admin/alertes', [
            'alertes' => $alertes,
            'user' => $this->currentUser()
        ]);
    }

    public function parametres(): void
    {
        $entreprise = $this->entrepriseModel->find($this->entrepriseId);
        
        $this->view('admin/parametres', [
            'entreprise' => $entreprise,
            'langues' => LANGUAGES,
            'csrf_token' => $this->generateCsrf(),
            'user' => $this->currentUser()
        ]);
    }
    
    public function integration(): void
    {
        $entreprise = $this->entrepriseModel->find($this->entrepriseId);
        
        // Générer une clé API si elle n'existe pas
        if (empty($entreprise['api_key'])) {
            $newKey = $this->entrepriseModel->regenerateApiKey($this->entrepriseId);
            $entreprise['api_key'] = $newKey;
        }
        
        $this->view('admin/integration', [
            'entreprise' => $entreprise,
            'user' => $this->currentUser()
        ]);
    }
    
    public function regenerateApiKey(): void
    {
        if (!$this->isPost()) {
            $this->json(['success' => false, 'error' => 'Méthode non autorisée']);
            return;
        }
        
        $newKey = $this->entrepriseModel->regenerateApiKey($this->entrepriseId);
        
        if ($newKey) {
            $this->json(['success' => true, 'api_key' => $newKey]);
        } else {
            $this->json(['success' => false, 'error' => 'Erreur lors de la régénération']);
        }
    }

    public function updateParametres(): void
    {
        if (!$this->isPost() || !$this->validateCsrf()) {
            $this->redirect('/admin/parametres');
            return;
        }

        $widgetConfig = [
            'couleur_primaire' => $this->sanitize($this->input('couleur_primaire', '#4F46E5')),
            'message_bienvenue' => $this->sanitize($this->input('message_bienvenue', 'Bienvenue!')),
            'position' => $this->input('position', 'right')
        ];

        $this->entrepriseModel->update($this->entrepriseId, [
            'widget_config' => json_encode($widgetConfig)
        ]);

        $_SESSION['flash_success'] = 'Paramètres mis à jour avec succès.';
        $this->redirect('/admin/parametres');
    }

    // ==========================================
    // GESTION IA & FAQ
    // ==========================================

    public function ia(): void
    {
        $entreprise = $this->entrepriseModel->find($this->entrepriseId);
        
        // Récupérer les FAQ
        $faqs = $this->db->fetchAll(
            "SELECT * FROM faq WHERE entreprise_id = :eid ORDER BY created_at DESC",
            ['eid' => $this->entrepriseId]
        );

        // Récupérer les documents
        $documents = $this->db->fetchAll(
            "SELECT * FROM ia_documents WHERE entreprise_id = :eid ORDER BY created_at DESC",
            ['eid' => $this->entrepriseId]
        );
        
        // Récupérer les stats d'utilisation IA
        $aiStats = $this->db->fetch(
            "SELECT 
                COUNT(*) as total_requests,
                SUM(tokens_used) as total_tokens,
                DATE(MIN(created_at)) as first_use
             FROM ai_usage_logs 
             WHERE entreprise_id = :eid",
            ['eid' => $this->entrepriseId]
        );
        
        // Vérifier si l'IA est configurée
        $aiConfigured = defined('OPENAI_API_KEY') && !empty(OPENAI_API_KEY);
        
        $this->view('admin/ia/index', [
            'entreprise' => $entreprise,
            'faqs' => $faqs,
            'documents' => $documents,
            'aiStats' => $aiStats,
            'aiConfigured' => $aiConfigured,
            'csrf_token' => $this->generateCsrf(),
            'user' => $this->currentUser()
        ]);
    }

    public function createFaq(): void
    {
        $this->view('admin/ia/faq-create', [
            'csrf_token' => $this->generateCsrf(),
            'user' => $this->currentUser()
        ]);
    }

    public function storeFaq(): void
    {
        if (!$this->isPost() || !$this->validateCsrf()) {
            $this->redirect('/admin/ia');
            return;
        }

        $this->db->insert('faq', [
            'entreprise_id' => $this->entrepriseId,
            'question' => $this->sanitize($this->input('question')),
            'reponse' => $this->sanitize($this->input('reponse')),
            'categorie' => $this->sanitize($this->input('categorie', 'Général')),
            'is_active' => $this->input('is_active') ? 1 : 0,
            'created_at' => date('Y-m-d H:i:s')
        ]);

        $_SESSION['flash_success'] = 'FAQ ajoutée avec succès. L\'IA utilisera cette information.';
        $this->redirect('/admin/ia');
    }

    public function editFaq(string $id): void
    {
        $faq = $this->db->fetch(
            "SELECT * FROM faq WHERE id = :id AND entreprise_id = :eid",
            ['id' => $id, 'eid' => $this->entrepriseId]
        );
        
        if (!$faq) {
            $this->redirect('/admin/ia');
            return;
        }

        $this->view('admin/ia/faq-edit', [
            'faq' => $faq,
            'csrf_token' => $this->generateCsrf(),
            'user' => $this->currentUser()
        ]);
    }

    public function updateFaq(string $id): void
    {
        if (!$this->isPost() || !$this->validateCsrf()) {
            $this->redirect('/admin/ia');
            return;
        }

        $faq = $this->db->fetch(
            "SELECT * FROM faq WHERE id = :id AND entreprise_id = :eid",
            ['id' => $id, 'eid' => $this->entrepriseId]
        );
        
        if (!$faq) {
            $this->redirect('/admin/ia');
            return;
        }

        $this->db->query(
            "UPDATE faq SET 
                question = :question,
                reponse = :reponse,
                categorie = :categorie,
                is_active = :is_active,
                updated_at = NOW()
             WHERE id = :id",
            [
                'question' => $this->sanitize($this->input('question')),
                'reponse' => $this->sanitize($this->input('reponse')),
                'categorie' => $this->sanitize($this->input('categorie', 'Général')),
                'is_active' => $this->input('is_active') ? 1 : 0,
                'id' => $id
            ]
        );

        $_SESSION['flash_success'] = 'FAQ mise à jour avec succès.';
        $this->redirect('/admin/ia');
    }

    public function deleteFaq(string $id): void
    {
        if (!$this->isPost()) {
            $this->redirect('/admin/ia');
            return;
        }

        $this->db->query(
            "DELETE FROM faq WHERE id = :id AND entreprise_id = :eid",
            ['id' => $id, 'eid' => $this->entrepriseId]
        );

        if ($this->isAjax()) {
            $this->json(['success' => true]);
        } else {
            $_SESSION['flash_success'] = 'FAQ supprimée.';
            $this->redirect('/admin/ia');
        }
    }

    public function updateIaConfig(): void
    {
        if (!$this->isPost() || !$this->validateCsrf()) {
            $this->redirect('/admin/ia');
            return;
        }

        $iaConfig = [
            'contexte' => $this->sanitize($this->input('contexte')),
            'ton' => $this->sanitize($this->input('ton', 'professionnel')),
            'instructions' => $this->sanitize($this->input('instructions')),
            'auto_escalade' => $this->input('auto_escalade') ? true : false
        ];

        $this->entrepriseModel->update($this->entrepriseId, [
            'ia_config' => json_encode($iaConfig)
        ]);

        $_SESSION['flash_success'] = 'Configuration IA mise à jour.';
        $this->redirect('/admin/ia');
    }

    public function uploadDocument(): void
    {
        if (!$this->isPost() || !$this->validateCsrf()) {
            $this->redirect('/admin/ia');
            return;
        }

        if (!isset($_FILES['document']) || $_FILES['document']['error'] !== UPLOAD_ERR_OK) {
            $_SESSION['flash_error'] = 'Erreur lors du téléchargement du fichier.';
            $this->redirect('/admin/ia');
            return;
        }

        $file = $_FILES['document'];
        $allowedTypes = ['text/plain', 'application/pdf', 'text/markdown', 'text/csv'];
        $allowedExtensions = ['txt', 'pdf', 'md', 'csv'];
        
        $extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        
        if (!in_array($extension, $allowedExtensions)) {
            $_SESSION['flash_error'] = 'Type de fichier non autorisé. Formats acceptés: TXT, PDF, MD, CSV';
            $this->redirect('/admin/ia');
            return;
        }

        $maxSize = 5 * 1024 * 1024; // 5MB
        if ($file['size'] > $maxSize) {
            $_SESSION['flash_error'] = 'Le fichier est trop volumineux (max 5MB).';
            $this->redirect('/admin/ia');
            return;
        }

        // Créer le dossier de stockage
        $uploadDir = ROOT_PATH . '/storage/documents/' . $this->entrepriseId;
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }

        // Générer un nom unique
        $filename = uniqid() . '_' . preg_replace('/[^a-zA-Z0-9._-]/', '_', $file['name']);
        $filepath = $uploadDir . '/' . $filename;

        if (!move_uploaded_file($file['tmp_name'], $filepath)) {
            $_SESSION['flash_error'] = 'Erreur lors de l\'enregistrement du fichier.';
            $this->redirect('/admin/ia');
            return;
        }

        // Extraire le contenu du fichier
        $contenu = $this->extractDocumentContent($filepath, $extension);

        // Enregistrer en base
        $this->db->insert('ia_documents', [
            'entreprise_id' => $this->entrepriseId,
            'titre' => $this->sanitize($this->input('titre', pathinfo($file['name'], PATHINFO_FILENAME))),
            'description' => $this->sanitize($this->input('description')),
            'type_fichier' => $extension,
            'fichier_path' => 'storage/documents/' . $this->entrepriseId . '/' . $filename,
            'contenu_extrait' => $contenu,
            'taille_fichier' => $file['size'],
            'is_active' => 1,
            'created_at' => date('Y-m-d H:i:s')
        ]);

        $_SESSION['flash_success'] = 'Document ajouté à la base de connaissances IA.';
        $this->redirect('/admin/ia');
    }

    private function extractDocumentContent(string $filepath, string $extension): string
    {
        $content = '';
        
        switch ($extension) {
            case 'txt':
            case 'md':
            case 'csv':
                $content = file_get_contents($filepath);
                break;
            case 'pdf':
                // Pour le PDF, on extrait le texte basique
                // Une solution plus avancée nécessiterait une librairie comme TCPDF ou Smalot
                $content = $this->extractPdfText($filepath);
                break;
        }

        // Limiter la taille du contenu extrait (pour éviter surcharge)
        if (strlen($content) > 50000) {
            $content = substr($content, 0, 50000) . '... [contenu tronqué]';
        }

        return $content;
    }

    private function extractPdfText(string $filepath): string
    {
        // Extraction basique - cherche le texte brut dans le PDF
        $content = file_get_contents($filepath);
        
        // Extraction simple des objets texte PDF
        $text = '';
        if (preg_match_all('/\((.*?)\)/', $content, $matches)) {
            foreach ($matches[1] as $match) {
                // Filtrer les caractères non imprimables
                $clean = preg_replace('/[^\x20-\x7E\x{00C0}-\x{017F}]/u', ' ', $match);
                if (strlen(trim($clean)) > 2) {
                    $text .= $clean . ' ';
                }
            }
        }
        
        // Si pas de texte extrait, indiquer que le PDF nécessite OCR
        if (strlen(trim($text)) < 50) {
            return '[Document PDF - Contenu non extractible automatiquement. Veuillez ajouter une description détaillée.]';
        }

        return trim($text);
    }

    public function deleteDocument(string $id): void
    {
        if (!$this->isPost()) {
            $this->redirect('/admin/ia');
            return;
        }

        $doc = $this->db->fetch(
            "SELECT * FROM ia_documents WHERE id = :id AND entreprise_id = :eid",
            ['id' => $id, 'eid' => $this->entrepriseId]
        );

        if ($doc) {
            // Supprimer le fichier
            $filepath = ROOT_PATH . '/' . $doc['fichier_path'];
            if (file_exists($filepath)) {
                unlink($filepath);
            }

            // Supprimer de la base
            $this->db->query(
                "DELETE FROM ia_documents WHERE id = :id",
                ['id' => $id]
            );

            $_SESSION['flash_success'] = 'Document supprimé.';
        }

        if ($this->isAjax()) {
            $this->json(['success' => true]);
        } else {
            $this->redirect('/admin/ia');
        }
    }

    public function toggleDocument(string $id): void
    {
        if (!$this->isPost()) {
            $this->redirect('/admin/ia');
            return;
        }

        $doc = $this->db->fetch(
            "SELECT * FROM ia_documents WHERE id = :id AND entreprise_id = :eid",
            ['id' => $id, 'eid' => $this->entrepriseId]
        );

        if ($doc) {
            $this->db->query(
                "UPDATE ia_documents SET is_active = NOT is_active WHERE id = :id",
                ['id' => $id]
            );
        }

        $this->redirect('/admin/ia');
    }

    private function calculateCxIndex(array $stats): array
    {
        $total = $stats['total'] ?? 0;
        if ($total == 0) {
            return ['score' => 0, 'niveau' => 'N/A', 'details' => []];
        }

        $tauxResolution = ($stats['resolues'] ?? 0) / $total * 100;
        $tempsResolution = $stats['temps_resolution_moyen'] ?? 0;
        $satisfaction = $stats['satisfaction_moyenne'] ?? 0;
        $tauxEscalade = ($stats['escaladees'] ?? 0) / $total * 100;

        $scoreResolution = min(100, $tauxResolution);
        $scoreTemps = max(0, 100 - ($tempsResolution / 3600) * 10);
        $scoreSatisfaction = ($satisfaction / 5) * 100;
        $scoreEscalade = max(0, 100 - $tauxEscalade * 2);

        $score = ($scoreResolution * 0.3) + ($scoreTemps * 0.2) + ($scoreSatisfaction * 0.35) + ($scoreEscalade * 0.15);
        $score = round($score, 1);

        $niveau = 'Critique';
        if ($score >= 80) $niveau = 'Excellent';
        elseif ($score >= 60) $niveau = 'Bon';
        elseif ($score >= 40) $niveau = 'Moyen';
        elseif ($score >= 20) $niveau = 'Faible';

        return [
            'score' => $score,
            'niveau' => $niveau,
            'details' => [
                'resolution' => round($tauxResolution, 1),
                'temps_moyen' => round($tempsResolution / 60, 1),
                'satisfaction' => round($satisfaction, 2),
                'escalade' => round($tauxEscalade, 1)
            ]
        ];
    }
    
    // ==========================================
    // GESTION CONVERSATIONS - ASSIGNATION & STATUT
    // ==========================================
    
    /**
     * Assigner un agent à une conversation
     */
    public function assignerConversation(string $id): void
    {
        header('Content-Type: application/json');
        
        if (!$this->isPost()) {
            echo json_encode(['success' => false, 'error' => 'Méthode non autorisée']);
            return;
        }
        
        $data = json_decode(file_get_contents('php://input'), true);
        $agentId = (int)($data['agent_id'] ?? 0);
        
        if (!$agentId) {
            echo json_encode(['success' => false, 'error' => 'Agent non spécifié']);
            return;
        }
        
        // Vérifier que la conversation appartient à l'entreprise
        $conversation = $this->conversationModel->find((int)$id);
        if (!$conversation || $conversation['entreprise_id'] != $this->entrepriseId) {
            echo json_encode(['success' => false, 'error' => 'Conversation non trouvée']);
            return;
        }
        
        // Vérifier que l'agent appartient à l'entreprise
        $agent = $this->userModel->find($agentId);
        if (!$agent || $agent['entreprise_id'] != $this->entrepriseId) {
            echo json_encode(['success' => false, 'error' => 'Agent non autorisé']);
            return;
        }
        
        $success = $this->conversationModel->assignToAgent((int)$id, $agentId);
        
        echo json_encode([
            'success' => $success,
            'agent_nom' => $agent['nom'] . ' ' . ($agent['prenom'] ?? '')
        ]);
    }
    
    /**
     * Mettre à jour le statut d'une conversation
     */
    public function updateStatutConversation(string $id): void
    {
        header('Content-Type: application/json');
        
        if (!$this->isPost()) {
            echo json_encode(['success' => false, 'error' => 'Méthode non autorisée']);
            return;
        }
        
        $data = json_decode(file_get_contents('php://input'), true);
        $statut = $data['statut'] ?? '';
        
        $statutsValides = ['open', 'in_progress', 'resolved', 'closed'];
        if (!in_array($statut, $statutsValides)) {
            echo json_encode(['success' => false, 'error' => 'Statut invalide']);
            return;
        }
        
        // Vérifier que la conversation appartient à l'entreprise
        $conversation = $this->conversationModel->find((int)$id);
        if (!$conversation || $conversation['entreprise_id'] != $this->entrepriseId) {
            echo json_encode(['success' => false, 'error' => 'Conversation non trouvée']);
            return;
        }
        
        $updateData = ['statut' => $statut];
        
        // Si résolu ou fermé, ajouter la date de fermeture
        if (in_array($statut, ['resolved', 'closed'])) {
            $updateData['closed_at'] = date('Y-m-d H:i:s');
        }
        
        $success = $this->conversationModel->update((int)$id, $updateData) > 0;
        
        echo json_encode(['success' => $success]);
    }
    
    /**
     * Page QR Codes et Liens directs
     */
    public function qrcodes(): void
    {
        require_once APP_PATH . '/Services/QRCodeService.php';
        
        $entreprise = $this->entrepriseModel->find($this->entrepriseId);
        $qrService = new \App\Services\QRCodeService();
        
        $links = $qrService->generateAllLinks($entreprise);
        
        $user = $this->userModel->find($_SESSION['user_id']);
        
        $this->view('admin/qrcodes', [
            'entreprise' => $entreprise,
            'links' => $links,
            'user' => $user,
            'pageTitle' => 'QR Codes & Liens'
        ]);
    }
}
