// Transactions Page
let transactionsData = [];
let filteredTransactions = [];
let categoriesData = [];
let branchesData = [];
let partnersData = [];

// Pagination
let txCurrentPage = 1;
const txItemsPerPage = 20;

// Filters
let activeFilters = {
    type: '',
    paymentMethod: '',
    branchId: '',
    categoryId: '',
    description: '',
    minAmount: '',
    maxAmount: ''
};

// Period filter
let txCurrentPeriod = 'month';
let txCustomStartDate = '';
let txCustomEndDate = '';

function getTxPeriodDates(period) {
    const now = new Date();
    let startDate, endDate;
    
    switch (period) {
        case 'day':
            startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate());
            endDate = new Date(now.getFullYear(), now.getMonth(), now.getDate());
            break;
        case 'week':
            const dayOfWeek = now.getDay();
            startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() - dayOfWeek);
            endDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() + (6 - dayOfWeek));
            break;
        case 'biweekly':
            const dayOfMonth = now.getDate();
            if (dayOfMonth <= 15) {
                startDate = new Date(now.getFullYear(), now.getMonth(), 1);
                endDate = new Date(now.getFullYear(), now.getMonth(), 15);
            } else {
                startDate = new Date(now.getFullYear(), now.getMonth(), 16);
                endDate = new Date(now.getFullYear(), now.getMonth() + 1, 0);
            }
            break;
        case 'month':
            startDate = new Date(now.getFullYear(), now.getMonth(), 1);
            endDate = new Date(now.getFullYear(), now.getMonth() + 1, 0);
            break;
        case 'trimester':
            const quarter = Math.floor(now.getMonth() / 3);
            startDate = new Date(now.getFullYear(), quarter * 3, 1);
            endDate = new Date(now.getFullYear(), quarter * 3 + 3, 0);
            break;
        case 'semester':
            const half = now.getMonth() < 6 ? 0 : 6;
            startDate = new Date(now.getFullYear(), half, 1);
            endDate = new Date(now.getFullYear(), half + 6, 0);
            break;
        case 'year':
            startDate = new Date(now.getFullYear(), 0, 1);
            endDate = new Date(now.getFullYear(), 11, 31);
            break;
        case 'custom':
            return {
                startDate: txCustomStartDate,
                endDate: txCustomEndDate
            };
        default:
            startDate = new Date(now.getFullYear(), now.getMonth(), 1);
            endDate = new Date(now.getFullYear(), now.getMonth() + 1, 0);
    }
    
    return {
        startDate: startDate.toISOString().split('T')[0],
        endDate: endDate.toISOString().split('T')[0]
    };
}

async function renderTransactions() {
    const content = document.getElementById('main-content');
    content.innerHTML = '<div class="flex justify-center items-center h-64"><div class="spinner"></div></div>';
    
    try {
        const dates = getTxPeriodDates(txCurrentPeriod);
        
        const [transactions, categories, branches, partners] = await Promise.all([
            apiRequest(`transactions.php?startDate=${dates.startDate}&endDate=${dates.endDate}`),
            apiRequest('categories.php'),
            apiRequest('branches.php'),
            apiRequest('partners.php')
        ]);
        
        transactionsData = transactions;
        categoriesData = categories;
        branchesData = branches;
        partnersData = partners;
        
        applyFilters();
        renderTransactionsContent();
        
    } catch (error) {
        content.innerHTML = `<div class="empty-state"><p>Erro ao carregar lançamentos: ${error.message}</p></div>`;
    }
}

function applyFilters() {
    filteredTransactions = transactionsData.filter(t => {
        if (activeFilters.type && t.type !== activeFilters.type) return false;
        if (activeFilters.paymentMethod && t.payment_method !== activeFilters.paymentMethod) return false;
        if (activeFilters.branchId && t.branch_id !== activeFilters.branchId) return false;
        if (activeFilters.categoryId && t.category_id !== activeFilters.categoryId) return false;
        if (activeFilters.description && !t.description.toLowerCase().includes(activeFilters.description.toLowerCase())) return false;
        if (activeFilters.minAmount && parseFloat(t.amount) < parseFloat(activeFilters.minAmount)) return false;
        if (activeFilters.maxAmount && parseFloat(t.amount) > parseFloat(activeFilters.maxAmount)) return false;
        return true;
    });
    txCurrentPage = 1;
}

function renderTransactionsContent() {
    const content = document.getElementById('main-content');
    const totalPages = Math.ceil(filteredTransactions.length / txItemsPerPage);
    const startIndex = (txCurrentPage - 1) * txItemsPerPage;
    const endIndex = startIndex + txItemsPerPage;
    const pageData = filteredTransactions.slice(startIndex, endIndex);
    
    content.innerHTML = `
        <!-- Period Filter -->
        <div class="bg-white dark:bg-zinc-800 rounded-lg shadow p-4 mb-4 border border-gray-200 dark:border-zinc-700">
            <div class="flex flex-wrap gap-2 items-center mb-3">
                <span class="text-sm font-medium text-gray-700 dark:text-gray-300 mr-2">Período:</span>
                <button onclick="setTransactionPeriod('day')" class="px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${txCurrentPeriod === 'day' ? 'bg-zinc-800 text-white' : 'bg-white text-black border border-gray-300'}" data-testid="filter-day">Dia</button>
                <button onclick="setTransactionPeriod('week')" class="px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${txCurrentPeriod === 'week' ? 'bg-zinc-800 text-white' : 'bg-white text-black border border-gray-300'}" data-testid="filter-week">Semana</button>
                <button onclick="setTransactionPeriod('biweekly')" class="px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${txCurrentPeriod === 'biweekly' ? 'bg-zinc-800 text-white' : 'bg-white text-black border border-gray-300'}" data-testid="filter-biweekly">Quinzena</button>
                <button onclick="setTransactionPeriod('month')" class="px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${txCurrentPeriod === 'month' ? 'bg-zinc-800 text-white' : 'bg-white text-black border border-gray-300'}" data-testid="filter-month">Mês</button>
                <button onclick="setTransactionPeriod('trimester')" class="px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${txCurrentPeriod === 'trimester' ? 'bg-zinc-800 text-white' : 'bg-white text-black border border-gray-300'}" data-testid="filter-trimester">Trimestre</button>
                <button onclick="setTransactionPeriod('semester')" class="px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${txCurrentPeriod === 'semester' ? 'bg-zinc-800 text-white' : 'bg-white text-black border border-gray-300'}" data-testid="filter-semester">Semestre</button>
                <button onclick="setTransactionPeriod('year')" class="px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${txCurrentPeriod === 'year' ? 'bg-zinc-800 text-white' : 'bg-white text-black border border-gray-300'}" data-testid="filter-year">Anual</button>
            </div>
            <div class="flex flex-wrap gap-2 items-center">
                <span class="text-sm font-medium text-gray-700 dark:text-gray-300 mr-2">Personalizado:</span>
                <input type="date" id="tx-custom-start" class="px-2 py-1 text-sm border border-gray-300 dark:border-zinc-600 rounded bg-white dark:bg-zinc-700 text-gray-900 dark:text-white" value="${txCustomStartDate}">
                <span class="text-sm text-gray-500">até</span>
                <input type="date" id="tx-custom-end" class="px-2 py-1 text-sm border border-gray-300 dark:border-zinc-600 rounded bg-white dark:bg-zinc-700 text-gray-900 dark:text-white" value="${txCustomEndDate}">
                <button onclick="setTxCustomDates()" class="px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${txCurrentPeriod === 'custom' ? 'bg-zinc-800 text-white' : 'bg-white text-black border border-gray-300'}" data-testid="filter-custom">Filtrar</button>
            </div>
        </div>

        <!-- Filters -->
        <div class="bg-white dark:bg-zinc-800 rounded-lg shadow p-4 mb-4 border border-gray-200 dark:border-zinc-700">
            <div class="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-7 gap-3">
                <div>
                    <label class="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">Tipo</label>
                    <select id="filter-type" onchange="updateFilter('type', 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="income" ${activeFilters.type === 'income' ? 'selected' : ''}>Entrada</option>
                        <option value="expense" ${activeFilters.type === 'expense' ? 'selected' : ''}>Saída</option>
                        <option value="partner_loan" ${activeFilters.type === 'partner_loan' ? 'selected' : ''}>Parceiro</option>
                    </select>
                </div>
                <div>
                    <label class="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">Pagamento</label>
                    <select id="filter-payment" onchange="updateFilter('paymentMethod', 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-payment">
                        <option value="">Todos</option>
                        <option value="cash" ${activeFilters.paymentMethod === 'cash' ? 'selected' : ''}>Dinheiro</option>
                        <option value="debit" ${activeFilters.paymentMethod === 'debit' ? 'selected' : ''}>Débito</option>
                        <option value="credit" ${activeFilters.paymentMethod === 'credit' ? 'selected' : ''}>Crédito</option>
                        <option value="pix" ${activeFilters.paymentMethod === 'pix' ? 'selected' : ''}>PIX</option>
                        <option value="ifood" ${activeFilters.paymentMethod === 'ifood' ? 'selected' : ''}>iFood</option>
                    </select>
                </div>
                <div>
                    <label class="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">Filial</label>
                    <select id="filter-branch" onchange="updateFilter('branchId', 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-branch">
                        <option value="">Todas</option>
                        ${branchesData.map(b => `<option value="${b.id}" ${activeFilters.branchId === b.id ? 'selected' : ''}>${b.name}</option>`).join('')}
                    </select>
                </div>
                <div>
                    <label class="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">Categoria</label>
                    <select id="filter-category" onchange="updateFilter('categoryId', 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-category">
                        <option value="">Todas</option>
                        ${categoriesData.map(c => `<option value="${c.id}" ${activeFilters.categoryId === c.id ? 'selected' : ''}>${c.name}</option>`).join('')}
                    </select>
                </div>
                <div>
                    <label class="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">Valor Mín</label>
                    <input type="number" id="filter-min-amount" step="0.01" placeholder="0,00" value="${activeFilters.minAmount}" onchange="updateFilter('minAmount', 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-min-amount">
                </div>
                <div>
                    <label class="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">Valor Máx</label>
                    <input type="number" id="filter-max-amount" step="0.01" placeholder="0,00" value="${activeFilters.maxAmount}" onchange="updateFilter('maxAmount', 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-max-amount">
                </div>
                <div>
                    <label class="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">Descrição</label>
                    <input type="text" id="filter-description" placeholder="Buscar..." value="${activeFilters.description}" onkeyup="updateFilter('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>
            <div class="mt-3 flex justify-end">
                <button onclick="clearTransactionFilters()" class="text-sm text-blue-500 hover:text-blue-700" data-testid="button-clear-filters">Limpar Filtros</button>
            </div>
        </div>
        
        <div class="flex justify-between items-center mb-4">
            <h3 class="text-lg font-semibold text-gray-800 dark:text-white">
                Lista de Lançamentos 
                <span class="text-sm font-normal text-gray-500">(${filteredTransactions.length} registros)</span>
            </h3>
            <button class="btn btn-primary" onclick="openTransactionModal()" data-testid="button-new-transaction">
                <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>
                Novo Lançamento
            </button>
        </div>
        
        <div class="card">
            <div class="table-container">
                ${pageData.length > 0 ? `
                    <table>
                        <thead>
                            <tr>
                                <th>Data</th>
                                <th>Descrição</th>
                                <th>Tipo</th>
                                <th>Valor</th>
                                <th>Pagamento</th>
                                <th>Filial</th>
                                <th>Arquivo</th>
                                <th>Ações</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${pageData.map(t => `
                                <tr data-testid="row-transaction-${t.id}">
                                    <td class="text-gray-600 dark:text-gray-300">${formatDate(t.transaction_date)}</td>
                                    <td class="font-medium text-gray-800 dark:text-white">${t.description}</td>
                                    <td>
                                        <span class="badge ${t.type === 'income' ? 'badge-income' : t.type === 'expense' ? 'badge-expense' : 'badge-pending'}">
                                            ${t.type === 'income' ? 'Entrada' : t.type === 'expense' ? 'Saída' : 'Parceiro'}
                                        </span>
                                    </td>
                                    <td class="font-medium ${t.type === 'income' ? 'text-income' : 'text-expense'}">${formatMoney(t.amount)}</td>
                                    <td class="text-gray-600 dark:text-gray-300">${formatPaymentMethod(t.payment_method)}</td>
                                    <td class="text-gray-600 dark:text-gray-300">${t.branch_name || '-'}</td>
                                    <td>
                                        ${t.file_path ? `<a href="${t.file_path}" target="_blank" class="text-blue-500 hover:text-blue-700"><svg class="w-5 h-5 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13"></path></svg></a>` : '-'}
                                    </td>
                                    <td>
                                        <div class="flex gap-2">
                                            <button class="btn btn-outline btn-sm" onclick="openTransactionModal('${t.id}')" data-testid="button-edit-transaction-${t.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="deleteTransaction('${t.id}')" data-testid="button-delete-transaction-${t.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>
                                    </td>
                                </tr>
                            `).join('')}
                        </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, filteredTransactions.length)} de ${filteredTransactions.length}
                            </div>
                            <div class="flex gap-1">
                                <button onclick="goToTransactionPage(1)" ${txCurrentPage === 1 ? 'disabled' : ''} class="px-3 py-1 rounded text-sm ${txCurrentPage === 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="goToTransactionPage(${txCurrentPage - 1})" ${txCurrentPage === 1 ? 'disabled' : ''} class="px-3 py-1 rounded text-sm ${txCurrentPage === 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">${txCurrentPage} / ${totalPages}</span>
                                <button onclick="goToTransactionPage(${txCurrentPage + 1})" ${txCurrentPage === totalPages ? 'disabled' : ''} class="px-3 py-1 rounded text-sm ${txCurrentPage === 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="goToTransactionPage(${totalPages})" ${txCurrentPage === totalPages ? 'disabled' : ''} class="px-3 py-1 rounded text-sm ${txCurrentPage === 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 class="empty-state"><p>Nenhum lançamento encontrado</p></div>'}
            </div>
        </div>
    `;
}

function setTransactionPeriod(period) {
    txCurrentPeriod = period;
    renderTransactions();
}

function setTxCustomDates() {
    const startInput = document.getElementById('tx-custom-start');
    const endInput = document.getElementById('tx-custom-end');
    if (startInput && endInput && startInput.value && endInput.value) {
        txCustomStartDate = startInput.value;
        txCustomEndDate = endInput.value;
        txCurrentPeriod = 'custom';
        renderTransactions();
    }
}

function updateFilter(key, value) {
    activeFilters[key] = value;
    applyFilters();
    renderTransactionsContent();
}

function clearTransactionFilters() {
    activeFilters = {
        type: '',
        paymentMethod: '',
        branchId: '',
        categoryId: '',
        description: '',
        minAmount: '',
        maxAmount: ''
    };
    applyFilters();
    renderTransactionsContent();
}

function goToTransactionPage(page) {
    const totalPages = Math.ceil(filteredTransactions.length / txItemsPerPage);
    if (page >= 1 && page <= totalPages) {
        txCurrentPage = page;
        renderTransactionsContent();
    }
}

function formatPaymentMethod(method) {
    const methods = {
        cash: 'Dinheiro',
        debit: 'Débito',
        credit: 'Crédito',
        pix: 'PIX',
        ifood: 'iFood'
    };
    return methods[method] || '-';
}

function openTransactionModal(id = null) {
    const transaction = id ? transactionsData.find(t => t.id === id) : null;
    
    openModal(`
        <div class="p-6">
            <h3 class="text-lg font-semibold mb-4 text-gray-800 dark:text-white">
                ${transaction ? 'Editar Lançamento' : 'Novo Lançamento'}
            </h3>
            <form id="transaction-form" onsubmit="saveTransaction(event, ${id ? `'${id}'` : null})">
                <div class="form-group">
                    <label class="form-label">Tipo</label>
                    <select id="tx-type" class="form-select" required data-testid="select-type">
                        <option value="income" ${transaction?.type === 'income' ? 'selected' : ''}>Entrada</option>
                        <option value="expense" ${transaction?.type === 'expense' ? 'selected' : ''}>Saída</option>
                        <option value="partner_loan" ${transaction?.type === 'partner_loan' ? 'selected' : ''}>Empréstimo Parceiro</option>
                    </select>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Descrição</label>
                    <input type="text" id="tx-description" class="form-input" required value="${transaction?.description || ''}" data-testid="input-description">
                </div>
                
                <div class="form-group">
                    <label class="form-label">Valor (R$)</label>
                    <input type="number" id="tx-amount" class="form-input" step="0.01" min="0" required value="${transaction?.amount || ''}" data-testid="input-amount">
                </div>
                
                <div class="form-group">
                    <label class="form-label">Data</label>
                    <input type="date" id="tx-date" class="form-input" required value="${transaction?.transaction_date || new Date().toISOString().split('T')[0]}" data-testid="input-date">
                </div>
                
                <div class="form-group">
                    <label class="form-label">Forma de Pagamento</label>
                    <select id="tx-payment-method" class="form-select" data-testid="select-payment-method">
                        <option value="">Selecione...</option>
                        <option value="cash" ${transaction?.payment_method === 'cash' ? 'selected' : ''}>Dinheiro</option>
                        <option value="debit" ${transaction?.payment_method === 'debit' ? 'selected' : ''}>Débito</option>
                        <option value="credit" ${transaction?.payment_method === 'credit' ? 'selected' : ''}>Crédito</option>
                        <option value="pix" ${transaction?.payment_method === 'pix' ? 'selected' : ''}>PIX</option>
                        <option value="ifood" ${transaction?.payment_method === 'ifood' ? 'selected' : ''}>iFood</option>
                    </select>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Filial</label>
                    <select id="tx-branch" class="form-select">
                        <option value="">Selecione...</option>
                        ${branchesData.map(b => `<option value="${b.id}" ${transaction?.branch_id == b.id ? 'selected' : ''}>${b.name}</option>`).join('')}
                    </select>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Categoria</label>
                    <select id="tx-category" class="form-select">
                        <option value="">Selecione...</option>
                        ${categoriesData.map(c => `<option value="${c.id}" ${transaction?.category_id == c.id ? 'selected' : ''}>${c.name}</option>`).join('')}
                    </select>
                </div>
                
                <div class="form-group" id="partner-group" style="display: none;">
                    <label class="form-label">Parceiro</label>
                    <select id="tx-partner" class="form-select">
                        <option value="">Selecione...</option>
                        ${partnersData.map(p => `<option value="${p.id}" ${transaction?.partner_id == p.id ? 'selected' : ''}>${p.name}</option>`).join('')}
                    </select>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Arquivo (NF/Comprovante)</label>
                    <input type="file" id="tx-file" accept=".pdf,.jpg,.jpeg,.png" class="form-input" data-testid="input-file">
                    ${transaction?.file_path ? `<p class="text-sm text-gray-500 mt-1">Arquivo atual: <a href="${transaction.file_path}" target="_blank" class="text-blue-500">Ver arquivo</a></p>` : ''}
                </div>
                
                <div class="form-group">
                    <label class="form-label">Observações</label>
                    <textarea id="tx-notes" class="form-textarea" rows="2">${transaction?.notes || ''}</textarea>
                </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>
    `);
    
    const typeSelect = document.getElementById('tx-type');
    const partnerGroup = document.getElementById('partner-group');
    
    function togglePartnerField() {
        partnerGroup.style.display = typeSelect.value === 'partner_loan' ? 'block' : 'none';
    }
    
    typeSelect.addEventListener('change', togglePartnerField);
    togglePartnerField();
}

async function saveTransaction(event, id = null) {
    event.preventDefault();
    
    const fileInput = document.getElementById('tx-file');
    const file = fileInput.files[0];
    
    if (file) {
        const formData = new FormData();
        formData.append('type', document.getElementById('tx-type').value);
        formData.append('description', document.getElementById('tx-description').value);
        formData.append('amount', document.getElementById('tx-amount').value);
        formData.append('date', document.getElementById('tx-date').value);
        formData.append('paymentMethod', document.getElementById('tx-payment-method').value || '');
        formData.append('branchId', document.getElementById('tx-branch').value || '');
        formData.append('categoryId', document.getElementById('tx-category').value || '');
        formData.append('partnerId', document.getElementById('tx-partner').value || '');
        formData.append('notes', document.getElementById('tx-notes').value || '');
        formData.append('file', file);
        if (id) formData.append('id', id);
        
        try {
            const response = await fetch(`api/transactions.php${id ? `?id=${id}` : ''}`, {
                method: id ? 'POST' : 'POST',
                credentials: 'include',
                body: formData
            });
            const result = await response.json();
            
            if (result.error) {
                showToast(result.error, 'error');
            } else {
                showToast(id ? 'Lançamento atualizado com sucesso!' : 'Lançamento criado com sucesso!');
                closeModal();
                renderTransactions();
            }
        } catch (error) {
            showToast(error.message, 'error');
        }
    } else {
        const data = {
            type: document.getElementById('tx-type').value,
            description: document.getElementById('tx-description').value,
            amount: parseFloat(document.getElementById('tx-amount').value),
            date: document.getElementById('tx-date').value,
            paymentMethod: document.getElementById('tx-payment-method').value || null,
            branchId: document.getElementById('tx-branch').value || null,
            categoryId: document.getElementById('tx-category').value || null,
            partnerId: document.getElementById('tx-partner').value || null,
            notes: document.getElementById('tx-notes').value || null
        };
        
        try {
            if (id) {
                await apiRequest(`transactions.php?id=${id}`, 'PUT', data);
                showToast('Lançamento atualizado com sucesso!');
            } else {
                await apiRequest('transactions.php', 'POST', data);
                showToast('Lançamento criado com sucesso!');
            }
            closeModal();
            renderTransactions();
        } catch (error) {
            showToast(error.message, 'error');
        }
    }
}

async function deleteTransaction(id) {
    if (!confirm('Tem certeza que deseja excluir este lançamento?')) return;
    
    try {
        await apiRequest(`transactions.php?id=${id}`, 'DELETE');
        showToast('Lançamento excluído com sucesso!');
        renderTransactions();
    } catch (error) {
        showToast(error.message, 'error');
    }
}
