// resources/js/expenseTableAjax.js
import { buildEndpoint } from './urlBuilder';

document.addEventListener('DOMContentLoaded', function() {
    const expenseTable = $('#expenseTable');
    
    if (!expenseTable.length) {
        return;
    }
    
    const dateFromInput = document.getElementById('filterDateFrom');
    const dateToInput = document.getElementById('filterDateTo');
    const categorySelect = document.getElementById('filterCategory');
    const statusSelect = document.getElementById('filterStatus');
    const applyFiltersBtn = document.getElementById('applyFilters');
    
    let dataTable = null;
    
    // Cargar categorías para el filtro
    fetch(buildEndpoint('admin-fit/expense/categories'), {
        headers: { 'Accept': 'application/json' }
    })
        .then(response => response.json())
        .then(data => {
            if (data.data && categorySelect) {
                data.data.forEach(cat => {
                    const option = document.createElement('option');
                    option.value = cat.id;
                    option.textContent = cat.name;
                    categorySelect.appendChild(option);
                });
            }
        })
        .catch(error => console.error('Error cargando categorías:', error));
    
    dataTable = expenseTable.DataTable({
        processing: true,
        serverSide: true,
        scrollX: true,
        autoWidth: false,
        ajax: {
            url: buildEndpoint('admin-fit/expense/json'),
            type: 'GET',
            data: function(d) {
                d.date_from = dateFromInput?.value || null;
                d.date_to = dateToInput?.value || null;
                d.category_id = categorySelect?.value || null;
                d.status = statusSelect?.value || null;
            }
        },
        columns: [
            { data: 'id', name: 'id', className: 'text-center', width: '5%' },
            { data: 'expense_date_formatted', name: 'expense_date', className: 'text-center', width: '10%' },
            { 
                data: null, 
                name: 'category_name', 
                className: 'text-center',
                width: '12%',
                render: function(data) {
                    const color = data.category_color || '#6c757d';
                    return `<span class="badge" style="background-color: ${color}">${data.category_name}</span>`;
                }
            },
            { data: 'description', name: 'description', className: 'text-start' },
            { data: 'amount_formatted', name: 'amount', className: 'text-end', width: '12%' },
            { data: 'status_badge', name: 'status', className: 'text-center', width: '10%' },
            {
                data: null,
                name: 'actions',
                orderable: false,
                searchable: false,
                className: 'text-center',
                width: '10%',
                render: function(data) {
                    return `
                        <div class="d-flex justify-content-center gap-2">
                            <a href="${buildEndpoint(`admin-fit/expense/${data.id}/edit`)}" class="btn btn-sm btn-warning">
                                <i class="bi bi-pencil"></i>
                            </a>
                            <button type="button" class="btn btn-sm btn-danger btn-delete-expense" data-id="${data.id}">
                                <i class="bi bi-trash"></i>
                            </button>
                        </div>
                    `;
                }
            }
        ],
        order: [[1, 'desc']],
        language: {
            processing: 'Procesando...',
            search: 'Buscar:',
            lengthMenu: 'Mostrar _MENU_ registros',
            info: 'Mostrando registros del _START_ al _END_ de un total de _TOTAL_ registros',
            infoEmpty: 'Mostrando registros del 0 al 0 de un total de 0 registros',
            infoFiltered: '(filtrado de un total de _MAX_ registros)',
            loadingRecords: 'Cargando...',
            zeroRecords: 'No se encontraron resultados',
            emptyTable: 'Ningún dato disponible en esta tabla',
            paginate: {
                first: 'Primero',
                previous: 'Anterior',
                next: 'Siguiente',
                last: 'Último'
            }
        }
    });
    
    applyFiltersBtn?.addEventListener('click', function() {
        dataTable.ajax.reload();
        const modal = bootstrap.Modal.getInstance(document.getElementById('filterModal'));
        if (modal) modal.hide();
    });
    
    // Eliminar gasto
    expenseTable.on('click', '.btn-delete-expense', async function() {
        const expenseId = $(this).data('id');
        const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
        
        const result = await Swal.fire({
            title: '¿Eliminar gasto?',
            text: 'Esta acción no se puede deshacer.',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Sí, eliminar',
            cancelButtonText: 'Cancelar'
        });
        
        if (!result.isConfirmed) return;
        
        try {
            const response = await fetch(buildEndpoint(`admin-fit/expense/${expenseId}`), {
                method: 'DELETE',
                headers: {
                    'Accept': 'application/json',
                    'X-CSRF-TOKEN': csrfToken
                }
            });
            
            const data = await response.json();
            
            if (!response.ok || !data.success) {
                throw new Error(data.message || 'Error al eliminar');
            }
            
            Swal.fire('Eliminado', 'Gasto eliminado correctamente', 'success');
            dataTable.ajax.reload();
        } catch (error) {
            Swal.fire('Error', error.message, 'error');
        }
    });
});