// Branches Page
let branchesPageData = [];

async function renderBranches() {
    const content = document.getElementById('main-content');
    
    try {
        branchesPageData = await apiRequest('branches.php');
        
        content.innerHTML = `
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-lg font-semibold text-gray-800 dark:text-white">Lista de Filiais</h3>
                <button class="btn btn-primary" onclick="openBranchModal()" data-testid="button-new-branch">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/></svg>
                    Nova Filial
                </button>
            </div>
            
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                ${branchesPageData.length > 0 ? branchesPageData.map(b => `
                    <div class="card" data-testid="card-branch-${b.id}">
                        <div class="flex items-start justify-between mb-4">
                            <div class="flex items-center gap-3">
                                <div class="w-12 h-12 rounded-full bg-green-100 dark:bg-green-900 flex items-center justify-center">
                                    <svg class="w-6 h-6 text-green-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4"/></svg>
                                </div>
                                <div>
                                    <h4 class="font-semibold text-gray-800 dark:text-white">${b.name}</h4>
                                    <span class="badge ${b.active ? 'badge-income' : 'badge-expense'}">${b.active ? 'Ativa' : 'Inativa'}</span>
                                </div>
                            </div>
                            <div class="flex gap-1">
                                <button class="btn btn-outline btn-sm" onclick="openBranchModal('${b.id}')" data-testid="button-edit-branch-${b.id}">
                                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg>
                                </button>
                                <button class="btn btn-danger btn-sm" onclick="deleteBranch('${b.id}')" data-testid="button-delete-branch-${b.id}">
                                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
                                </button>
                            </div>
                        </div>
                        <div class="space-y-2 text-sm">
                            ${b.address ? `<p class="text-gray-600 dark:text-gray-300"><strong>Endereço:</strong> ${b.address}</p>` : ''}
                        </div>
                    </div>
                `).join('') : '<div class="col-span-full empty-state"><p>Nenhuma filial cadastrada</p></div>'}
            </div>
        `;
        
    } catch (error) {
        content.innerHTML = `<div class="empty-state"><p>Erro ao carregar filiais: ${error.message}</p></div>`;
    }
}

function openBranchModal(id = null) {
    const branch = id ? branchesPageData.find(b => b.id === id) : null;
    
    openModal(`
        <div class="p-6">
            <h3 class="text-lg font-semibold mb-4 text-gray-800 dark:text-white">
                ${branch ? 'Editar Filial' : 'Nova Filial'}
            </h3>
            <form id="branch-form" onsubmit="saveBranch(event, ${id ? `'${id}'` : null})">
                <div class="form-group">
                    <label class="form-label">Nome</label>
                    <input type="text" id="branch-name" class="form-input" required value="${branch?.name || ''}" data-testid="input-name">
                </div>
                
                <div class="form-group">
                    <label class="form-label">Endereço</label>
                    <input type="text" id="branch-address" class="form-input" value="${branch?.address || ''}" data-testid="input-address">
                </div>
                
                <div class="form-group">
                    <label class="flex items-center gap-2">
                        <input type="checkbox" id="branch-active" ${branch?.active !== false ? 'checked' : ''}>
                        <span class="form-label mb-0">Ativa</span>
                    </label>
                </div>
                
                <div class="flex gap-2 justify-end mt-6">
                    <button type="button" class="btn btn-secondary" onclick="closeModal()">Cancelar</button>
                    <button type="submit" class="btn btn-primary" data-testid="button-submit">Salvar</button>
                </div>
            </form>
        </div>
    `);
}

async function saveBranch(event, id = null) {
    event.preventDefault();
    
    const data = {
        name: document.getElementById('branch-name').value,
        address: document.getElementById('branch-address').value || null,
        isActive: document.getElementById('branch-active').checked
    };
    
    try {
        if (id) {
            await apiRequest(`branches.php?id=${id}`, 'PUT', data);
            showToast('Filial atualizada com sucesso!');
        } else {
            await apiRequest('branches.php', 'POST', data);
            showToast('Filial criada com sucesso!');
        }
        closeModal();
        renderBranches();
    } catch (error) {
        showToast(error.message, 'error');
    }
}

async function deleteBranch(id) {
    if (!confirm('Tem certeza que deseja excluir esta filial?')) return;
    
    try {
        await apiRequest(`branches.php?id=${id}`, 'DELETE');
        showToast('Filial excluída com sucesso!');
        renderBranches();
    } catch (error) {
        showToast(error.message, 'error');
    }
}
