{% extends "base_config.html" %}
{% block content %}
<div class="page">
    <div class="section">
        <h2 class="section-title">
            <img class="card-icon" src="/static/assets/icons/chat.svg" alt="Chat">
            <span class="card-title-text">Chat</span>
        </h2>
        <form id="config-form">
            <table>
                <tr>
                    <td>
                        <label for="openai-api-key" title="Get your OpenAI key from https://platform.openai.com/account/api-keys">OpenAI API key</label>
                    </td>
                    <td>
                        <input type="text" id="openai-api-key" name="openai-api-key" value="{{ current_config['api_key'] }}">
                    </td>
                </tr>
                <tr>
                    <td>
                        <label for="chat-model">Chat Model</label>
                    </td>
                    <td>
                        <input type="text" id="chat-model" name="chat-model" value="{{ current_config['chat_model'] }}">
                    </td>
                </tr>
            </table>
            <div class="section">
                <div id="success" style="display: none;" ></div>
                <button id="submit" type="submit">Save</button>
            </div>
        </form>
    </div>
</div>
<script>
    submit.addEventListener("click", function(event) {
        event.preventDefault();
        var openai_api_key = document.getElementById("openai-api-key").value;
        var chat_model = document.getElementById("chat-model").value;

        if (openai_api_key == "" || chat_model == "") {
            document.getElementById("success").innerHTML = "⚠️ Please fill all the fields.";
            document.getElementById("success").style.display = "block";
            return;
        }

        const csrfToken = document.cookie.split('; ').find(row => row.startsWith('csrftoken'))?.split('=')[1];
        fetch('/api/config/data/processor/conversation/openai', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': csrfToken
            },
            body: JSON.stringify({
                "api_key": openai_api_key,
                "chat_model": chat_model
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data["status"] == "ok") {
                document.getElementById("success").innerHTML = "✅ Successfully updated. Go to your <a href='/config'>settings page</a> to complete setup.";
                document.getElementById("success").style.display = "block";
            } else {
                document.getElementById("success").innerHTML = "⚠️ Failed to update settings.";
                document.getElementById("success").style.display = "block";
            }
        })
    });
</script>
{% endblock %}
