let currentCurrency = '$';

function calculateInvoice() {
    let subtotal = 0;
    const items = document.querySelectorAll('.item-container');
    
    items.forEach(item => {
        const rate = parseFloat(item.querySelector('.item-rate').value) || 0;
        const qty = parseFloat(item.querySelector('.item-qty').value) || 0;
        const amount = rate * qty;
        item.querySelector('.item-amount-top').textContent = currentCurrency + amount.toFixed(2);
        subtotal += amount;
    });
    
    document.getElementById('subtotalDisplay').textContent = currentCurrency + subtotal.toFixed(2);
    
    let discVal = 0;
    if(document.getElementById('row-discount').style.display !== 'none') {
        discVal = parseFloat(document.getElementById('discountInput').value) || 0;
    }
    const discType = document.getElementById('discountTypeInput').value;
    const calcDisc = (discType === 'percent') ? (subtotal * (discVal / 100)) : discVal;
    
    const afterDiscount = subtotal - calcDisc;

    let taxVal = 0;
    if(document.getElementById('row-tax').style.display !== 'none') {
        taxVal = parseFloat(document.getElementById('taxInput').value) || 0;
    }
    const taxType = document.getElementById('taxTypeInput').value;
    const calcTax = (taxType === 'percent') ? (afterDiscount * (taxVal / 100)) : taxVal;

    let shipping = 0;
    if(document.getElementById('row-shipping').style.display !== 'none') {
        shipping = parseFloat(document.getElementById('shippingInput').value) || 0;
    }

    const total = afterDiscount + calcTax + shipping;
    document.getElementById('totalDisplay').textContent = currentCurrency + total.toFixed(2);
    
    const paid = parseFloat(document.getElementById('paidInput').value) || 0;
    const balance = total - paid;
    document.getElementById('balanceDisplay').textContent = currentCurrency + balance.toFixed(2);
}

function toggleCalcType(field) {
    const typeInput = document.getElementById(field + 'TypeInput');
    const symLabel = document.getElementById(field + 'Sym');

    if (typeInput.value === 'percent') {
        typeInput.value = 'fixed';
        symLabel.textContent = currentCurrency;
    } else {
        typeInput.value = 'percent';
        symLabel.textContent = '%';
    }
    calculateInvoice();
}

function showRow(type) {
    document.getElementById('row-' + type).style.display = 'flex';
    if (type === 'discount') document.getElementById('addDiscountBtn').style.display = 'none';
    if (type === 'tax') document.getElementById('addTaxBtn').style.display = 'none';
    if (type === 'shipping') document.getElementById('addShippingBtn').style.display = 'none';
    checkActionLinksContainer();
    calculateInvoice();
}

function hideRow(type) {
    document.getElementById('row-' + type).style.display = 'none';
    document.getElementById(type + 'Input').value = '0'; 
    if (type === 'discount') document.getElementById('addDiscountBtn').style.display = 'inline-block';
    if (type === 'tax') document.getElementById('addTaxBtn').style.display = 'inline-block';
    if (type === 'shipping') document.getElementById('addShippingBtn').style.display = 'inline-block';
    checkActionLinksContainer();
    calculateInvoice();
}

function checkActionLinksContainer() {
    const d = document.getElementById('addDiscountBtn').style.display;
    const t = document.getElementById('addTaxBtn').style.display;
    const s = document.getElementById('addShippingBtn').style.display;
    const container = document.getElementById('actionLinksContainer');
    if (d === 'none' && t === 'none' && s === 'none') {
        container.style.display = 'none';
    } else {
        container.style.display = 'flex';
    }
}

function updateCurrency(sym) {
    currentCurrency = sym;
    document.getElementById('currencyInput').value = sym;
    document.querySelectorAll('.dyn-curr-sym').forEach(el => el.textContent = sym);
    if(document.getElementById('discountTypeInput').value === 'fixed') {
        document.getElementById('discountSym').textContent = sym;
    }
    if(document.getElementById('taxTypeInput').value === 'fixed') {
        document.getElementById('taxSym').textContent = sym;
    }
    calculateInvoice();
}

document.addEventListener('DOMContentLoaded', function() {
    const currencySelector = document.getElementById('currencySelector');
    if(currencySelector) {
        currencySelector.addEventListener('change', function(e) {
            updateCurrency(e.target.value);
        });
    }

    document.addEventListener('input', function(e) {
        if (e.target.tagName.toLowerCase() === 'textarea') {
            e.target.style.height = 'auto';
            e.target.style.height = (e.target.scrollHeight) + 'px';
        }
        if (e.target.classList.contains('calc-input')) {
            calculateInvoice();
        }
    });

    const logoInput = document.getElementById('logoInput');
    if(logoInput) {
        logoInput.addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = function(event) {
                    const container = document.getElementById('logoPreviewContainer');
                    container.style.backgroundImage = 'url(' + event.target.result + ')';
                    document.getElementById('logoTextWrapper').style.display = 'none';
                    container.style.border = 'none';
                }
                reader.readAsDataURL(file);
            }
        });
    }

    // API Auto Save Backend Logic
    const formElement = document.getElementById('invoiceForm');
    if(formElement) {
        formElement.addEventListener('submit', function(e) {
            const formData = new FormData(this);
            fetch('/api/invoices/save_invoice.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if(data.status === 'success') {
                    console.log('Invoice successfully saved to Database.');
                }
            })
            .catch(error => console.error('API Error:', error));
        });
    }

    calculateInvoice();
});

function addLineItem() {
    const wrapper = document.getElementById('itemsWrapper');
    const firstItem = wrapper.querySelector('.item-container');
    const newItem = firstItem.cloneNode(true);
    newItem.querySelector('.item-rate').value = '';
    newItem.querySelector('.item-qty').value = '';
    newItem.querySelector('textarea').value = '';
    newItem.querySelector('.item-amount-top').textContent = currentCurrency + '0.00';
    newItem.querySelector('.remove-item').style.display = 'inline';
    wrapper.appendChild(newItem);
    calculateInvoice();
}

function removeItem(element) {
    const items = document.querySelectorAll('.item-container');
    if(items.length > 1) {
        element.closest('.item-container').remove();
        calculateInvoice();
    }
}