/**
 * ComptaFlow UK - Invoice Lines Dynamic JS
 */
(function($) {
    'use strict';

    function recalcLine($row) {
        var qty = parseFloat($row.find('.line-qty').val()) || 0;
        var price = parseFloat($row.find('.line-price').val()) || 0;
        var vatRate = parseFloat($row.find('.line-vat-rate').val()) || 0;

        var net = Math.round(qty * price * 100) / 100;
        var vat = Math.round(net * vatRate) / 100;

        $row.find('.line-net').text('\u00a3' + net.toFixed(2));
        $row.find('.line-vat-amount').text('\u00a3' + vat.toFixed(2));

        var $selected = $row.find('.line-vat-rate option:selected');
        $row.find('.line-vat-code').val($selected.data('code') || 'GB-20');
    }

    function recalcTotals() {
        var subtotal = 0;
        var totalVat = 0;

        $('#invoice-lines-body .invoice-line-row').each(function() {
            var $row = $(this);
            var qty = parseFloat($row.find('.line-qty').val()) || 0;
            var price = parseFloat($row.find('.line-price').val()) || 0;
            var vatRate = parseFloat($row.find('.line-vat-rate').val()) || 0;

            var net = Math.round(qty * price * 100) / 100;
            var vat = Math.round(net * vatRate) / 100;

            subtotal += net;
            totalVat += vat;
        });

        var total = subtotal + totalVat;

        $('#inv-subtotal').text('\u00a3' + subtotal.toFixed(2));
        $('#inv-totalvat').text('\u00a3' + totalVat.toFixed(2));
        $('#inv-total').text('\u00a3' + total.toFixed(2));
    }

    function addLine() {
        var vatOptions = '';
        if (typeof comptaflow_uk_invoice_data !== 'undefined' && comptaflow_uk_invoice_data.vat_rates) {
            $.each(comptaflow_uk_invoice_data.vat_rates, function(i, rate) {
                var sel = (parseFloat(rate.rate_value) === 20) ? ' selected' : '';
                vatOptions += '<option value="' + rate.rate_value + '" data-code="' + rate.rate_code + '"' + sel + '>' +
                    parseFloat(rate.rate_value).toFixed(0) + '% - ' + rate.rate_name + '</option>';
            });
        } else {
            vatOptions = '<option value="20" data-code="GB-20" selected>20% - Standard</option>' +
                '<option value="5" data-code="GB-5">5% - Reduced</option>' +
                '<option value="0" data-code="GB-0">0% - Zero</option>';
        }

        var html = '<tr class="invoice-line-row">' +
            '<td><input type="text" name="line_description[]" class="regular-text" style="width:100%" required></td>' +
            '<td><input type="number" name="line_quantity[]" value="1" step="0.001" min="0" style="width:100%" class="line-qty"></td>' +
            '<td><input type="number" name="line_unit_price[]" value="0" step="0.01" min="0" style="width:100%" class="line-price"></td>' +
            '<td><select name="line_vat_rate[]" class="line-vat-rate" style="width:100%">' + vatOptions + '</select>' +
            '<input type="hidden" name="line_vat_code[]" value="GB-20" class="line-vat-code"></td>' +
            '<td><input type="text" name="line_account_code[]" value="4010" style="width:100%"></td>' +
            '<td class="right line-net">\u00a30.00</td>' +
            '<td class="right line-vat-amount">\u00a30.00</td>' +
            '<td><button type="button" class="button remove-invoice-line">&times;</button></td>' +
            '</tr>';

        $('#invoice-lines-body').append(html);
    }

    $(document).ready(function() {
        $('#add-invoice-line').on('click', function() {
            addLine();
        });

        $(document).on('click', '.remove-invoice-line', function() {
            var $tbody = $('#invoice-lines-body');
            if ($tbody.find('.invoice-line-row').length > 1) {
                $(this).closest('tr').remove();
                recalcTotals();
            }
        });

        $(document).on('change keyup', '.line-qty, .line-price, .line-vat-rate', function() {
            recalcLine($(this).closest('tr'));
            recalcTotals();
        });

        // Auto-fill due date from payment terms
        $('input[name="payment_terms"]').on('change', function() {
            var terms = parseInt($(this).val()) || 30;
            var issueDate = $('input[name="issue_date"]').val();
            if (issueDate) {
                var due = new Date(issueDate);
                due.setDate(due.getDate() + terms);
                var dd = due.toISOString().split('T')[0];
                $('input[name="due_date"]').val(dd);
            }
        });

        $('input[name="issue_date"]').on('change', function() {
            $('input[name="payment_terms"]').trigger('change');
        });

        // Status filter redirect
        $('#cfuk-status-filter').on('change', function() {
            var val = $(this).val();
            var url = new URL(window.location.href);
            if (val) {
                url.searchParams.set('status', val);
            } else {
                url.searchParams.delete('status');
            }
            url.searchParams.delete('paged');
            window.location.href = url.toString();
        });

        // Initial calculation
        recalcTotals();
    });
})(jQuery);
