// Bills Page
let billsData = [];
let filteredBills = [];
let billsCategoriesData = [];
let billsBranchesData = [];

// Pagination
let billsCurrentPage = 1;
const billsItemsPerPage = 20;

// Filters
let billsActiveFilters = {
    status: '',
    branchId: '',
    categoryId: '',
    description: '',
    recurrence: '',
    minAmount: '',
    maxAmount: ''
};

// Period filter
let billsCurrentPeriod = 'month';
let billsCustomStartDate = '';
let billsCustomEndDate = '';

function getBillsPeriodDates(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: billsCustomStartDate,
                endDate: billsCustomEndDate
            };
        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 renderBills() {
    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 = getBillsPeriodDates(billsCurrentPeriod);
        
        const [bills, categories, branches] = await Promise.all([
            apiRequest(`bills.php?startDate=${dates.startDate}&endDate=${dates.endDate}`),
            apiRequest('categories.php'),
            apiRequest('branches.php')
        ]);
        
        billsData = bills;
        billsCategoriesData = categories;
        billsBranchesData = branches;
        
        applyBillsFilters();
        renderBillsContent();
        
    } catch (error) {
        content.innerHTML = `<div class="empty-state"><p>Erro ao carregar boletos: ${error.message}</p></div>`;
    }
}

function applyBillsFilters() {
    filteredBills = billsData.filter(b => {
        if (billsActiveFilters.status && b.status !== billsActiveFilters.status) return false;
        if (billsActiveFilters.branchId && b.branch_id !== billsActiveFilters.branchId) return false;
        if (billsActiveFilters.categoryId && b.category_id !== billsActiveFilters.categoryId) return false;
        if (billsActiveFilters.description && !b.description.toLowerCase().includes(billsActiveFilters.description.toLowerCase())) return false;
        if (billsActiveFilters.recurrence) {
            if (billsActiveFilters.recurrence === 'none' && b.recurrence && b.recurrence !== 'none') return false;
            if (billsActiveFilters.recurrence !== 'none' && b.recurrence !== billsActiveFilters.recurrence) return false;
        }
        if (billsActiveFilters.minAmount && parseFloat(b.amount) < parseFloat(billsActiveFilters.minAmount)) return false;
        if (billsActiveFilters.maxAmount && parseFloat(b.amount) > parseFloat(billsActiveFilters.maxAmount)) return false;
        return true;
    });
    billsCurrentPage = 1;
}

function renderBillsContent() {
    const content = document.getElementById('main-content');
    const totalPages = Math.ceil(filteredBills.length / billsItemsPerPage);
    const startIndex = (billsCurrentPage - 1) * billsItemsPerPage;
    const endIndex = startIndex + billsItemsPerPage;
    const pageData = filteredBills.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="setBillsPeriod('day')" class="px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${billsCurrentPeriod === 'day' ? 'bg-zinc-800 text-white' : 'bg-white text-black border border-gray-300'}" data-testid="filter-day">Dia</button>
                <button onclick="setBillsPeriod('week')" class="px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${billsCurrentPeriod === 'week' ? 'bg-zinc-800 text-white' : 'bg-white text-black border border-gray-300'}" data-testid="filter-week">Semana</button>
                <button onclick="setBillsPeriod('biweekly')" class="px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${billsCurrentPeriod === 'biweekly' ? 'bg-zinc-800 text-white' : 'bg-white text-black border border-gray-300'}" data-testid="filter-biweekly">Quinzena</button>
                <button onclick="setBillsPeriod('month')" class="px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${billsCurrentPeriod === 'month' ? 'bg-zinc-800 text-white' : 'bg-white text-black border border-gray-300'}" data-testid="filter-month">Mês</button>
                <button onclick="setBillsPeriod('trimester')" class="px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${billsCurrentPeriod === 'trimester' ? 'bg-zinc-800 text-white' : 'bg-white text-black border border-gray-300'}" data-testid="filter-trimester">Trimestre</button>
                <button onclick="setBillsPeriod('semester')" class="px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${billsCurrentPeriod === 'semester' ? 'bg-zinc-800 text-white' : 'bg-white text-black border border-gray-300'}" data-testid="filter-semester">Semestre</button>
                <button onclick="setBillsPeriod('year')" class="px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${billsCurrentPeriod === '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="bills-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="${billsCustomStartDate}">
                <span class="text-sm text-gray-500">até</span>
                <input type="date" id="bills-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="${billsCustomEndDate}">
                <button onclick="setBillsCustomDates()" class="px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${billsCurrentPeriod === '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">Status</label>
                    <select id="bills-filter-status" onchange="updateBillsFilter('status', 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-status">
                        <option value="">Todos</option>
                        <option value="pending" ${billsActiveFilters.status === 'pending' ? 'selected' : ''}>Pendente</option>
                        <option value="paid" ${billsActiveFilters.status === 'paid' ? 'selected' : ''}>Pago</option>
                        <option value="overdue" ${billsActiveFilters.status === 'overdue' ? 'selected' : ''}>Vencido</option>
                    </select>
                </div>
                <div>
                    <label class="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">Recorrência</label>
                    <select id="bills-filter-recurrence" onchange="updateBillsFilter('recurrence', 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-recurrence">
                        <option value="">Todos</option>
                        <option value="none" ${billsActiveFilters.recurrence === 'none' ? 'selected' : ''}>Não recorrente</option>
                        <option value="weekly" ${billsActiveFilters.recurrence === 'weekly' ? 'selected' : ''}>Semanal</option>
                        <option value="monthly" ${billsActiveFilters.recurrence === 'monthly' ? 'selected' : ''}>Mensal</option>
                    </select>
                </div>
                <div>
                    <label class="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">Filial</label>
                    <select id="bills-filter-branch" onchange="updateBillsFilter('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>
                        ${billsBranchesData.map(b => `<option value="${b.id}" ${billsActiveFilters.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="bills-filter-category" onchange="updateBillsFilter('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>
                        ${billsCategoriesData.filter(c => c.type === 'expense').map(c => `<option value="${c.id}" ${billsActiveFilters.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="bills-filter-min-amount" step="0.01" placeholder="0,00" value="${billsActiveFilters.minAmount}" onchange="updateBillsFilter('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="bills-filter-max-amount" step="0.01" placeholder="0,00" value="${billsActiveFilters.maxAmount}" onchange="updateBillsFilter('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="bills-filter-description" placeholder="Buscar..." value="${billsActiveFilters.description}" onkeyup="updateBillsFilter('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="clearBillsFilters()" 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 Boletos 
                <span class="text-sm font-normal text-gray-500">(${filteredBills.length} registros)</span>
            </h3>
            <button class="btn btn-primary" onclick="openBillModal()" data-testid="button-new-bill">
                <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 Boleto
            </button>
        </div>
        
        <div class="card">
            <div class="table-container">
                ${pageData.length > 0 ? `
                    <table>
                        <thead>
                            <tr>
                                <th>Vencimento</th>
                                <th>Descrição</th>
                                <th>Valor</th>
                                <th>Status</th>
                                <th>Recorrente</th>
                                <th>Filial</th>
                                <th>Arquivo</th>
                                <th>Ações</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${pageData.map(b => `
                                <tr data-testid="row-bill-${b.id}">
                                    <td class="text-gray-600 dark:text-gray-300">${formatDate(b.due_date)}</td>
                                    <td class="font-medium text-gray-800 dark:text-white">${b.description}</td>
                                    <td class="font-medium text-expense">${formatMoney(b.amount)}</td>
                                    <td>
                                        <span class="badge badge-${b.status}">
                                            ${formatBillStatus(b.status)}
                                        </span>
                                    </td>
                                    <td class="text-gray-600 dark:text-gray-300">
                                        ${b.recurrence && b.recurrence !== 'none' ? formatRecurringType(b.recurrence) : 'Não'}
                                    </td>
                                    <td class="text-gray-600 dark:text-gray-300">${b.branch_name || '-'}</td>
                                    <td>
                                        ${b.file_path ? `<a href="${b.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">
                                            ${b.status === 'pending' ? `
                                                <button class="btn btn-primary btn-sm" onclick="markBillAsPaid('${b.id}')" data-testid="button-pay-bill-${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="M5 13l4 4L19 7"/></svg>
                                                </button>
                                            ` : ''}
                                            <button class="btn btn-outline btn-sm" onclick="openBillModal('${b.id}')" data-testid="button-edit-bill-${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="deleteBill('${b.id}')" data-testid="button-delete-bill-${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>
                                    </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, filteredBills.length)} de ${filteredBills.length}
                            </div>
                            <div class="flex gap-1">
                                <button onclick="goToBillsPage(1)" ${billsCurrentPage === 1 ? 'disabled' : ''} class="px-3 py-1 rounded text-sm ${billsCurrentPage === 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="goToBillsPage(${billsCurrentPage - 1})" ${billsCurrentPage === 1 ? 'disabled' : ''} class="px-3 py-1 rounded text-sm ${billsCurrentPage === 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">${billsCurrentPage} / ${totalPages}</span>
                                <button onclick="goToBillsPage(${billsCurrentPage + 1})" ${billsCurrentPage === totalPages ? 'disabled' : ''} class="px-3 py-1 rounded text-sm ${billsCurrentPage === 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="goToBillsPage(${totalPages})" ${billsCurrentPage === totalPages ? 'disabled' : ''} class="px-3 py-1 rounded text-sm ${billsCurrentPage === 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 boleto encontrado</p></div>'}
            </div>
        </div>
    `;
}

function setBillsPeriod(period) {
    billsCurrentPeriod = period;
    renderBills();
}

function setBillsCustomDates() {
    const startInput = document.getElementById('bills-custom-start');
    const endInput = document.getElementById('bills-custom-end');
    if (startInput && endInput && startInput.value && endInput.value) {
        billsCustomStartDate = startInput.value;
        billsCustomEndDate = endInput.value;
        billsCurrentPeriod = 'custom';
        renderBills();
    }
}

function updateBillsFilter(key, value) {
    billsActiveFilters[key] = value;
    applyBillsFilters();
    renderBillsContent();
}

function clearBillsFilters() {
    billsActiveFilters = {
        status: '',
        branchId: '',
        categoryId: '',
        description: '',
        recurrence: '',
        minAmount: '',
        maxAmount: ''
    };
    applyBillsFilters();
    renderBillsContent();
}

function goToBillsPage(page) {
    const totalPages = Math.ceil(filteredBills.length / billsItemsPerPage);
    if (page >= 1 && page <= totalPages) {
        billsCurrentPage = page;
        renderBillsContent();
    }
}

function formatBillStatus(status) {
    const statuses = {
        pending: 'Pendente',
        paid: 'Pago',
        overdue: 'Vencido',
        cancelled: 'Cancelado'
    };
    return statuses[status] || status;
}

function formatRecurringType(type) {
    const types = {
        weekly: 'Semanal',
        biweekly: 'Quinzenal',
        monthly: 'Mensal',
        yearly: 'Anual'
    };
    return types[type] || type;
}

function openBillModal(id = null) {
    const bill = id ? billsData.find(b => b.id === id) : null;
    const hasRecurrence = bill?.recurrence && bill.recurrence !== 'none';
    
    openModal(`
        <div class="p-6">
            <h3 class="text-lg font-semibold mb-4 text-gray-800 dark:text-white">
                ${bill ? 'Editar Boleto' : 'Novo Boleto'}
            </h3>
            <form id="bill-form" onsubmit="saveBill(event, ${id ? `'${id}'` : null})">
                <div class="form-group">
                    <label class="form-label">Descrição</label>
                    <input type="text" id="bill-description" class="form-input" required value="${bill?.description || ''}" data-testid="input-description">
                </div>
                
                <div class="form-group">
                    <label class="form-label">Valor (R$)</label>
                    <input type="number" id="bill-amount" class="form-input" step="0.01" min="0" required value="${bill?.amount || ''}" data-testid="input-amount">
                </div>
                
                <div class="form-group">
                    <label class="form-label">Vencimento</label>
                    <input type="date" id="bill-due-date" class="form-input" required value="${bill?.due_date || ''}" data-testid="input-due-date">
                </div>
                
                <div class="form-group">
                    <label class="form-label">Status</label>
                    <select id="bill-status" class="form-select" data-testid="select-status">
                        <option value="pending" ${bill?.status === 'pending' ? 'selected' : ''}>Pendente</option>
                        <option value="paid" ${bill?.status === 'paid' ? 'selected' : ''}>Pago</option>
                        <option value="overdue" ${bill?.status === 'overdue' ? 'selected' : ''}>Vencido</option>
                    </select>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Recorrência</label>
                    <select id="bill-recurrence" class="form-select">
                        <option value="none" ${!hasRecurrence ? 'selected' : ''}>Não recorrente</option>
                        <option value="weekly" ${bill?.recurrence === 'weekly' ? 'selected' : ''}>Semanal</option>
                        <option value="monthly" ${bill?.recurrence === 'monthly' ? 'selected' : ''}>Mensal</option>
                    </select>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Filial</label>
                    <select id="bill-branch" class="form-select">
                        <option value="">Selecione...</option>
                        ${billsBranchesData.map(b => `<option value="${b.id}" ${bill?.branch_id == b.id ? 'selected' : ''}>${b.name}</option>`).join('')}
                    </select>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Categoria</label>
                    <select id="bill-category" class="form-select">
                        <option value="">Selecione...</option>
                        ${billsCategoriesData.filter(c => c.type === 'expense').map(c => `<option value="${c.id}" ${bill?.category_id == c.id ? 'selected' : ''}>${c.name}</option>`).join('')}
                    </select>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Arquivo (Boleto)</label>
                    <input type="file" id="bill-file" accept=".pdf,.jpg,.jpeg,.png" class="form-input" data-testid="input-file">
                    ${bill?.file_path ? `<p class="text-sm text-gray-500 mt-1">Arquivo atual: <a href="${bill.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="bill-notes" class="form-textarea" rows="2">${bill?.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>
    `);
}

async function saveBill(event, id = null) {
    event.preventDefault();
    
    const fileInput = document.getElementById('bill-file');
    const file = fileInput.files[0];
    const recurrence = document.getElementById('bill-recurrence').value;
    
    if (file) {
        const formData = new FormData();
        formData.append('description', document.getElementById('bill-description').value);
        formData.append('amount', document.getElementById('bill-amount').value);
        formData.append('dueDate', document.getElementById('bill-due-date').value);
        formData.append('status', document.getElementById('bill-status').value);
        formData.append('recurrence', recurrence !== 'none' ? recurrence : '');
        formData.append('branchId', document.getElementById('bill-branch').value || '');
        formData.append('categoryId', document.getElementById('bill-category').value || '');
        formData.append('notes', document.getElementById('bill-notes').value || '');
        formData.append('file', file);
        if (id) formData.append('id', id);
        
        try {
            const response = await fetch(`api/bills.php${id ? `?id=${id}` : ''}`, {
                method: 'POST',
                credentials: 'include',
                body: formData
            });
            const result = await response.json();
            
            if (result.error) {
                showToast(result.error, 'error');
            } else {
                showToast(id ? 'Boleto atualizado com sucesso!' : 'Boleto criado com sucesso!');
                closeModal();
                renderBills();
            }
        } catch (error) {
            showToast(error.message, 'error');
        }
    } else {
        const data = {
            description: document.getElementById('bill-description').value,
            amount: parseFloat(document.getElementById('bill-amount').value),
            dueDate: document.getElementById('bill-due-date').value,
            status: document.getElementById('bill-status').value,
            recurrence: recurrence !== 'none' ? recurrence : null,
            branchId: document.getElementById('bill-branch').value || null,
            categoryId: document.getElementById('bill-category').value || null,
            notes: document.getElementById('bill-notes').value || null
        };
        
        try {
            if (id) {
                await apiRequest(`bills.php?id=${id}`, 'PUT', data);
                showToast('Boleto atualizado com sucesso!');
            } else {
                await apiRequest('bills.php', 'POST', data);
                showToast('Boleto criado com sucesso!');
            }
            closeModal();
            renderBills();
        } catch (error) {
            showToast(error.message, 'error');
        }
    }
}

async function markBillAsPaid(id) {
    const bill = billsData.find(b => b.id === id);
    if (!bill) return;
    
    try {
        await apiRequest(`bills.php?id=${id}`, 'PUT', {
            description: bill.description,
            amount: bill.amount,
            dueDate: bill.due_date,
            recurrence: bill.recurrence,
            branchId: bill.branch_id,
            categoryId: bill.category_id,
            notes: bill.notes,
            status: 'paid'
        });
        showToast('Boleto marcado como pago!');
        renderBills();
    } catch (error) {
        showToast(error.message, 'error');
    }
}

async function deleteBill(id) {
    if (!confirm('Tem certeza que deseja excluir este boleto?')) return;
    
    try {
        await apiRequest(`bills.php?id=${id}`, 'DELETE');
        showToast('Boleto excluído com sucesso!');
        renderBills();
    } catch (error) {
        showToast(error.message, 'error');
    }
}
