// Employees Page
async function renderEmployees() {
    const content = document.getElementById('main-content');
    
    try {
        const [employees, branches] = await Promise.all([
            apiRequest('employees.php'),
            apiRequest('branches.php')
        ]);
        
        content.innerHTML = `
            <div class="space-y-6">
                <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
                    <h3 class="text-xl font-semibold text-gray-800 dark:text-white">Funcionários</h3>
                    <button onclick="openEmployeeModal()" class="btn-primary" data-testid="button-new-employee">
                        <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/></svg>
                        Novo Funcionário
                    </button>
                </div>
                
                <div class="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
                    ${employees.filter(e => e.active).map(emp => `
                        <div class="card p-4" data-testid="card-employee-${emp.id}">
                            <div class="flex items-start justify-between">
                                <div class="flex items-center gap-3">
                                    <div class="w-12 h-12 rounded-full bg-blue-500 flex items-center justify-center text-white text-lg font-medium">
                                        ${emp.name.charAt(0).toUpperCase()}
                                    </div>
                                    <div>
                                        <h4 class="font-semibold text-gray-800 dark:text-white">${emp.name}</h4>
                                        <p class="text-sm text-gray-500 dark:text-gray-400">${emp.branch_name || 'Sem filial'}</p>
                                    </div>
                                </div>
                                <div class="flex gap-1">
                                    <button onclick="openEmployeeModal('${emp.id}')" class="p-1.5 rounded hover:bg-gray-100 dark:hover:bg-zinc-700" title="Editar">
                                        <svg class="w-4 h-4 text-gray-500" 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 onclick="deleteEmployee('${emp.id}')" class="p-1.5 rounded hover:bg-gray-100 dark:hover:bg-zinc-700" title="Excluir">
                                        <svg class="w-4 h-4 text-red-500" 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="mt-4 pt-4 border-t border-gray-100 dark:border-zinc-700 space-y-2">
                                <div class="flex justify-between text-sm">
                                    <span class="text-gray-500">Salário:</span>
                                    <span class="font-medium text-gray-800 dark:text-white">${formatMoney(emp.salary)}</span>
                                </div>
                                ${emp.cpf ? `<div class="flex justify-between text-sm">
                                    <span class="text-gray-500">CPF:</span>
                                    <span class="text-gray-800 dark:text-white">${emp.cpf}</span>
                                </div>` : ''}
                                ${emp.phone ? `<div class="flex justify-between text-sm">
                                    <span class="text-gray-500">Telefone:</span>
                                    <span class="text-gray-800 dark:text-white">${emp.phone}</span>
                                </div>` : ''}
                            </div>
                            <div class="mt-3">
                                <button onclick="loadPage('salaries'); setTimeout(() => filterByEmployee('${emp.id}'), 100)" class="text-sm text-blue-500 hover:text-blue-600">
                                    Ver pagamentos
                                </button>
                            </div>
                        </div>
                    `).join('') || '<p class="text-gray-500 col-span-full text-center py-8">Nenhum funcionário cadastrado</p>'}
                </div>
            </div>
        `;
        
        window.employeesData = employees;
        window.branchesData = branches;
        
    } catch (error) {
        content.innerHTML = `<div class="text-red-500">Erro ao carregar funcionários: ${error.message}</div>`;
    }
}

async function openEmployeeModal(id = null) {
    const branches = window.branchesData || await apiRequest('branches.php');
    let employee = null;
    
    if (id) {
        employee = (window.employeesData || []).find(e => e.id === id);
    }
    
    const modalContent = `
        <div class="p-6">
            <h3 class="text-lg font-semibold mb-4 text-gray-800 dark:text-white">${id ? 'Editar' : 'Novo'} Funcionário</h3>
            <form id="employee-form" class="space-y-4">
                <input type="hidden" id="employee-id" value="${id || ''}">
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Nome *</label>
                    <input type="text" id="employee-name" required class="form-input" value="${employee?.name || ''}" data-testid="input-employee-name">
                </div>
                
                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">CPF</label>
                        <input type="text" id="employee-cpf" class="form-input" value="${employee?.cpf || ''}" placeholder="000.000.000-00" data-testid="input-employee-cpf">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Telefone</label>
                        <input type="text" id="employee-phone" class="form-input" value="${employee?.phone || ''}" placeholder="(00) 00000-0000" data-testid="input-employee-phone">
                    </div>
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Endereço</label>
                    <input type="text" id="employee-address" class="form-input" value="${employee?.address || ''}" data-testid="input-employee-address">
                </div>
                
                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Salário *</label>
                        <input type="number" id="employee-salary" required step="0.01" min="0" class="form-input" value="${employee?.salary || ''}" data-testid="input-employee-salary">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Filial</label>
                        <select id="employee-branch" class="form-input" data-testid="select-employee-branch">
                            <option value="">Selecione...</option>
                            ${branches.filter(b => b.active).map(b => `
                                <option value="${b.id}" ${employee?.branch_id === b.id ? 'selected' : ''}>${b.name}</option>
                            `).join('')}
                        </select>
                    </div>
                </div>
                
                <div class="flex justify-end gap-3 pt-4">
                    <button type="button" onclick="closeModal()" class="btn-secondary">Cancelar</button>
                    <button type="submit" class="btn-primary" data-testid="button-save-employee">Salvar</button>
                </div>
            </form>
        </div>
    `;
    
    openModal(modalContent);
    
    document.getElementById('employee-form').onsubmit = async (e) => {
        e.preventDefault();
        await saveEmployee();
    };
}

async function saveEmployee() {
    const id = document.getElementById('employee-id').value;
    const data = {
        name: document.getElementById('employee-name').value,
        cpf: document.getElementById('employee-cpf').value || null,
        phone: document.getElementById('employee-phone').value || null,
        address: document.getElementById('employee-address').value || null,
        salary: parseFloat(document.getElementById('employee-salary').value) || 0,
        branch_id: document.getElementById('employee-branch').value || null
    };
    
    try {
        if (id) {
            await apiRequest(`employees.php?id=${id}`, 'PUT', data);
            showToast('Funcionário atualizado com sucesso!');
        } else {
            await apiRequest('employees.php', 'POST', data);
            showToast('Funcionário cadastrado com sucesso!');
        }
        closeModal();
        renderEmployees();
    } catch (error) {
        showToast(error.message, 'error');
    }
}

async function deleteEmployee(id) {
    if (!confirm('Tem certeza que deseja excluir este funcionário?')) return;
    
    try {
        await apiRequest(`employees.php?id=${id}`, 'DELETE');
        showToast('Funcionário excluído com sucesso!');
        renderEmployees();
    } catch (error) {
        showToast(error.message, 'error');
    }
}
