<?php
require_once BASE_PATH . '/app/ai_settings.php';

if (!ai_client_must_provide_key()) {
    return;
}

$existingKey = ai_get_client_key($_SESSION['user']['id'] ?? '');
$hasKey = !empty($existingKey);

function _mc_mask(string $key): string {
    $len = strlen($key);
    if ($len <= 12) return str_repeat('•', $len);
    return substr($key, 0, 7) . '••••••' . substr($key, -4);
}

$keyMasked = $hasKey ? _mc_mask($existingKey) : '';
?>

<div class="mc-openai-card">
    <div class="mc-openai-head">
        <div class="mc-openai-icon">🤖</div>
        <div class="mc-openai-head-text">
            <h3>Chave OpenAI</h3>
            <p>Necessária para o Agente de Atendimento funcionar na sua conta.</p>
        </div>
        <span class="mc-openai-status <?= $hasKey ? 'is-ok' : 'is-warn' ?>">
            <?= $hasKey ? '✓ Configurada' : '⚠ Não configurada' ?>
        </span>
    </div>

    <?php if ($hasKey): ?>
        <div class="mc-openai-current">
            <span class="mc-openai-label">Chave atual:</span>
            <code><?= htmlspecialchars($keyMasked) ?></code>
            <div class="mc-openai-current-actions">
                <button type="button" class="mc-openai-btn-ghost" id="btn-openai-change">Trocar chave</button>
                <button type="button" class="mc-openai-btn-danger" id="btn-openai-delete">Remover</button>
            </div>
        </div>
    <?php endif; ?>

    <div id="openai-form" style="<?= $hasKey ? 'display:none;' : '' ?>">
        <div class="mc-openai-field">
            <label>Sua API Key da OpenAI</label>
            <input type="password" id="openai-key-input" placeholder="sk-proj-..." autocomplete="off">
            <small>Cole aqui sua chave (começa com <code>sk-</code>). Ela será testada antes de ser salva.</small>
        </div>

        <div class="mc-openai-actions">
            <button type="button" class="mc-openai-btn-secondary" id="btn-openai-test">Testar chave</button>
            <button type="button" class="mc-openai-btn-primary" id="btn-openai-save">Salvar</button>
            <span id="openai-msg"></span>
        </div>

        <div class="mc-openai-help">
            <strong>Como obter sua chave:</strong>
            <ol>
                <li>Acesse <a href="https://platform.openai.com/api-keys" target="_blank" rel="noopener">platform.openai.com/api-keys</a></li>
                <li>Clique em <strong>"+ Create new secret key"</strong></li>
                <li>Dê um nome (ex: "Evolua Prospect") e clique em Create</li>
                <li>Copie a chave e cole aqui</li>
            </ol>
            <p class="mc-openai-warn">
                ⚠ Mantenha sua chave segura. Quem tiver acesso pode gerar gastos na sua conta OpenAI.
            </p>
        </div>
    </div>
</div>

<style>
.mc-openai-card {
    background: #ffffff;
    border: 1px solid #e5e7eb;
    border-radius: 14px;
    padding: 20px;
    margin: 20px 0;
    box-sizing: border-box;
    max-width: 100%;
    overflow: hidden;
}
.mc-openai-head {
    display: flex;
    align-items: center;
    gap: 14px;
    margin-bottom: 16px;
    flex-wrap: wrap;
}
.mc-openai-icon { font-size: 32px; flex-shrink: 0; }
.mc-openai-head-text { flex: 1; min-width: 0; }
.mc-openai-head h3 { margin: 0 0 4px; font-size: 16px; color: #0f172a; font-weight: 700; }
.mc-openai-head p { margin: 0; font-size: 13px; color: #64748b; }
.mc-openai-status {
    margin-left: auto;
    padding: 4px 10px;
    border-radius: 999px;
    font-size: 11px;
    font-weight: 700;
    flex-shrink: 0;
    white-space: nowrap;
}
.mc-openai-status.is-ok { background: #d1fae5; color: #047857; border: 1px solid #6ee7b7; }
.mc-openai-status.is-warn { background: #fef3c7; color: #b45309; border: 1px solid #fcd34d; }

.mc-openai-current {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 12px;
    background: #f8fafc;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    margin-bottom: 12px;
    flex-wrap: wrap;
}
.mc-openai-label { color: #64748b; font-size: 13px; flex-shrink: 0; }
.mc-openai-current code {
    background: #ede9fe;
    color: #6d28d9;
    padding: 4px 10px;
    border-radius: 6px;
    font-size: 12px;
    font-family: ui-monospace, monospace;
    max-width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    min-width: 0;
}
.mc-openai-current-actions {
    display: flex;
    gap: 6px;
    margin-left: auto;
    flex-shrink: 0;
}

.mc-openai-field { margin-bottom: 14px; }
.mc-openai-field label {
    display: block;
    margin-bottom: 6px;
    color: #334155;
    font-size: 13px;
    font-weight: 600;
}
.mc-openai-field input {
    width: 100%;
    padding: 10px 14px;
    background: #ffffff;
    color: #0f172a;
    border: 1px solid #cbd5e1;
    border-radius: 10px;
    font-size: 13px;
    font-family: ui-monospace, monospace;
    box-sizing: border-box;
}
.mc-openai-field input:focus {
    outline: none;
    border-color: #7c3aed;
    box-shadow: 0 0 0 3px rgba(124,58,237,.15);
}
.mc-openai-field small {
    color: #64748b;
    font-size: 11.5px;
    display: block;
    margin-top: 5px;
}
.mc-openai-field small code {
    background: #ede9fe;
    color: #6d28d9;
    padding: 1px 6px;
    border-radius: 4px;
    font-size: 11px;
}
.mc-openai-actions {
    display: flex;
    gap: 10px;
    align-items: center;
    margin-bottom: 14px;
    flex-wrap: wrap;
}
.mc-openai-btn-primary,
.mc-openai-btn-secondary,
.mc-openai-btn-ghost,
.mc-openai-btn-danger {
    border: 0;
    padding: 8px 16px;
    border-radius: 8px;
    font-size: 13px;
    font-weight: 600;
    cursor: pointer;
    transition: all .2s;
    font-family: inherit;
    white-space: nowrap;
}
.mc-openai-btn-primary {
    background: linear-gradient(90deg, #6ee7ff, #7c3aed);
    color: #0b1020;
    box-shadow: 0 4px 12px rgba(124,58,237,.25);
}
.mc-openai-btn-primary:hover {
    transform: translateY(-1px);
    box-shadow: 0 6px 16px rgba(124,58,237,.35);
}
.mc-openai-btn-secondary { background: #f1f5f9; color: #334155; border: 1px solid #cbd5e1; }
.mc-openai-btn-secondary:hover { background: #e2e8f0; }
.mc-openai-btn-ghost {
    background: transparent;
    color: #6d28d9;
    padding: 6px 12px;
    font-size: 12px;
    border: 1px solid transparent;
}
.mc-openai-btn-ghost:hover { background: #ede9fe; border-color: #c4b5fd; }
.mc-openai-btn-danger {
    background: #fef2f2;
    color: #b91c1c;
    padding: 6px 12px;
    font-size: 12px;
    border: 1px solid #fecaca;
}
.mc-openai-btn-danger:hover { background: #fee2e2; }

.mc-openai-help {
    background: #f8fafc;
    border: 1px solid #e2e8f0;
    border-radius: 10px;
    padding: 14px 16px;
    margin-top: 8px;
    font-size: 13px;
    color: #475569;
    line-height: 1.55;
}
.mc-openai-help strong { color: #0f172a; display: block; margin-bottom: 8px; }
.mc-openai-help ol { margin: 0 0 8px; padding-left: 22px; color: #475569; }
.mc-openai-help li { margin-bottom: 5px; }
.mc-openai-help a {
    color: #6d28d9;
    font-weight: 600;
    text-decoration: underline;
    word-break: break-all;
}
.mc-openai-help a:hover { color: #5b21b6; }
.mc-openai-warn {
    color: #b45309;
    background: #fef3c7;
    border: 1px solid #fcd34d;
    border-radius: 8px;
    padding: 8px 12px;
    font-size: 12px;
    margin: 10px 0 0;
    font-weight: 500;
}
#openai-msg { font-size: 12px; flex: 1; min-width: 150px; word-break: break-word; }
#openai-msg.ok  { color: #047857; font-weight: 600; }
#openai-msg.err { color: #b91c1c; font-weight: 600; }

.dark .mc-openai-card { background: #0b0f1a; border-color: #1f2937; }
.dark .mc-openai-head h3 { color: #f1f5f9; }
.dark .mc-openai-head p { color: #94a3b8; }
.dark .mc-openai-current { background: #1e293b; border-color: #334155; }
.dark .mc-openai-current code { background: rgba(124,58,237,.2); color: #c4b5fd; }
.dark .mc-openai-field label { color: #cbd5e1; }
.dark .mc-openai-field input { background: #0f172a; color: #e5e7eb; border-color: #334155; }
.dark .mc-openai-field small { color: #94a3b8; }
.dark .mc-openai-help { background: #0f172a; border-color: #1e293b; color: #cbd5e1; }
.dark .mc-openai-help strong { color: #f1f5f9; }
.dark .mc-openai-help a { color: #a78bfa; }
.dark .mc-openai-btn-secondary { background: #1e293b; color: #e5e7eb; border-color: #334155; }
</style>

<script>
(function() {
    const CSRF = '<?= htmlspecialchars(csrf_token(), ENT_QUOTES) ?>';
    const BASE = '<?= htmlspecialchars(BASE_URL, ENT_QUOTES) ?>';

    const $ = (s) => document.querySelector(s);

    const form = $('#openai-form');
    const input = $('#openai-key-input');
    const msg = $('#openai-msg');
    const btnTest = $('#btn-openai-test');
    const btnSave = $('#btn-openai-save');
    const btnChange = $('#btn-openai-change');
    const btnDelete = $('#btn-openai-delete');

    function setMsg(type, text) {
        if (!msg) return;
        msg.textContent = text || '';
        msg.className = type || '';
    }

    async function api(action, payload = {}) {
        const r = await fetch(BASE + 'api/openai_key.php?action=' + action, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ ...payload, csrf_token: CSRF }),
        });
        const data = await r.json();
        if (!r.ok || !data.ok) throw new Error(data.error || 'Erro');
        return data;
    }

    btnTest?.addEventListener('click', async () => {
        const key = (input.value || '').trim();
        if (!key) return setMsg('err', 'Cole a chave antes');

        btnTest.disabled = true;
        btnTest.textContent = 'Testando...';
        setMsg('', '');

        try {
            await api('test', { api_key: key });
            setMsg('ok', '✓ Chave válida!');
        } catch (e) {
            setMsg('err', '✗ ' + e.message);
        } finally {
            btnTest.disabled = false;
            btnTest.textContent = 'Testar chave';
        }
    });

    btnSave?.addEventListener('click', async () => {
        const key = (input.value || '').trim();
        if (!key) return setMsg('err', 'Cole a chave antes');

        btnSave.disabled = true;
        btnSave.textContent = 'Salvando...';
        setMsg('', 'Validando com OpenAI...');

        try {
            await api('save', { api_key: key });
            setMsg('ok', '✓ Salva! Recarregando...');
            setTimeout(() => location.reload(), 1000);
        } catch (e) {
            setMsg('err', e.message);
            btnSave.disabled = false;
            btnSave.textContent = 'Salvar';
        }
    });

    btnChange?.addEventListener('click', () => {
        if (form) form.style.display = 'block';
        input?.focus();
    });

    btnDelete?.addEventListener('click', async () => {
        if (!confirm('Remover sua chave OpenAI? O Agente de Atendimento será desativado até você cadastrar uma nova.')) return;

        try {
            await api('delete');
            location.reload();
        } catch (e) {
            alert('Erro: ' + e.message);
        }
    });
})();
</script>