// ===== FUNÇÕES DE GERENCIAMENTO DE CONTATOS ===== function abrirModalContato(contato = null) { const modal = new bootstrap.Modal(document.getElementById('modalContato')); const form = document.getElementById('formContato'); const title = document.getElementById('modalContatoTitle'); // Limpar formulário form.reset(); if (contato) { // Editar contato existente title.textContent = 'Editar Contato'; document.getElementById('contatoId').value = contato.id; document.getElementById('contatoNome').value = contato.nome; document.getElementById('contatoTelefone').value = contato.telefone; document.getElementById('contatoTipo').value = contato.tipo; document.getElementById('contatoAtivo').checked = contato.ativo === 1; } else { // Novo contato title.textContent = 'Adicionar Contato'; document.getElementById('contatoId').value = ''; document.getElementById('contatoAtivo').checked = true; } modal.show(); } async function salvarContato() { try { const form = document.getElementById('formContato'); const formData = new FormData(form); const contato = { nome: formData.get('nome'), telefone: formData.get('telefone').replace(/\D/g, ''), // Remove não-dígitos tipo: formData.get('tipo'), ativo: formData.get('ativo') === 'on' }; // Validações if (!contato.nome || !contato.telefone || !contato.tipo) { showToast('Preencha todos os campos obrigatórios', 'error'); return; } if (contato.telefone.length < 10 || contato.telefone.length > 11) { showToast('Telefone deve ter 10 ou 11 dígitos', 'error'); return; } const id = formData.get('id'); const isEdit = id && id !== ''; const url = isEdit ? `${API_BASE}/whatsapp/contatos/${id}` : `${API_BASE}/whatsapp/contatos`; const method = isEdit ? 'PUT' : 'POST'; const response = await fetch(url, { method: method, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(contato) }); const data = await response.json(); if (data.status === 'success') { showToast(data.message, 'success'); // Fechar modal const modal = bootstrap.Modal.getInstance(document.getElementById('modalContato')); modal.hide(); // Recarregar lista de contatos await listarContatos(); } else { showToast(data.message, 'error'); } } catch (error) { console.error('Erro ao salvar contato:', error); showToast('Erro ao salvar contato', 'error'); } } async function excluirContato(id, nome) { if (!confirm(`Tem certeza que deseja excluir o contato "${nome}"?\n\nEsta ação não pode ser desfeita.`)) { return; } try { const response = await fetch(`${API_BASE}/whatsapp/contatos/${id}`, { method: 'DELETE' }); const data = await response.json(); if (data.status === 'success') { showToast(data.message, 'success'); await listarContatos(); } else { showToast(data.message, 'error'); } } catch (error) { console.error('Erro ao excluir contato:', error); showToast('Erro ao excluir contato', 'error'); } } async function alternarStatusContato(id, ativo) { try { // Buscar dados atuais do contato const response = await fetch(`${API_BASE}/whatsapp/contatos`); const data = await response.json(); if (data.status !== 'success') { showToast('Erro ao buscar dados do contato', 'error'); return; } const contato = data.contatos.find(c => c.id === id); if (!contato) { showToast('Contato não encontrado', 'error'); return; } // Atualizar apenas o status const updateResponse = await fetch(`${API_BASE}/whatsapp/contatos/${id}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ nome: contato.nome, telefone: contato.telefone, tipo: contato.tipo, ativo: !ativo }) }); const updateData = await updateResponse.json(); if (updateData.status === 'success') { showToast(`Contato ${!ativo ? 'ativado' : 'desativado'} com sucesso`, 'success'); await listarContatos(); } else { showToast(updateData.message, 'error'); } } catch (error) { console.error('Erro ao alterar status do contato:', error); showToast('Erro ao alterar status do contato', 'error'); } } function showToast(message, type = 'info') { // Criar toast se não existir let toastContainer = document.getElementById('toast-container'); if (!toastContainer) { toastContainer = document.createElement('div'); toastContainer.id = 'toast-container'; toastContainer.className = 'position-fixed top-0 end-0 p-3'; toastContainer.style.zIndex = '9999'; document.body.appendChild(toastContainer); } const toastId = 'toast-' + Date.now(); const bgClass = type === 'success' ? 'bg-success' : type === 'error' ? 'bg-danger' : 'bg-info'; const toastHtml = `