// Expenses Management JavaScript

$(document).ready(function() {
    // Set today's date as default
    $('#expenseDate').val(new Date().toISOString().split('T')[0]);

    // Open Expenses Modal
    $('#btnExpenses').on('click', function() {
        $('#expensesModal').modal('show');
        updateSummary();
    });

    // Calculate and display amount as user types
    $('#expenseAmount').on('input', function() {
        let amount = parseFloat($(this).val()) || 0;
        $('#expenseAmountDisplay').text('₹' + amount.toFixed(2));
    });

    // Update summary when fields change
    $('#expenseDate, #expenseCategory').on('change', function() {
        updateSummary();
    });

    // Save Expense
    $('#btnSaveExpense').on('click', function() {
        saveExpense();
    });

    // Reset form when modal closes
    $('#expensesModal').on('hidden.bs.modal', function() {
        resetExpenseForm();
    });
});

function updateSummary() {
    const date = $('#expenseDate').val();
    const category = $('#expenseCategory').val();
    
    if (date) {
        const dateObj = new Date(date);
        const formattedDate = dateObj.toLocaleDateString('en-IN', { 
            day: '2-digit', 
            month: 'short', 
            year: 'numeric' 
        });
        $('#summaryDate').text(formattedDate);
    } else {
        $('#summaryDate').text('-');
    }
    
    $('#summaryCategory').text(category || '-');
}

function saveExpense() {
    // Get form data
    const expenseDate = $('#expenseDate').val();
    const expenseCategory = $('#expenseCategory').val();
    const expenseDescription = $('#expenseDescription').val();
    const amount = parseFloat($('#expenseAmount').val());
    const paymentMode = $('#expensePaymentMode').val();
    const reference = $('#expenseReference').val();

    // Validate
    if (!expenseDate || !expenseCategory || !amount || amount <= 0) {
        alert('Please fill all required fields');
        return;
    }

    // Disable button to prevent double submission
    $('#btnSaveExpense').prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Saving...');

    // AJAX request to save expense
    $.ajax({
        url: 'api/add-expense.php',
        type: 'POST',
        data: {
            expenseDate: expenseDate,
            expenseCategory: expenseCategory,
            expenseDescription: expenseDescription,
            amount: amount,
            paymentMode: paymentMode,
            reference: reference
        },
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                // Show success message
                showNotification('Success', response.message, 'success');
                
                // Close modal and reset form
                $('#expensesModal').modal('hide');
                resetExpenseForm();
            } else {
                showNotification('Error', response.message, 'error');
            }
        },
        error: function(xhr, status, error) {
            showNotification('Error', 'Failed to save expense: ' + error, 'error');
        },
        complete: function() {
            // Re-enable button
            $('#btnSaveExpense').prop('disabled', false).html('<i class="fas fa-save"></i> Save Expense');
        }
    });
}

function resetExpenseForm() {
    $('#expenseDate').val(new Date().toISOString().split('T')[0]);
    $('#expenseCategory').val('');
    $('#expenseDescription').val('');
    $('#expenseAmount').val('');
    $('#expensePaymentMode').val('Cash');
    $('#expenseReference').val('');
    $('#expenseAmountDisplay').text('₹0.00');
    updateSummary();
}

function showNotification(title, message, type) {
    // Simple notification - you can enhance this with toast libraries
    const icon = type === 'success' ? 'check-circle' : 'exclamation-circle';
    const color = type === 'success' ? 'success' : 'danger';
    
    const notification = `
        <div class="alert alert-${color} alert-dismissible fade show" role="alert" style="position: fixed; top: 80px; right: 20px; z-index: 9999; min-width: 300px;">
            <i class="fas fa-${icon}"></i> <strong>${title}:</strong> ${message}
            <button type="button" class="close" data-dismiss="alert">
                <span>&times;</span>
            </button>
        </div>
    `;
    
    $('body').append(notification);
    
    // Auto-dismiss after 3 seconds
    setTimeout(function() {
        $('.alert').fadeOut('slow', function() {
            $(this).remove();
        });
    }, 3000);
}
