<?php ob_start(); ?>

<div class="space-y-6">
    <!-- Header -->
    <div class="flex items-center justify-between">
        <div class="flex items-center gap-4">
            <a href="<?= BASE_URL ?>/admin/conversations" class="w-10 h-10 bg-white rounded-lg flex items-center justify-center shadow-sm hover:bg-gray-50">
                <i class="fas fa-arrow-left text-gray-600"></i>
            </a>
            <div>
                <h1 class="text-xl font-bold text-gray-900">Conversation #<?= $conversation['id'] ?></h1>
                <p class="text-sm text-gray-500">
                    <?= $client ? htmlspecialchars($client['nom'] ?? 'Client') : 'Visiteur' ?>
                    • <?= date('d/m/Y H:i', strtotime($conversation['created_at'])) ?>
                </p>
            </div>
        </div>
        <div class="flex items-center gap-2">
            <span class="px-3 py-1 rounded-full text-sm font-medium <?php
                echo match($conversation['statut']) {
                    'open' => 'bg-green-100 text-green-700',
                    'in_progress' => 'bg-blue-100 text-blue-700',
                    'resolved' => 'bg-purple-100 text-purple-700',
                    'closed' => 'bg-gray-100 text-gray-700',
                    default => 'bg-gray-100 text-gray-700'
                };
            ?>">
                <?= ucfirst(str_replace('_', ' ', $conversation['statut'])) ?>
            </span>
        </div>
    </div>

    <div class="grid md:grid-cols-3 gap-6">
        <!-- Messages -->
        <div class="md:col-span-2">
            <div class="bg-white rounded-xl shadow-sm">
                <div class="p-4 border-b">
                    <h3 class="font-semibold text-gray-900">Messages</h3>
                </div>
                <div class="p-4 space-y-4 max-h-[600px] overflow-y-auto" id="messages-container">
                    <?php if (empty($conversation['messages'])): ?>
                        <p class="text-center text-gray-500 py-8">Aucun message dans cette conversation</p>
                    <?php else: ?>
                        <?php foreach ($conversation['messages'] as $msg): ?>
                            <?php 
                            $isClient = $msg['sender_type'] === 'client';
                            $isBot = $msg['sender_type'] === 'bot';
                            ?>
                            <div class="flex <?= $isClient ? 'justify-start' : 'justify-end' ?>">
                                <div class="max-w-[80%] <?= $isClient ? 'order-2' : 'order-1' ?>">
                                    <div class="<?php
                                        if ($isClient) {
                                            echo 'bg-gray-100 text-gray-800 rounded-2xl rounded-bl-md';
                                        } elseif ($isBot) {
                                            echo 'bg-gradient-to-r from-cyan-500 to-emerald-500 text-white rounded-2xl rounded-br-md';
                                        } else {
                                            echo 'bg-blue-500 text-white rounded-2xl rounded-br-md';
                                        }
                                    ?> px-4 py-3">
                                        <p class="text-sm whitespace-pre-wrap"><?= htmlspecialchars($msg['contenu'] ?? '') ?></p>
                                    </div>
                                    <div class="flex items-center gap-2 mt-1 <?= $isClient ? '' : 'justify-end' ?>">
                                        <span class="text-xs text-gray-400">
                                            <?php if ($isBot): ?>
                                                <i class="fas fa-robot mr-1"></i>IA
                                            <?php elseif (!$isClient): ?>
                                                <i class="fas fa-user-tie mr-1"></i><?= htmlspecialchars($msg['agent_nom'] ?? 'Agent') ?>
                                            <?php endif; ?>
                                        </span>
                                        <span class="text-xs text-gray-400">
                                            <?= date('H:i', strtotime($msg['created_at'])) ?>
                                        </span>
                                    </div>
                                </div>
                                <?php if ($isClient): ?>
                                <div class="w-8 h-8 rounded-full bg-gray-300 flex items-center justify-center mr-2 order-1 flex-shrink-0">
                                    <i class="fas fa-user text-gray-500 text-xs"></i>
                                </div>
                                <?php endif; ?>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Infos -->
        <div class="space-y-6">
            <!-- Client -->
            <div class="bg-white rounded-xl p-6 shadow-sm">
                <h3 class="font-semibold text-gray-900 mb-4">Client</h3>
                <?php if ($client): ?>
                <div class="space-y-3 text-sm">
                    <div class="flex justify-between">
                        <span class="text-gray-500">Nom</span>
                        <span class="font-medium"><?= htmlspecialchars($client['nom'] ?? '-') ?></span>
                    </div>
                    <div class="flex justify-between">
                        <span class="text-gray-500">Téléphone</span>
                        <span class="font-medium"><?= htmlspecialchars($client['telephone'] ?? '-') ?></span>
                    </div>
                    <div class="flex justify-between">
                        <span class="text-gray-500">Email</span>
                        <span class="font-medium"><?= htmlspecialchars($client['email'] ?? '-') ?></span>
                    </div>
                </div>
                <?php else: ?>
                <p class="text-gray-500 text-sm">Visiteur anonyme</p>
                <?php endif; ?>
            </div>

            <!-- Détails -->
            <div class="bg-white rounded-xl p-6 shadow-sm">
                <h3 class="font-semibold text-gray-900 mb-4">Détails</h3>
                <div class="space-y-3 text-sm">
                    <div class="flex justify-between">
                        <span class="text-gray-500">Canal</span>
                        <span class="font-medium capitalize"><?= $conversation['canal'] ?? 'widget' ?></span>
                    </div>
                    <div class="flex justify-between">
                        <span class="text-gray-500">Messages</span>
                        <span class="font-medium"><?= count($conversation['messages'] ?? []) ?></span>
                    </div>
                    <div class="flex justify-between">
                        <span class="text-gray-500">Agent</span>
                        <span class="font-medium" id="agent-actuel"><?= $conversation['agent_nom'] ?? 'Non assigné' ?></span>
                    </div>
                    <?php if ($conversation['closed_at']): ?>
                    <div class="flex justify-between">
                        <span class="text-gray-500">Fermée le</span>
                        <span class="font-medium"><?= date('d/m/Y H:i', strtotime($conversation['closed_at'])) ?></span>
                    </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Assignation Agent -->
            <div class="bg-white rounded-xl p-6 shadow-sm">
                <h3 class="font-semibold text-gray-900 mb-4">
                    <i class="fas fa-user-plus mr-2 text-purple-500"></i>Assigner un agent
                </h3>
                <select id="select-agent" class="w-full px-3 py-2 border rounded-lg text-sm mb-3">
                    <option value="">-- Sélectionner un agent --</option>
                    <?php if (!empty($agents)): ?>
                        <?php foreach ($agents as $agent): ?>
                        <option value="<?= $agent['id'] ?>" <?= ($conversation['agent_id'] ?? 0) == $agent['id'] ? 'selected' : '' ?>>
                            <?= htmlspecialchars($agent['nom'] . ' ' . ($agent['prenom'] ?? '')) ?>
                            <?= $agent['is_online'] ? '🟢' : '⚪' ?>
                        </option>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </select>
                <button onclick="assignerAgent()" class="w-full px-4 py-2 bg-purple-500 text-white rounded-lg hover:bg-purple-600 text-sm">
                    <i class="fas fa-check mr-1"></i> Assigner
                </button>
            </div>

            <!-- Actions rapides -->
            <?php if (!in_array($conversation['statut'], ['closed', 'resolved'])): ?>
            <div class="bg-white rounded-xl p-6 shadow-sm">
                <h3 class="font-semibold text-gray-900 mb-4">
                    <i class="fas fa-bolt mr-2 text-yellow-500"></i>Actions
                </h3>
                <div class="space-y-2">
                    <?php if ($conversation['statut'] === 'open'): ?>
                    <button onclick="updateStatut('in_progress')" class="w-full px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 text-sm">
                        <i class="fas fa-play mr-1"></i> Prendre en charge
                    </button>
                    <?php endif; ?>
                    <button onclick="updateStatut('resolved')" class="w-full px-4 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600 text-sm">
                        <i class="fas fa-check-circle mr-1"></i> Marquer résolu
                    </button>
                    <button onclick="updateStatut('closed')" class="w-full px-4 py-2 bg-gray-500 text-white rounded-lg hover:bg-gray-600 text-sm">
                        <i class="fas fa-times-circle mr-1"></i> Fermer
                    </button>
                </div>
            </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
var conversationId = <?= $conversation['id'] ?>;

function showToast(message, type) {
    var toast = document.createElement('div');
    toast.textContent = message;
    var bg = type === 'error' ? '#ef4444' : '#10b981';
    toast.style.cssText = 'position:fixed;bottom:20px;left:50%;transform:translateX(-50%);background:' + bg + ';color:white;padding:12px 24px;border-radius:8px;z-index:9999';
    document.body.appendChild(toast);
    setTimeout(function() { toast.remove(); }, 2000);
}

function assignerAgent() {
    var agentId = document.getElementById('select-agent').value;
    if (!agentId) {
        showToast('Sélectionnez un agent', 'error');
        return;
    }
    
    fetch('<?= BASE_URL ?>/admin/conversations/' + conversationId + '/assigner', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({ agent_id: agentId })
    })
    .then(function(res) { return res.json(); })
    .then(function(data) {
        if (data.success) {
            showToast('Agent assigné avec succès');
            var select = document.getElementById('select-agent');
            var agentNom = select.options[select.selectedIndex].text.replace(/🟢|⚪/g, '').trim();
            document.getElementById('agent-actuel').textContent = agentNom;
        } else {
            showToast(data.error || 'Erreur', 'error');
        }
    });
}

function updateStatut(statut) {
    fetch('<?= BASE_URL ?>/admin/conversations/' + conversationId + '/statut', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({ statut: statut })
    })
    .then(function(res) { return res.json(); })
    .then(function(data) {
        if (data.success) {
            showToast('Statut mis à jour');
            setTimeout(function() { location.reload(); }, 1000);
        } else {
            showToast(data.error || 'Erreur', 'error');
        }
    });
}
</script>

<?php 
$content = ob_get_clean();
$title = 'Conversation #' . $conversation['id'] . ' - ' . APP_NAME;
$pageTitle = 'Conversation #' . $conversation['id'];
include VIEWS_PATH . '/layouts/main.php';
?>
