document.addEventListener('DOMContentLoaded', function () {

    flatpickr("#invoice_date", {
        defaultDate: "today",
        dateFormat: "Y-m-d"
    });

    flatpickr("#due_date", {
        defaultDate: "today",
        dateFormat: "Y-m-d"
    });

    const form = document.getElementById('invoice-form');
    const addItemButton = document.getElementById('add-item');
    const invoiceItems = document.getElementById('invoice-items');
    const message = document.getElementById('invoice-message');
    const subtotalField = document.getElementById('subtotal');
    const totalField = document.getElementById('total');
    const currencySelect = document.getElementById('currency');
    const resetFormButton = document.getElementById('reset-form');

    function updateTotals() {
        let subtotal = 0;
        invoiceItems.querySelectorAll('tr').forEach(row => {
            let qty = parseInt(row.querySelector('input[name="item_qty[]"]').value) || 0;
            const price = parseFloat(row.querySelector('input[name="item_price[]"]').value) || 0;

            const MAX_QTY = 999;
            const MIN_QTY = 1;

            if (qty > MAX_QTY) {
                qty = MAX_QTY;
                row.querySelector('input[name="item_qty[]"]').value = MAX_QTY;
            } else if (qty < MIN_QTY) {
                qty = MIN_QTY;
                row.querySelector('input[name="item_qty[]"]').value = MIN_QTY;
            }

            const MAX_PRICE = 9999999;
            const MIN_PRICE = 0;

            const validPrice = Math.max(MIN_PRICE, Math.min(price, MAX_PRICE));

            const total = qty * validPrice;
            row.querySelector('input[name="item_total[]"]').value = total.toFixed(2);
            subtotal += total;
        });

        const taxInput = document.getElementById('taxRate');
        let taxRate = parseFloat(taxInput.value) || 0;
        if (taxRate < 0) taxRate = 0;

        const taxAmount = (subtotal * (taxRate / 100)).toFixed(2);
        const totalAmount = (subtotal + parseFloat(taxAmount)).toFixed(2);

        const currency = currencySelect ? currencySelect.value : '$';
        subtotalField.textContent = `${currency}${subtotal.toFixed(2)}`;
        totalField.textContent = `${currency}${totalAmount}`;
    }

    form.addEventListener('input', updateTotals);
    updateTotals();

    if (currencySelect) {
        currencySelect.addEventListener('change', updateTotals);
    }

    addItemButton.addEventListener('click', () => {
        const firstRow = invoiceItems.querySelector('tr');
        const newRow = firstRow.cloneNode(true);

        newRow.querySelectorAll('input').forEach(input => {
            if (input.name === 'item_name[]') input.value = '';
            if (input.name === 'item_qty[]') input.value = '1';
            if (input.name === 'item_price[]') input.value = '0.00';
            if (input.name === 'item_total[]') input.value = '0.00';
        });

        invoiceItems.appendChild(newRow);
    });

    resetFormButton.addEventListener("click", function () {
        location.reload();
    });

    invoiceItems.addEventListener('click', e => {
        if (e.target.classList.contains('remove-item')) {
            const allRows = invoiceItems.querySelectorAll('tr');
            const row = e.target.closest('tr');

            if (allRows.length > 1) {
                row.remove();
                updateTotals();
            } else {
                row.querySelector('input[name="item_name[]"]').value = '';
                row.querySelector('input[name="item_qty[]"]').value = '1';
                row.querySelector('input[name="item_price[]"]').value = '0.00';
                row.querySelector('input[name="item_total[]"]').value = '0.00';
                updateTotals();
            }
        }
    });

    form.addEventListener('submit', async function (e) {
        e.preventDefault();

        const items = [];
        invoiceItems.querySelectorAll('tr').forEach(row => {
            items.push({
                name: row.querySelector('input[name="item_name[]"]').value,
                qty: row.querySelector('input[name="item_qty[]"]').value,
                price: row.querySelector('input[name="item_price[]"]').value,
                total: row.querySelector('input[name="item_total[]"]').value,
            });
        });

        const formData = new FormData(form);
        formData.append('action', 'ingen_generate_pdf');
        formData.append('items', JSON.stringify(items));
        const taxInput = document.getElementById('taxRate');
        const taxRate = parseFloat(taxInput.value) || 0;
        formData.append('tax_rate', taxRate);

        const response = await fetch(ingen_ajax_object.ajax_url, {
            method: 'POST',
            body: formData
        });

        const result = await response.json();
        if (result.success) {
            const newTab = window.open(result.data.url, '_blank');
            if (!newTab || newTab.closed || typeof newTab.closed == 'undefined') {
                message.textContent = 'Please allow pop-ups to view the invoice.';
            } else {
                message.textContent = '';
            }
            updateTotals();
        } else {
            message.textContent = 'Failed to generate invoice.';
        }
    });

    document.addEventListener('input', function (event) {
        const input = event.target;

        if (input.name === 'item_qty[]') {
            input.value = input.value.replace(/\D/g, '');
        }

        if (input.name === 'item_price[]' || input.id === 'taxRate') {
            let value = input.value;

            value = value.replace(',', '.');

            const partialMatch = /^(\d{0,7})?(\.)?(\d{0,2})?$/.test(value);
            if (partialMatch) {
                input.value = value;
            } else {
                input.value = value.slice(0, -1);
            }
        }
    });

    document.addEventListener('focusin', function (event) {
        if (event.target.name === 'item_price[]' && event.target.value === '0.00' || event.target.id === 'taxRate' && event.target.value === '0.00') {
            event.target.value = '';
        }
        if (event.target.id === 'taxRate' && (event.target.value === '0' || event.target.value === '0.00')) {
            event.target.value = '';
        }

    });

    document.addEventListener('focusout', function (event) {
        if (event.target.name === 'item_price[]' || event.target.id === 'taxRate') {
            let value = event.target.value.replace(',', '.');
            let number = parseFloat(value);

            if (isNaN(number)) {
                number = 0;
            }

            const min = parseFloat(event.target.min) || 0;
            const max = parseFloat(event.target.max) || 9999999;

            if (number < min) number = min;
            if (number > max) number = max;

            event.target.value = number.toFixed(2);
        }
    });

    jQuery(document).ready(function($) {
        let mediaUploader;

        $('#upload_logo_button').on('click', function(e) {
            e.preventDefault();
            if (mediaUploader) {
                mediaUploader.open();
                return;
            }

            mediaUploader = wp.media.frames.file_frame = wp.media({
                title: 'Choose Logo',
                button: {
                    text: 'Choose Logo'
                },
                multiple: false
            });

            mediaUploader.on('select', function() {
                const attachment = mediaUploader.state().get('selection').first().toJSON();
                $('#logo_url').val(attachment.url);
                $('#logo_preview').html('<img src="' + attachment.url + '" style="max-height: 80px;">');
            });

            mediaUploader.open();
        });
    });

});
