// Salaries Page
let selectedEmployee = null;
let currentReferenceMonth = getCurrentMonth();
let salaryPaymentsData = [];
let filteredPayments = [];
let salaryEmployeesData = [];

// Pagination
let salaryCurrentPage = 1;
const salaryItemsPerPage = 20;

// Filters
let salaryFilters = {
    employeeId: '',
    paymentType: '',
    description: ''
};

async function renderSalaries() {
    const content = document.getElementById('main-content');
    content.innerHTML = '<div class="flex justify-center items-center h-64"><div class="spinner"></div></div>';
    
    try {
        const [payments, employees] = await Promise.all([
            apiRequest('salary-payments.php'),
            apiRequest('employees.php')
        ]);
        
        salaryPaymentsData = payments;
        salaryEmployeesData = employees.filter(e => e.active);
        
        applyPaymentFilters();
        renderSalariesContent();
        
    } catch (error) {
        content.innerHTML = `<div class="text-red-500">Erro ao carregar salários: ${error.message}</div>`;
    }
}

function applyPaymentFilters() {
    filteredPayments = salaryPaymentsData.filter(p => {
        if (salaryFilters.employeeId && p.employee_id !== salaryFilters.employeeId) return false;
        if (salaryFilters.paymentType && p.payment_type !== salaryFilters.paymentType) return false;
        if (salaryFilters.description && !p.description?.toLowerCase().includes(salaryFilters.description.toLowerCase())) return false;
        return true;
    });
    salaryCurrentPage = 1;
}

function updateSalaryFilter(key, value) {
    salaryFilters[key] = value;
    applyPaymentFilters();
    renderSalariesContent();
}

function clearSalaryFilters() {
    salaryFilters = { employeeId: '', paymentType: '', description: '' };
    applyPaymentFilters();
    renderSalariesContent();
}

function goToSalaryPage(page) {
    const totalPages = Math.ceil(filteredPayments.length / salaryItemsPerPage);
    if (page >= 1 && page <= totalPages) {
        salaryCurrentPage = page;
        renderSalariesContent();
    }
}

function renderSalariesContent() {
    const content = document.getElementById('main-content');
    
    const groupedByEmployee = {};
    salaryEmployeesData.forEach(emp => {
        groupedByEmployee[emp.id] = {
            employee: emp,
            payments: salaryPaymentsData.filter(p => p.employee_id === emp.id),
            totalPaid: salaryPaymentsData.filter(p => p.employee_id === emp.id && p.reference_month === currentReferenceMonth)
                .reduce((sum, p) => sum + parseFloat(p.amount || 0), 0)
        };
    });
    
    const totalPages = Math.ceil(filteredPayments.length / salaryItemsPerPage);
    const startIndex = (salaryCurrentPage - 1) * salaryItemsPerPage;
    const endIndex = startIndex + salaryItemsPerPage;
    const pagePayments = filteredPayments.slice(startIndex, endIndex);
    
    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">Salários</h3>
                <div class="flex gap-2 items-center">
                    <label class="text-sm text-gray-600 dark:text-gray-400">Mês referência:</label>
                    <input type="month" id="reference-month" value="${currentReferenceMonth}" onchange="changeReferenceMonth(this.value)" class="form-input w-auto">
                    <button onclick="openPaymentModal()" class="btn-primary" data-testid="button-new-payment">
                        <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 Pagamento
                    </button>
                </div>
            </div>
            
            <!-- Summary Cards -->
            <div class="grid gap-4 md:grid-cols-3">
                ${Object.values(groupedByEmployee).map(data => {
                    const employeeSalary = parseFloat(data.employee.salary || 0);
                    const remaining = employeeSalary - data.totalPaid;
                    const advances = data.payments.filter(p => p.payment_type === 'advance' && p.reference_month === currentReferenceMonth);
                    const salaryPayments = data.payments.filter(p => p.payment_type === 'salary' && p.reference_month === currentReferenceMonth);
                    
                    return `
                        <div class="card p-4" data-testid="card-salary-${data.employee.id}">
                            <div class="flex items-center justify-between mb-3">
                                <div class="flex items-center gap-2">
                                    <div class="w-10 h-10 rounded-full bg-blue-500 flex items-center justify-center text-white font-medium">
                                        ${data.employee.name.charAt(0).toUpperCase()}
                                    </div>
                                    <div>
                                        <h4 class="font-medium text-gray-800 dark:text-white">${data.employee.name}</h4>
                                        <p class="text-xs text-gray-500">Salário: ${formatMoney(employeeSalary)}</p>
                                    </div>
                                </div>
                                <button onclick="openPaymentModal(null, '${data.employee.id}')" class="p-2 rounded-full hover:bg-gray-100 dark:hover:bg-zinc-700" title="Adicionar pagamento">
                                    <svg class="w-5 h-5 text-green-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/></svg>
                                </button>
                            </div>
                            
                            <div class="space-y-2 text-sm">
                                <div class="flex justify-between">
                                    <span class="text-gray-500">Adiantamentos:</span>
                                    <span class="text-orange-500 font-medium">${formatMoney(advances.reduce((s, p) => s + parseFloat(p.amount || 0), 0))}</span>
                                </div>
                                <div class="flex justify-between">
                                    <span class="text-gray-500">Pagamentos:</span>
                                    <span class="text-green-500 font-medium">${formatMoney(salaryPayments.reduce((s, p) => s + parseFloat(p.amount || 0), 0))}</span>
                                </div>
                                <div class="flex justify-between pt-2 border-t border-gray-100 dark:border-zinc-700">
                                    <span class="text-gray-500">Restante:</span>
                                    <span class="${remaining > 0 ? 'text-red-500' : 'text-green-500'} font-bold">${formatMoney(remaining)}</span>
                                </div>
                            </div>
                            
                            <button onclick="showEmployeeHistory('${data.employee.id}')" class="mt-3 text-sm text-blue-500 hover:text-blue-600 w-full text-center">
                                Ver histórico
                            </button>
                        </div>
                    `;
                }).join('') || '<p class="text-gray-500 col-span-full text-center py-8">Nenhum funcionário cadastrado</p>'}
            </div>
            
            <!-- Recent Payments Table with Filters -->
            <div class="card overflow-hidden">
                <div class="p-4 border-b border-gray-200 dark:border-zinc-700">
                    <h4 class="font-semibold text-gray-800 dark:text-white mb-3">Pagamentos Recentes</h4>
                    
                    <!-- Filters -->
                    <div class="grid grid-cols-2 md:grid-cols-4 gap-3">
                        <div>
                            <label class="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">Funcionário</label>
                            <select onchange="updateSalaryFilter('employeeId', this.value)" class="w-full px-2 py-1.5 text-sm border border-gray-300 dark:border-zinc-600 rounded bg-white dark:bg-zinc-700 text-gray-900 dark:text-white" data-testid="filter-employee">
                                <option value="">Todos</option>
                                ${salaryEmployeesData.map(e => `<option value="${e.id}" ${salaryFilters.employeeId === e.id ? 'selected' : ''}>${e.name}</option>`).join('')}
                            </select>
                        </div>
                        <div>
                            <label class="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">Tipo</label>
                            <select onchange="updateSalaryFilter('paymentType', this.value)" class="w-full px-2 py-1.5 text-sm border border-gray-300 dark:border-zinc-600 rounded bg-white dark:bg-zinc-700 text-gray-900 dark:text-white" data-testid="filter-type">
                                <option value="">Todos</option>
                                <option value="salary" ${salaryFilters.paymentType === 'salary' ? 'selected' : ''}>Salário</option>
                                <option value="advance" ${salaryFilters.paymentType === 'advance' ? 'selected' : ''}>Adiantamento</option>
                                <option value="bonus" ${salaryFilters.paymentType === 'bonus' ? 'selected' : ''}>Bônus</option>
                                <option value="extra" ${salaryFilters.paymentType === 'extra' ? 'selected' : ''}>Extra</option>
                                <option value="vacation" ${salaryFilters.paymentType === 'vacation' ? 'selected' : ''}>Férias</option>
                                <option value="thirteenth" ${salaryFilters.paymentType === 'thirteenth' ? 'selected' : ''}>13º Salário</option>
                            </select>
                        </div>
                        <div>
                            <label class="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">Descrição</label>
                            <input type="text" placeholder="Buscar..." value="${salaryFilters.description}" onkeyup="updateSalaryFilter('description', this.value)" class="w-full px-2 py-1.5 text-sm border border-gray-300 dark:border-zinc-600 rounded bg-white dark:bg-zinc-700 text-gray-900 dark:text-white" data-testid="filter-description">
                        </div>
                        <div class="flex items-end">
                            <button onclick="clearSalaryFilters()" class="text-sm text-blue-500 hover:text-blue-700">Limpar Filtros</button>
                        </div>
                    </div>
                </div>
                <div class="overflow-x-auto">
                    <table class="w-full">
                        <thead class="bg-gray-50 dark:bg-zinc-700">
                            <tr>
                                <th class="table-header">Data</th>
                                <th class="table-header">Funcionário</th>
                                <th class="table-header">Tipo</th>
                                <th class="table-header">Valor</th>
                                <th class="table-header">Descrição</th>
                                <th class="table-header">Registrado por</th>
                                <th class="table-header">Ações</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-200 dark:divide-zinc-700">
                            ${pagePayments.map(p => `
                                <tr class="hover:bg-gray-50 dark:hover:bg-zinc-700/50">
                                    <td class="table-cell">${formatDate(p.payment_date)}</td>
                                    <td class="table-cell font-medium">${p.employee_name}</td>
                                    <td class="table-cell">
                                        <span class="px-2 py-1 text-xs rounded-full ${getPaymentTypeBadgeClass(p.payment_type)}">
                                            ${formatPaymentType(p.payment_type)}
                                        </span>
                                    </td>
                                    <td class="table-cell font-medium">${formatMoney(p.amount)}</td>
                                    <td class="table-cell text-gray-500">${p.description || '-'}</td>
                                    <td class="table-cell text-gray-500">${p.created_by_name || '-'}</td>
                                    <td class="table-cell">
                                        <div class="flex gap-1">
                                            <button onclick="openPaymentModal('${p.id}')" class="p-1 rounded hover:bg-gray-100 dark:hover:bg-zinc-600" 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="deletePayment('${p.id}')" class="p-1 rounded hover:bg-gray-100 dark:hover:bg-zinc-600" 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>
                                    </td>
                                </tr>
                            `).join('') || '<tr><td colspan="7" class="table-cell text-center text-gray-500">Nenhum pagamento registrado</td></tr>'}
                        </tbody>
                    </table>
                    
                    <!-- Pagination -->
                    ${totalPages > 1 ? `
                        <div class="flex items-center justify-between p-4 border-t border-gray-200 dark:border-zinc-700">
                            <div class="text-sm text-gray-500 dark:text-gray-400">
                                Mostrando ${startIndex + 1} - ${Math.min(endIndex, filteredPayments.length)} de ${filteredPayments.length}
                            </div>
                            <div class="flex gap-1">
                                <button onclick="goToSalaryPage(1)" ${salaryCurrentPage === 1 ? 'disabled' : ''} class="px-3 py-1 rounded text-sm ${salaryCurrentPage === 1 ? 'bg-gray-100 text-gray-400 dark:bg-zinc-700' : 'bg-gray-200 hover:bg-gray-300 dark:bg-zinc-600 dark:hover:bg-zinc-500 text-gray-700 dark:text-white'}">«</button>
                                <button onclick="goToSalaryPage(${salaryCurrentPage - 1})" ${salaryCurrentPage === 1 ? 'disabled' : ''} class="px-3 py-1 rounded text-sm ${salaryCurrentPage === 1 ? 'bg-gray-100 text-gray-400 dark:bg-zinc-700' : 'bg-gray-200 hover:bg-gray-300 dark:bg-zinc-600 dark:hover:bg-zinc-500 text-gray-700 dark:text-white'}">‹</button>
                                <span class="px-3 py-1 text-sm text-gray-700 dark:text-white">${salaryCurrentPage} / ${totalPages}</span>
                                <button onclick="goToSalaryPage(${salaryCurrentPage + 1})" ${salaryCurrentPage === totalPages ? 'disabled' : ''} class="px-3 py-1 rounded text-sm ${salaryCurrentPage === totalPages ? 'bg-gray-100 text-gray-400 dark:bg-zinc-700' : 'bg-gray-200 hover:bg-gray-300 dark:bg-zinc-600 dark:hover:bg-zinc-500 text-gray-700 dark:text-white'}">›</button>
                                <button onclick="goToSalaryPage(${totalPages})" ${salaryCurrentPage === totalPages ? 'disabled' : ''} class="px-3 py-1 rounded text-sm ${salaryCurrentPage === totalPages ? 'bg-gray-100 text-gray-400 dark:bg-zinc-700' : 'bg-gray-200 hover:bg-gray-300 dark:bg-zinc-600 dark:hover:bg-zinc-500 text-gray-700 dark:text-white'}">»</button>
                            </div>
                        </div>
                    ` : ''}
                </div>
            </div>
        </div>
    `;
}

function getPaymentTypeBadgeClass(type) {
    const classes = {
        advance: 'bg-orange-100 text-orange-800 dark:bg-orange-900/30 dark:text-orange-400',
        salary: 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400',
        bonus: 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400',
        extra: 'bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-400',
        vacation: 'bg-cyan-100 text-cyan-800 dark:bg-cyan-900/30 dark:text-cyan-400',
        thirteenth: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400'
    };
    return classes[type] || 'bg-gray-100 text-gray-800 dark:bg-gray-900/30 dark:text-gray-400';
}

function formatPaymentType(type) {
    const types = {
        advance: 'Adiantamento',
        salary: 'Salário',
        bonus: 'Bônus',
        extra: 'Extra',
        vacation: 'Férias',
        thirteenth: '13º Salário'
    };
    return types[type] || type;
}

function changeReferenceMonth(month) {
    currentReferenceMonth = month;
    renderSalaries();
}

function filterByEmployee(employeeId) {
    selectedEmployee = employeeId;
    showEmployeeHistory(employeeId);
}

async function showEmployeeHistory(employeeId) {
    const payments = await apiRequest(`salary-payments.php?employee_id=${employeeId}`);
    const employee = salaryEmployeesData.find(e => e.id === employeeId);
    
    const modalContent = `
        <div class="p-6" style="min-width: 600px; max-width: 90vw;">
            <h3 class="text-lg font-semibold mb-4 text-gray-800 dark:text-white">Histórico de Pagamentos - ${employee?.name || 'Funcionário'}</h3>
            
            <div class="max-h-[60vh] overflow-y-auto space-y-3">
                ${payments.map(p => `
                    <div class="p-3 bg-gray-50 dark:bg-zinc-700 rounded-lg">
                        <div class="flex justify-between items-start gap-4">
                            <div class="flex-1">
                                <span class="px-2 py-0.5 text-xs rounded-full ${getPaymentTypeBadgeClass(p.payment_type)}">
                                    ${formatPaymentType(p.payment_type)}
                                </span>
                                <p class="mt-1 text-sm text-gray-600 dark:text-gray-400">${p.description || 'Sem descrição'}</p>
                                <p class="text-xs text-gray-400 mt-1">Ref: ${p.reference_month || '-'}</p>
                            </div>
                            <div class="text-right">
                                <p class="font-bold text-gray-800 dark:text-white">${formatMoney(p.amount)}</p>
                                <p class="text-xs text-gray-500">${formatDate(p.payment_date)}</p>
                            </div>
                            <div class="flex gap-1">
                                <button onclick="closeModal(); openPaymentModal('${p.id}')" class="p-1 rounded hover:bg-gray-200 dark:hover:bg-zinc-600" title="Editar">
                                    <svg class="w-4 h-4 text-blue-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="deletePaymentFromHistory('${p.id}', '${employeeId}')" class="p-1 rounded hover:bg-gray-200 dark:hover:bg-zinc-600" 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>
                `).join('') || '<p class="text-gray-500 text-center py-4">Nenhum pagamento registrado</p>'}
            </div>
            
            <div class="mt-4 flex justify-end">
                <button onclick="closeModal()" class="btn-secondary">Fechar</button>
            </div>
        </div>
    `;
    
    openModal(modalContent, 'lg');
}

async function deletePaymentFromHistory(paymentId, employeeId) {
    if (!confirm('Tem certeza que deseja excluir este pagamento?')) return;
    
    try {
        await apiRequest(`salary-payments.php?id=${paymentId}`, 'DELETE');
        showToast('Pagamento excluído com sucesso!');
        closeModal();
        await renderSalaries();
        showEmployeeHistory(employeeId);
    } catch (error) {
        showToast(error.message, 'error');
    }
}

async function openPaymentModal(paymentId = null, employeeId = null) {
    const employees = salaryEmployeesData.length > 0 ? salaryEmployeesData : await apiRequest('employees.php');
    let payment = null;
    
    if (paymentId) {
        payment = salaryPaymentsData.find(p => p.id === paymentId);
    }
    
    const today = new Date().toISOString().split('T')[0];
    const isEdit = !!paymentId;
    
    const modalContent = `
        <div class="p-6">
            <h3 class="text-lg font-semibold mb-4 text-gray-800 dark:text-white">${paymentId ? 'Editar' : 'Novo'} Pagamento</h3>
            <form id="payment-form" class="space-y-4">
                <input type="hidden" id="payment-id" value="${paymentId || ''}">
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Funcionário *</label>
                    <select id="payment-employee" required class="form-input" data-testid="select-payment-employee">
                        <option value="">Selecione...</option>
                        ${employees.filter(e => e.active).map(e => `
                            <option value="${e.id}" ${(payment?.employee_id === e.id || employeeId === e.id) ? 'selected' : ''}>${e.name} - ${formatMoney(e.salary)}</option>
                        `).join('')}
                    </select>
                </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">Tipo *</label>
                        <select id="payment-type" required class="form-input" onchange="toggleInstallmentOption()" data-testid="select-payment-type">
                            <option value="salary" ${payment?.payment_type === 'salary' ? 'selected' : ''}>Salário</option>
                            <option value="advance" ${payment?.payment_type === 'advance' ? 'selected' : ''}>Adiantamento</option>
                            <option value="extra" ${payment?.payment_type === 'extra' ? 'selected' : ''}>Extra</option>
                            <option value="vacation" ${payment?.payment_type === 'vacation' ? 'selected' : ''}>Férias</option>
                            <option value="thirteenth" ${payment?.payment_type === 'thirteenth' ? 'selected' : ''}>13º Salário</option>
                            <option value="bonus" ${payment?.payment_type === 'bonus' ? 'selected' : ''}>Bônus</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Valor Total *</label>
                        <input type="number" id="payment-amount" required step="0.01" min="0" class="form-input" value="${payment?.amount || ''}" onchange="updateInstallmentPreview()" data-testid="input-payment-amount">
                    </div>
                </div>
                
                <!-- Installment Option (only for new advances) -->
                <div id="installment-section" class="${isEdit ? 'hidden' : ''}" style="display: none;">
                    <div class="p-4 bg-orange-50 dark:bg-orange-900/20 rounded-lg border border-orange-200 dark:border-orange-800">
                        <div class="flex items-center gap-2 mb-3">
                            <input type="checkbox" id="payment-installment" class="w-4 h-4 text-orange-500" onchange="toggleInstallmentFields()">
                            <label for="payment-installment" class="text-sm font-medium text-orange-800 dark:text-orange-300">Parcelar adiantamento</label>
                        </div>
                        <div id="installment-fields" class="hidden space-y-3">
                            <div class="grid grid-cols-2 gap-4">
                                <div>
                                    <label class="block text-xs text-orange-700 dark:text-orange-400 mb-1">Número de parcelas</label>
                                    <input type="number" id="payment-installments" min="2" max="48" value="12" class="form-input" onchange="updateInstallmentPreview()" data-testid="input-installments">
                                </div>
                                <div>
                                    <label class="block text-xs text-orange-700 dark:text-orange-400 mb-1">Valor por parcela</label>
                                    <input type="text" id="installment-value" class="form-input bg-gray-100 dark:bg-zinc-600" readonly>
                                </div>
                            </div>
                            <p id="installment-preview" class="text-xs text-orange-600 dark:text-orange-400"></p>
                        </div>
                    </div>
                </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">Data do Pagamento *</label>
                        <input type="date" id="payment-date" required class="form-input" value="${payment?.payment_date || today}" data-testid="input-payment-date">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1" id="reference-label">Mês Referência</label>
                        <input type="month" id="payment-reference" class="form-input" value="${payment?.reference_month || currentReferenceMonth}" data-testid="input-payment-reference">
                    </div>
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Descrição</label>
                    <input type="text" id="payment-description" class="form-input" value="${payment?.description || ''}" placeholder="Ex: Pagamento quinzenal, Vale transporte..." data-testid="input-payment-description">
                </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-payment">Salvar</button>
                </div>
            </form>
        </div>
    `;
    
    openModal(modalContent);
    
    toggleInstallmentOption();
    
    document.getElementById('payment-form').onsubmit = async (e) => {
        e.preventDefault();
        await savePayment();
    };
}

function toggleInstallmentOption() {
    const paymentType = document.getElementById('payment-type').value;
    const installmentSection = document.getElementById('installment-section');
    const paymentId = document.getElementById('payment-id').value;
    
    if (paymentType === 'advance' && !paymentId) {
        installmentSection.style.display = 'block';
    } else {
        installmentSection.style.display = 'none';
        document.getElementById('payment-installment').checked = false;
        toggleInstallmentFields();
    }
}

function toggleInstallmentFields() {
    const isInstallment = document.getElementById('payment-installment').checked;
    const fieldsDiv = document.getElementById('installment-fields');
    const referenceLabel = document.getElementById('reference-label');
    
    if (isInstallment) {
        fieldsDiv.classList.remove('hidden');
        referenceLabel.textContent = 'Mês da 1ª Parcela';
        updateInstallmentPreview();
    } else {
        fieldsDiv.classList.add('hidden');
        referenceLabel.textContent = 'Mês Referência';
    }
}

function updateInstallmentPreview() {
    const totalAmount = parseFloat(document.getElementById('payment-amount').value) || 0;
    const installments = parseInt(document.getElementById('payment-installments').value) || 1;
    const startMonth = document.getElementById('payment-reference').value;
    
    if (installments > 0 && totalAmount > 0) {
        const installmentValue = totalAmount / installments;
        document.getElementById('installment-value').value = formatMoney(installmentValue);
        
        if (startMonth) {
            const [year, month] = startMonth.split('-').map(Number);
            const endDate = new Date(year, month - 1 + installments - 1, 1);
            const endMonthStr = endDate.toLocaleDateString('pt-BR', { month: 'long', year: 'numeric' });
            document.getElementById('installment-preview').textContent = 
                `${installments}x de ${formatMoney(installmentValue)} - última parcela em ${endMonthStr}`;
        }
    }
}

async function savePayment() {
    const id = document.getElementById('payment-id').value;
    const isInstallment = document.getElementById('payment-installment')?.checked || false;
    const paymentType = document.getElementById('payment-type').value;
    
    try {
        if (id) {
            const data = {
                employee_id: document.getElementById('payment-employee').value,
                payment_type: paymentType,
                amount: parseFloat(document.getElementById('payment-amount').value),
                payment_date: document.getElementById('payment-date').value,
                reference_month: document.getElementById('payment-reference').value || null,
                description: document.getElementById('payment-description').value || null
            };
            await apiRequest(`salary-payments.php?id=${id}`, 'PUT', data);
            showToast('Pagamento atualizado com sucesso!');
        } else if (isInstallment && paymentType === 'advance') {
            const totalAmount = parseFloat(document.getElementById('payment-amount').value);
            const installments = parseInt(document.getElementById('payment-installments').value);
            const startMonth = document.getElementById('payment-reference').value;
            const description = document.getElementById('payment-description').value || 'Adiantamento parcelado';
            const firstPaymentDate = document.getElementById('payment-date').value;
            const employeeId = document.getElementById('payment-employee').value;
            
            const installmentAmount = Math.round((totalAmount / installments) * 100) / 100;
            
            const [startYear, startMonthNum] = startMonth.split('-').map(Number);
            const [payYear, payMonth, payDay] = firstPaymentDate.split('-').map(Number);
            
            for (let i = 0; i < installments; i++) {
                const refDate = new Date(startYear, startMonthNum - 1 + i, 1);
                const refMonth = `${refDate.getFullYear()}-${String(refDate.getMonth() + 1).padStart(2, '0')}`;
                
                // Calculate payment date for each installment (same day each month)
                const paymentDate = new Date(payYear, payMonth - 1 + i, payDay);
                const paymentDateStr = paymentDate.toISOString().split('T')[0];
                
                const data = {
                    employee_id: employeeId,
                    payment_type: 'advance',
                    amount: installmentAmount,
                    payment_date: paymentDateStr,
                    reference_month: refMonth,
                    description: `${description} (${i + 1}/${installments})`
                };
                
                await apiRequest('salary-payments.php', 'POST', data);
            }
            
            showToast(`${installments} parcelas registradas com sucesso!`);
        } else {
            const data = {
                employee_id: document.getElementById('payment-employee').value,
                payment_type: paymentType,
                amount: parseFloat(document.getElementById('payment-amount').value),
                payment_date: document.getElementById('payment-date').value,
                reference_month: document.getElementById('payment-reference').value || null,
                description: document.getElementById('payment-description').value || null
            };
            await apiRequest('salary-payments.php', 'POST', data);
            showToast('Pagamento registrado com sucesso!');
        }
        closeModal();
        renderSalaries();
    } catch (error) {
        showToast(error.message, 'error');
    }
}

async function deletePayment(id) {
    if (!confirm('Tem certeza que deseja excluir este pagamento?')) return;
    
    try {
        await apiRequest(`salary-payments.php?id=${id}`, 'DELETE');
        showToast('Pagamento excluído com sucesso!');
        renderSalaries();
    } catch (error) {
        showToast(error.message, 'error');
    }
}
