$(document).ready(function () {

    // The global page-ready script in includes/linkshead.php disables every
    // .form element on load (unless Add mode) and does a plain
    // removeAttr('disabled') on #hedit click. That's enough for ordinary
    // inputs, but select2 wraps the native <select> and doesn't pick up a
    // bare attribute removal — it needs prop() + a change trigger so the
    // widget itself re-renders as enabled (same fix sale.php uses for its
    // product dropdowns).
    $('#hedit').on('click', function () {
        setTimeout(function () {
            $('.jvbody .jvacc').each(function () {
                $(this).prop('disabled', false).trigger('change.select2');
            });
        }, 0);
    });

    // ── Row management ───────────────────────────────────────────────────────
    $('.jvbody').on('click', '.jvremove', function () {
        if ($('.jvbody tr').length <= 2) {
            Swal.fire({ icon: 'warning', title: 'A Journal Voucher needs at least two lines.', confirmButtonColor: '#2563eb' });
            return;
        }
        $(this).closest('tr').remove();
        renumberRows();
        recalcTotals();
    });

    $('#addnew').on('click', function () {
        AddRows();
    });

    function AddRows() {
        var ctr = parseInt($('#items').val(), 10) || 0;
        $.post('jv_add.php', { ctr: ctr }, function (data) {
            var $row = $(data).appendTo('.jvbody');
            $row.find('.select2').select2({ width: '100%' });
            $('#items').val(ctr + 1);
        });
    }

    // Auto-append a fresh row once the user starts typing into the last row —
    // keeps the grid growing without an explicit click every time.
    $('.jvbody').on('keyup change', '.jvdebit, .jvcredit', function () {
        var $tr = $(this).closest('tr');
        if ($tr.is('.jvbody tr:last-child') && parseFloat($(this).val()) > 0) {
            AddRows();
        }
    });

    // ── Debit / Credit are mutually exclusive per row ───────────────────────
    $('.jvbody').on('keyup blur', '.jvdebit, .jvcredit', function () {
        var $tr   = $(this).closest('tr');
        var debit = parseFloat($tr.find('.jvdebit').val());
        var credit = parseFloat($tr.find('.jvcredit').val());

        if (debit > 0) {
            $tr.find('.jvcredit').val('').prop('readonly', true);
        } else {
            $tr.find('.jvcredit').prop('readonly', false);
        }
        if (credit > 0) {
            $tr.find('.jvdebit').val('').prop('readonly', true);
        } else {
            $tr.find('.jvdebit').prop('readonly', false);
        }
        recalcTotals();
    });

    function renumberRows() {
        $('.jvbody tr').each(function (i) {
            $(this).find('.jv-sr').text(i + 1);
            $(this).find('.jvacc').attr('name', 'party_' + i);
            $(this).find('.jvdebit').attr('name', 'debit_' + i);
            $(this).find('.jvcredit').attr('name', 'credit_' + i);
        });
        $('#items').val($('.jvbody tr').length);
    }

    function recalcTotals() {
        var totDebit = 0, totCredit = 0;
        $('.jvdebit').each(function () {
            var v = parseFloat(this.value);
            if (!isNaN(v)) totDebit += v;
        });
        $('.jvcredit').each(function () {
            var v = parseFloat(this.value);
            if (!isNaN(v)) totCredit += v;
        });
        $('#totdebit').val(totDebit.toFixed(2));
        $('#totcredit').val(totCredit.toFixed(2));

        var $balanceTag = $('#jvBalanceTag');
        if ($balanceTag.length) {
            if (totDebit === totCredit && totDebit > 0) {
                $balanceTag.text('Balanced').css({ color: '#16a34a', background: '#dcfce7' });
            } else {
                $balanceTag.text('Not Balanced').css({ color: '#dc2626', background: '#fee2e2' });
            }
        }
    }
    recalcTotals();

    // ── Submit validation ────────────────────────────────────────────────────
    $('#ssubmit').on('click', function (e) {
        var totDebit = 0, totCredit = 0, validLines = 0;

        $('.jvbody tr').each(function () {
            var acc    = $(this).find('.jvacc').val();
            var debit  = parseFloat($(this).find('.jvdebit').val()) || 0;
            var credit = parseFloat($(this).find('.jvcredit').val()) || 0;
            if (acc && (debit > 0 || credit > 0)) validLines++;
        });

        $('.jvdebit').each(function () { var v = parseFloat(this.value); if (!isNaN(v)) totDebit += v; });
        $('.jvcredit').each(function () { var v = parseFloat(this.value); if (!isNaN(v)) totCredit += v; });
        totDebit = parseFloat(totDebit.toFixed(2));
        totCredit = parseFloat(totCredit.toFixed(2));

        if (validLines < 2) {
            e.preventDefault();
            Swal.fire({ icon: 'warning', title: 'At least two account lines are required.', confirmButtonColor: '#2563eb' });
            return false;
        }
        if (totDebit !== totCredit) {
            e.preventDefault();
            Swal.fire({ icon: 'error', title: 'Debit & Credit Total Does Not Match', text: 'Debit: ' + totDebit.toFixed(2) + '  |  Credit: ' + totCredit.toFixed(2), confirmButtonColor: '#2563eb' });
            return false;
        }
        if (totDebit <= 0) {
            e.preventDefault();
            Swal.fire({ icon: 'warning', title: 'Amount Cannot Be Empty', confirmButtonColor: '#2563eb' });
            return false;
        }
    });

});
