<?php $title = 'Admin: Landing Page'; ?>

<div class="card" style="width:98%;margin:0 auto;">
    <h1>Gestão da Landing Page</h1>
    
    <div class="alert alert-error" id="error" style="display:none;"></div>
    <div class="alert alert-success" id="success" style="display:none;"></div>
    
    <div id="tabs" style="display:flex;gap:0.5rem;border-bottom:1px solid #e5e7eb;margin-bottom:0.75rem;">
        <button class="tab-btn active" data-tab="config">Configurações</button>
        <button class="tab-btn" data-tab="plans">Planos</button>
        <button class="tab-btn" data-tab="contacts">Contatos</button>
    </div>
    
    <style>
        .tab-btn { background:#fff;border:1px solid #e5e7eb;border-bottom:none;padding:0.5rem 0.75rem;border-radius:6px 6px 0 0;cursor:pointer; }
        .tab-btn.active { background:#f9fafb; font-weight:600; }
        .tab-panel { display:none; }
        .tab-panel.active { display:block; }
        .form-group { margin-bottom:1rem; }
        .form-group label { display:block; margin-bottom:0.25rem; font-weight:600; }
        .form-group input, .form-group textarea, .form-group select { width:100%; padding:0.5rem; border:1px solid #e5e7eb; border-radius:4px; }
    </style>
    
    <!-- Configurações -->
    <div id="panel-config" class="tab-panel active">
        <h2>Configurações Gerais</h2>
        <div id="config-form"></div>
        <button class="btn" onclick="saveConfig()">Salvar Configurações</button>
    </div>
    
    <!-- Planos -->
    <div id="panel-plans" class="tab-panel">
        <h2>Planos da Landing Page</h2>
        <div style="margin-bottom:1rem;">
            <button class="btn" onclick="showPlanForm()">Adicionar Plano</button>
        </div>
        <div id="plans-list"></div>
    </div>
    
    <!-- Contatos -->
    <div id="panel-contacts" class="tab-panel">
        <h2>Contatos e Redes Sociais</h2>
        <div style="margin-bottom:1rem;">
            <button class="btn" onclick="showContactForm()">Adicionar Contato</button>
        </div>
        <div id="contacts-list"></div>
    </div>
</div>

<script>
let configData = {};
let plansData = [];
let contactsData = [];
let authToken = localStorage.getItem('admin_token') || '';

// Tabs
document.querySelectorAll('.tab-btn').forEach(btn => {
    btn.addEventListener('click', () => {
        document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
        document.querySelectorAll('.tab-panel').forEach(p => p.classList.remove('active'));
        btn.classList.add('active');
        document.getElementById('panel-' + btn.dataset.tab).classList.add('active');
        if (btn.dataset.tab === 'config') loadConfig();
        else if (btn.dataset.tab === 'plans') loadPlans();
        else if (btn.dataset.tab === 'contacts') loadContacts();
    });
});

// Carregar configurações
async function loadConfig() {
    try {
        const res = await fetch('/api/admin/landing-page/config', {
            headers: { 'Authorization': 'Bearer ' + authToken }
        });
        const data = await res.json();
        configData = data.data || {};
        renderConfigForm();
    } catch (e) {
        showError('Erro ao carregar configurações: ' + e.message);
    }
}

function renderConfigForm() {
    const form = document.getElementById('config-form');
    const categories = ['hero', 'modulos', 'planos', 'contato', 'rodape', 'empresa', 'trial'];
    let html = '';
    
    categories.forEach(cat => {
        if (configData[cat]) {
            html += `<h3 style="margin-top:1.5rem; margin-bottom:1rem; text-transform:capitalize;">${cat}</h3>`;
            Object.keys(configData[cat]).forEach(key => {
                const item = configData[cat][key];
                html += `
                    <div class="form-group">
                        <label>${key.replace(/_/g, ' ').toUpperCase()}</label>
                        ${item.tipo === 'text' || item.tipo === 'html' ? 
                            `<textarea name="${cat}.${key}" rows="3">${item.valor || ''}</textarea>` :
                            `<input type="${item.tipo}" name="${cat}.${key}" value="${item.valor || ''}">`
                        }
                    </div>
                `;
            });
        }
    });
    
    form.innerHTML = html;
}

async function saveConfig() {
    const formData = {};
    document.querySelectorAll('#config-form input, #config-form textarea').forEach(input => {
        const [cat, key] = input.name.split('.');
        if (!formData[cat]) formData[cat] = {};
        formData[cat][key] = input.value;
    });
    
    try {
        const res = await fetch('/api/admin/landing-page/config', {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer ' + authToken
            },
            body: JSON.stringify(formData)
        });
        
        if (res.ok) {
            showSuccess('Configurações salvas com sucesso!');
        } else {
            showError('Erro ao salvar configurações');
        }
    } catch (e) {
        showError('Erro: ' + e.message);
    }
}

// Carregar planos
async function loadPlans() {
    try {
        const res = await fetch('/api/admin/landing-page/plans', {
            headers: { 'Authorization': 'Bearer ' + authToken }
        });
        const data = await res.json();
        plansData = data.data || [];
        renderPlans();
    } catch (e) {
        showError('Erro ao carregar planos: ' + e.message);
    }
}

function renderPlans() {
    const list = document.getElementById('plans-list');
    list.innerHTML = '<table class="table"><thead><tr><th>Nome</th><th>Preço</th><th>Ciclo</th><th>Destaque</th><th>Ações</th></tr></thead><tbody>' +
        plansData.map(plan => `
            <tr>
                <td>${plan.nome}</td>
                <td>R$ ${plan.preco}</td>
                <td>${plan.ciclo}</td>
                <td>${plan.destaque ? 'Sim' : 'Não'}</td>
                <td>
                    <button onclick="editPlan(${plan.id})">Editar</button>
                    <button onclick="deletePlan(${plan.id})">Excluir</button>
                </td>
            </tr>
        `).join('') + '</tbody></table>';
}

// Carregar contatos
async function loadContacts() {
    try {
        const res = await fetch('/api/admin/landing-page/contacts', {
            headers: { 'Authorization': 'Bearer ' + authToken }
        });
        const data = await res.json();
        contactsData = data.data || [];
        renderContacts();
    } catch (e) {
        showError('Erro ao carregar contatos: ' + e.message);
    }
}

function renderContacts() {
    const list = document.getElementById('contacts-list');
    list.innerHTML = '<table class="table"><thead><tr><th>Tipo</th><th>Valor</th><th>Label</th><th>Ações</th></tr></thead><tbody>' +
        contactsData.map(contact => `
            <tr>
                <td>${contact.tipo}</td>
                <td>${contact.valor}</td>
                <td>${contact.label || ''}</td>
                <td>
                    <button onclick="editContact(${contact.id})">Editar</button>
                    <button onclick="deleteContact(${contact.id})">Excluir</button>
                </td>
            </tr>
        `).join('') + '</tbody></table>';
}

function showError(msg) {
    document.getElementById('error').textContent = msg;
    document.getElementById('error').style.display = 'block';
    setTimeout(() => document.getElementById('error').style.display = 'none', 5000);
}

function showSuccess(msg) {
    document.getElementById('success').textContent = msg;
    document.getElementById('success').style.display = 'block';
    setTimeout(() => document.getElementById('success').style.display = 'none', 5000);
}

// Carregar ao iniciar
loadConfig();
</script>

