<?php $title = 'Clientes'; ?>

<div class="card">
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem; gap: 0.5rem;">
        <h1>Clientes</h1>
        <div style="display: flex; gap: 0.5rem; align-items: center;">
            <a href="/clientes/create" class="btn">Novo Cliente</a>
            <a href="/clientes/mapa" class="btn btn-secondary">Mapa</a>
            <div class="form-inline" style="display: flex; gap: 0.25rem; align-items: center;">
                <label for="sepSelect" style="font-size: 0.9rem; color: #555;">CSV:</label>
                <select id="sepSelect" class="input" style="width: 110px;">
                    <option value=";">Ponto e vírgula</option>
                    <option value=",">Vírgula</option>
            <option value="\t">Tabulação</option>
                </select>
                <button id="exportBtn" class="btn btn-secondary">Exportar</button>
            </div>
            <div class="form-inline" style="display: flex; gap: 0.25rem; align-items: center;">
                <input type="file" id="importFile" accept="text/csv" />
                <button id="importBtn" class="btn">Importar</button>
                <button id="templateBtn" class="btn btn-secondary">Modelo de importação</button>
            </div>
        </div>
    </div>
    
    <div id="loading" class="loading">Carregando clientes...</div>
    <div id="error" class="alert alert-error" role="alert" aria-live="polite" style="display: none;"></div>
    
    <div id="columnFilters" class="card" style="margin-bottom: 0.75rem; padding: 0.5rem;">
        <div style="display:flex; align-items:center; justify-content: space-between; gap: 0.5rem;">
            <strong>Colunas da grid</strong>
            <div style="display:flex; gap:0.5rem;">
                <button id="selectAllCols" class="btn btn-secondary" type="button">Selecionar tudo</button>
                <button id="resetCols" class="btn btn-secondary" type="button">Padrão</button>
            </div>
        </div>
        <div id="columnCheckboxes" style="display: grid; grid-template-columns: repeat(4, minmax(150px, 1fr)); gap: 0.25rem; margin-top: 0.5rem;"></div>
    </div>
    
    <div class="table-responsive">
        <table id="clientsTable" class="table" style="display: none;">
            <thead>
                <tr id="clientsHeader"></tr>
            </thead>
            <tbody id="clientsBody"></tbody>
        </table>
    </div>
</div>

<script>
    const ALL_COLUMNS = [
        { key: 'id', label: 'ID' },
        { key: 'nome_fantasia', label: 'Nome Fantasia' },
        { key: 'nome', label: 'Nome' },
        { key: 'razao_social', label: 'Razão Social' },
        { key: 'tipo', label: 'Tipo' },
        { key: 'cpf', label: 'CPF' },
        { key: 'cnpj', label: 'CNPJ' },
        { key: 'telefone_fixo', label: 'Telefone Fixo' },
        { key: 'telefone_celular', label: 'Telefone Celular' },
        { key: 'email', label: 'E-mail' },
        { key: 'contato_nome', label: 'Contato' },
        { key: 'site_url', label: 'Site' },
        { key: 'referencias', label: 'Referências' },
        { key: 'limite_credito', label: 'Limite de Crédito' },
        { key: 'bloqueado', label: 'Bloqueado' },
        { key: 'inativo', label: 'Inativo' },
        { key: 'status_motivo', label: 'Motivo Status' },
    ];

    const DEFAULT_COLUMNS = ['id','nome_fantasia','razao_social','telefone_fixo','telefone_celular','cnpj'];

    function getSelectedColumns() {
        try {
            const raw = localStorage.getItem('clientes.columns');
            if (!raw) return DEFAULT_COLUMNS.slice();
            const parsed = JSON.parse(raw);
            if (Array.isArray(parsed) && parsed.length > 0) return parsed;
            return DEFAULT_COLUMNS.slice();
        } catch { return DEFAULT_COLUMNS.slice(); }
    }

    function setSelectedColumns(cols) {
        localStorage.setItem('clientes.columns', JSON.stringify(cols));
    }

    function renderColumnFilters() {
        const container = document.getElementById('columnCheckboxes');
        container.innerHTML = '';
        const selected = new Set(getSelectedColumns());
        ALL_COLUMNS.forEach(col => {
            const id = `col_${col.key}`;
            const wrapper = document.createElement('label');
            wrapper.style.display = 'flex';
            wrapper.style.alignItems = 'center';
            wrapper.style.gap = '0.4rem';
            wrapper.htmlFor = id;
            const cb = document.createElement('input');
            cb.type = 'checkbox';
            cb.id = id;
            cb.checked = selected.has(col.key);
            cb.addEventListener('change', () => {
                const current = getSelectedColumns();
                const idx = current.indexOf(col.key);
                if (cb.checked && idx === -1) current.push(col.key);
                if (!cb.checked && idx !== -1) current.splice(idx,1);
                setSelectedColumns(current);
                // Re-render se já temos dados
                if (window.__clientsCache) displayClients(window.__clientsCache);
            });
            const text = document.createElement('span');
            text.textContent = col.label;
            wrapper.appendChild(cb);
            wrapper.appendChild(text);
            container.appendChild(wrapper);
        });
        document.getElementById('selectAllCols').onclick = () => {
            setSelectedColumns(ALL_COLUMNS.map(c => c.key));
            renderColumnFilters();
            if (window.__clientsCache) displayClients(window.__clientsCache);
        };
        document.getElementById('resetCols').onclick = () => {
            setSelectedColumns(DEFAULT_COLUMNS.slice());
            renderColumnFilters();
            if (window.__clientsCache) displayClients(window.__clientsCache);
        };
    }

    async function loadClients() {
        try {
            showLoading();
            const response = await apiRequest('/api/clientes');
            
            if (!response) return; // Redirecionado para login
            
            if (!response.ok) {
                throw new Error('Erro ao carregar clientes');
            }

            const clients = await response.json();
            window.__clientsCache = clients;
            renderColumnFilters();
            displayClients(clients);
        } catch (error) {
            hideLoading();
            document.getElementById('error').style.display = 'block';
            document.getElementById('error').textContent = error.message;
        }
    }

    function displayClients(clients) {
        const selectedCols = getSelectedColumns();
        const theadRow = document.getElementById('clientsHeader');
        const tbody = document.getElementById('clientsBody');
        theadRow.innerHTML = '';
        tbody.innerHTML = '';

        // Montar cabeçalho conforme seleção
        selectedCols.forEach(key => {
            const col = ALL_COLUMNS.find(c => c.key === key);
            const th = document.createElement('th');
            th.textContent = col ? col.label : key;
            theadRow.appendChild(th);
        });
        // Coluna Ações fixa
        const thActions = document.createElement('th');
        thActions.textContent = 'Ações';
        theadRow.appendChild(thActions);

        const data = clients.data || clients; // compat de envelope
        data.forEach(client => {
            const row = document.createElement('tr');
            // Montar células dinâmicas
            selectedCols.forEach(key => {
                const td = document.createElement('td');
                let val = '';
                if (key === 'nome_fantasia') { val = client.nome_fantasia || client.nome || ''; }
                else if (key === 'cpf') { val = client.cpf || ''; }
                else if (key === 'cnpj') { val = client.cnpj || ''; }
                else if (key === 'limite_credito') { val = client.limite_credito != null ? String(client.limite_credito) : ''; }
                else if (key === 'bloqueado' || key === 'inativo') { val = client[key] ? 'Sim' : 'Não'; }
                else { val = client[key] != null ? client[key] : ''; }
                td.textContent = val;
                row.appendChild(td);
            });

            const tdActions = document.createElement('td');
            tdActions.innerHTML = `
                <a href="/clientes/${client.id}" class="btn btn-secondary" style="margin-right: 0.5rem; padding: 0.25rem 0.5rem; font-size: 0.875rem;">Ver</a>
                <a href="/clientes/${client.id}/edit" class="btn" style="margin-right: 0.5rem; padding: 0.25rem 0.5rem; font-size: 0.875rem;">Editar</a>
                <button onclick="deleteClient(${client.id})" class="btn btn-danger" style="padding: 0.25rem 0.5rem; font-size: 0.875rem;">Excluir</button>
            `;
            row.appendChild(tdActions);
            tbody.appendChild(row);
        });

        hideLoading();
        document.getElementById('clientsTable').style.display = 'table';
    }

    async function deleteClient(id) {
        if (!confirm('Tem certeza que deseja excluir este cliente?')) {
            return;
        }

        try {
            const response = await apiRequest(`/api/clientes/${id}`, {
                method: 'DELETE'
            });

            if (response && response.ok) {
                showAlert('Cliente excluído com sucesso!');
                loadClients(); // Recarregar a lista
            } else {
                showAlert('Erro ao excluir cliente', 'error');
            }
        } catch (error) {
            showAlert('Erro ao excluir cliente', 'error');
        }
    }

    // Exportação CSV
    document.getElementById('exportBtn').addEventListener('click', async () => {
        const sep = document.getElementById('sepSelect').value;
        const url = `/api/clientes/export/csv?sep=${encodeURIComponent(sep)}`;
        await downloadCsv(url, `clientes_export_${sep === '\t' ? 'tabulacao' : (sep === ',' ? 'virgula' : 'ponto-e-virgula')}.csv`);
    });

    // Modelo de importação CSV
    document.getElementById('templateBtn').addEventListener('click', async () => {
        const url = '/api/clientes/import/template';
        await downloadCsv(url, 'template_importacao_clientes.csv');
    });

    async function downloadCsv(url, filename) {
        try {
            const resp = await apiRequest(url, { method: 'GET' });
            if (!resp) return; // login
            if (!resp.ok) { showAlert('Falha ao baixar CSV', 'error'); return; }
            const blob = await resp.blob();
            const link = document.createElement('a');
            link.href = URL.createObjectURL(blob);
            link.download = filename;
            document.body.appendChild(link);
            link.click();
            URL.revokeObjectURL(link.href);
            link.remove();
        } catch (e) {
            showAlert('Erro ao baixar CSV', 'error');
        }
    }

    // Importação CSV
    document.getElementById('importBtn').addEventListener('click', async () => {
        const fileInput = document.getElementById('importFile');
        if (!fileInput.files || fileInput.files.length === 0) { showAlert('Selecione um arquivo CSV', 'error'); return; }
        const sep = document.getElementById('sepSelect').value;
        const fd = new FormData();
        fd.append('file', fileInput.files[0]);
        try {
            const resp = await apiRequest(`/api/clientes/import?sep=${encodeURIComponent(sep)}`, { method: 'POST', body: fd });
            if (!resp) return; // login
            const json = await resp.json();
            if (resp.ok && json.ok) {
                showAlert(`Importação concluída: ${json.imported} registros`, 'success');
                loadClients();
            } else {
                const errs = (json.errors || []).slice(0, 5).map(e => `L${e.line}: ${e.error}`).join('; ');
                showAlert(`Falha na importação. ${errs || ''}`, 'error');
            }
        } catch (e) {
            showAlert('Erro ao importar CSV', 'error');
        }
    });

    // Carregar clientes ao inicializar a página
    document.addEventListener('DOMContentLoaded', loadClients);
</script>