<script src="<?php echo e(asset('admintheme/assets/js/moment.min.js')); ?>"></script>
<script src="<?php echo e(asset('admintheme/assets/js/daterangepicker.min.js')); ?>"></script>
<script>        
    function initializeInvoiceDatePicker(entryDate = null) {
        <?php if(isset($transaction)): ?>
            entryDate = '<?php echo e($transaction->entry_date); ?>';
        <?php endif; ?>
        const dateFormat = "<?php echo e(config('constant.js_date_format.date')); ?>";
        $('#entry_date').daterangepicker({
            locale: { format: dateFormat },
            singleDatePicker: true,
            autoUpdateInput: true,
            autoApply: true,
            startDate:  entryDate ? moment(entryDate) : moment(),
        });
    }
</script>

<script>
    
$(document).ready(function() {

    initializeInvoiceDatePicker();
    var  remainingBalance;


    <?php if(isset($transaction)): ?>        
        let customerId = $('#customer_id').val();        
        if (customerId != '') {
            let findOption = $('#customer_id').find('option').filter('[value=' + customerId + ']');
            let debit = parseFloat(findOption.attr('data-debit')) || 0;
            let credit = parseFloat(findOption.attr('data-credit')) || 0;
            remainingBalance = debit - credit;               
            $("#remain_balance").val(remainingBalance); 
        }        
    <?php endif; ?>

    $(document).on('change', '#customer_id', function(e) {
        e.preventDefault();
        let $this = $(this);
        let customerId = $this.val();
        $("#remain_balance").val('');
        $('#customer_id-error').remove();
        if (customerId != '') {
            let findOption = $this.find('option').filter('[value=' + customerId + ']');
            let debit = parseFloat(findOption.attr('data-debit'));
            let credit = parseFloat(findOption.attr('data-credit'));
            remainingBalance = debit - credit;
            $("#remain_balance").val(remainingBalance);           
        }
    });

    $(document).on('input', '#amount', function() {
        var $this = $(this);
        $(".error").remove();
        var amount = parseFloat($this.val());
        var original_amount = parseInt($("#original_amount").val()) || 0; 

        // Calculate additional quantity to be added
        var additional_amount = amount - original_amount;


        if (remainingBalance != undefined && !isNaN(additional_amount)) {
            remainingBalance = parseFloat(remainingBalance);
            $('#amount_error').remove();
            if (remainingBalance >= additional_amount) {
                var remain = remainingBalance - additional_amount;
                $('#remain_balance').val(remain.toFixed(2));
            }
            else if(remainingBalance < 0)
            {
                var remain = remainingBalance - additional_amount;
                $('#remain_balance').val(remain.toFixed(2));
            }
            else {
                $('#remain_balance').val(remainingBalance);
                if (!isNaN(additional_amount)) {                    
                    var errorHtml = '<div><span class="error text-danger">The amount entered must be less than the remaining balance. </span></div>';
                    $(errorHtml).insertAfter($($this).parent());
                }
            }
        }
    });

    $(document).on('submit', '#SaveCashReceiptForm', function (e) {
        e.preventDefault();
        showLoader();
        $("#SaveCashReceiptForm button[type=submit]").prop('disabled',true);
        $(".error").remove();
        $(".is-invalid").removeClass('is-invalid');

        // validation 
        var amount = parseFloat($("#amount").val());
        var original_amount = parseInt($("#original_amount").val()) || 0;

        var validationAmount = amount;

        <?php if(isset($transaction)): ?>
            validationAmount = original_amount;
        <?php endif; ?>
        
        console.log('validationAmount',validationAmount);
        if (original_amount > remainingBalance)
        {
            hideLoader();
            $("#SaveCashReceiptForm button[type=submit]").prop('disabled', false);
            swal("Amount", "The amount entered must be less than the remaining balance.", "error");
            return;
        }else{
            var formData = $(this).serialize();
            var formAction = $(this).attr('action');

            var requestType = 'POST';
            <?php if(isset($transaction)): ?>
            requestType = 'PUT';
            <?php endif; ?>

            $.ajax({
                url: formAction,
                type: requestType,
                headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                data: formData,
                success: function (response) {
                    hideLoader();
                    var alertType = response['alert-type'];
                        var message = response['message'];
                        var title = "<?php echo e(trans('quickadmin.transaction-management.fields.case_reciept')); ?>";
                        $('#SaveCashReceiptForm')[0].reset(); 
                        swal({
                        title: response.invoiceNumber,
                        text: message,
                        icon: alertType,
                        buttons: {
                        confirm: 'OK',
                        },
                        closeOnClickOutside: false,
                        }).then((confirm) => {
                            if (confirm) {
                                window.location.replace(response.redirectUrl);
                            }
                        });                 
                                                                            
                        $("#SaveCashReceiptForm button[type=submit]").prop('disabled',false);
                },
                error: function (xhr) {
                    hideLoader();
                    $("#SaveCashReceiptForm button[type=submit]").prop('disabled',false);
                    var errors= xhr.responseJSON.errors;
                    for (const elementId in errors) {
                        //$("#"+elementId).addClass('is-invalid');
                        var errorHtml = '<div><span class="error text-danger">'+errors[elementId]+'</span></div>';
                        $(errorHtml).insertAfter($("#"+elementId).parent());
                    }
                }
            });
        }        
    });
});
</script><?php /**PATH /home/hipldemo2/public_html/billing-software.hipl-staging2.com/resources/views/admin/payment_transactions/partials/script.blade.php ENDPATH**/ ?>