<?php
require_once 'config/config.php';
require_once 'config/db.php';

// Basic auth protection for admin/ui can be added if needed

$page_title = 'Chatbot - Aide client';
?>
<!doctype html>
<html lang="fr">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title><?php echo $page_title; ?></title>
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <style>
        body { padding: 20px; }
        #chat { max-width: 900px; margin: 0 auto; }
        .msg { padding: 8px 12px; border-radius: 8px; margin-bottom: 8px; }
        .msg.user { background: #e7f1ff; text-align: right; }
        .msg.bot { background: #f3f3f3; }
        #messages { height: 60vh; overflow:auto; padding:10px; border:1px solid #ddd; border-radius:6px; }
    </style>
</head>
<body>
<div id="chat">
    <h3>Assistant client (local)</h3>
    <p class="text-muted">Posez une question sur le site, les services, ou les témoignages. Réponses basées sur les pages et la base de données locale.</p>

    <div id="messages" aria-live="polite"></div>

    <form id="chatForm" onsubmit="return false;">
        <div class="input-group mt-2">
            <input id="q" class="form-control" placeholder="Votre question...">
            <button id="send" class="btn btn-primary">Envoyer</button>
        </div>
    </form>
</div>

<script>
async function appendMessage(who, text) {
    const div = document.createElement('div');
    div.className = 'msg ' + (who === 'user' ? 'user' : 'bot');
    div.innerText = text;
    document.getElementById('messages').appendChild(div);
    document.getElementById('messages').scrollTop = document.getElementById('messages').scrollHeight;
}

document.getElementById('send').addEventListener('click', async () => {
    const q = document.getElementById('q').value.trim();
    if (!q) return;
    appendMessage('user', q);
    document.getElementById('q').value = '';

    appendMessage('bot', 'Recherche en cours...');

    try {
        const res = await fetch('chatbot_api.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ question: q })
        });
        const json = await res.json();
        // remove the 'Recherche en cours...' last bot message
        const msgs = document.querySelectorAll('#messages .msg.bot');
        if (msgs.length) msgs[msgs.length -1].remove();

        if (json.error) {
            appendMessage('bot', 'Erreur: ' + json.error);
            return;
        }

        // Afficher uniquement la réponse humaine
        appendMessage('bot', json.answer);
    } catch (err) {
        appendMessage('bot', 'Erreur réseau: ' + err.message);
    }
});
</script>
</body>
</html>