@extends('layouts.app')
@section('title')@lang('quickadmin.transaction-management.fields.new_case_reciept') @endsection
@section('customCss')
<meta name="csrf-token" content="{{ csrf_token() }}" >
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" />  

@endsection
@section('main-content')
<div class="card MainBox floatingLabel">
  <div class="mainHeading">
      <h2>@lang('quickadmin.order-management2.title-case-reciept')</h2>
  </div>
  <form method="post" id="SaveCashReceiptForm" action="{{route('transactions.store')}}" class="pt-2">
      @include('admin.payment_transactions._form')        
  </form>    
</div>
@endsection


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

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

    initializeInvoiceDatePicker();
    var  remainingBalance;


    @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); 
        }        
    @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).toFixed(2);
            $("#remain_balance").val(remainingBalance);    
            $("#remain_balance").attr("data-original-remain-bal", remainingBalance);
            $(".paymentRow").each(function() {
                $(this).find("input[type='text']").val('');
                $(this).find("#remain_balance")
                    .val(remainingBalance)
                    .attr("data-original-remain-bal", remainingBalance);
            });       
        }else {
            $(".paymentRow").each(function() {
                $(this).find("input").val('');
                $(this).find("select").val('').trigger("change");
            });
        }
    });

    // $(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).toFixed(2);
    //         $("#remain_balance").val(remainingBalance);           
    //            $(".paymentRow").each(function() {
    //             $(this).find("input[type='text']").val('');
    //             $(this).find("#remain_balance")
    //                 .val(remainingBalance)
    //                 .attr("data-original-remain-bal", remainingBalance);
    //         });
    //     } else {
    //         $(".paymentRow").each(function() {
    //             $(this).find("input").val('');
    //             $(this).find("select").val('').trigger("change");
    //         });
    //     }
    // });

    // $(document).on('input', '.amount', function() {
    //     $(".error").remove();

    //     let originalRemain = parseFloat($("#remain_balance").attr('data-original-remain-bal')) || 0;

    //     let remain = originalRemain;
    //     let isError = false;

    //     $('.amount').each(function() {
    //         let val = parseFloat($(this).val());
    //         if (!isNaN(val) && val > 0) {
    //             if (val <= remain) {
    //                 remain -= val; 
    //             } else {
    //                 isError = true;
    //             }
    //         }
    //     });
    //     $('#remain_balance').val(remain.toFixed(2));

    //     if (isError) {
    //         var errorHtml = '<div><span class="error text-danger">The entered amount exceeds the remaining balance available.</span></div>';
    //         $(errorHtml).insertAfter($(this).parent());
    //     }
    // });

    //  $(document).on('input', '.amount', function() {
    //     $(".error").remove(); 

    //     var amount = parseFloat($this.val());
    //     var original_amount = parseInt($("#original_amount").val()) || 0;
    //     var original_remaining_balance = parseFloat($("#remain_balance").attr('data-original-remain-bal'));

    //     $('#remain_balance').val(remain.toFixed(2));

    
    //     if (remain < 0) {
    //         var errorHtml = '<div class="error text-danger">Total amount exceeds the original balance!</div>';
    //         $(this).after(errorHtml);
    //     }
    // });


    $(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 amount = 0;
        $('.amount').each(function() {
            var val = parseFloat($(this).val());
            if (!isNaN(val)) amount += val;
        });

        var original_amount = parseInt($("#original_amount").val()) || 0;
        // if (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';
            @if(isset($transaction))
            requestType = 'PUT';
            @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 = "{{ 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);

                    if (xhr.responseJSON.errors) {
                        const errors = xhr.responseJSON.errors;

                        for (const elementId in errors) {
                            let message = errors[elementId][0];
                            let match = elementId.match(/^(\w+)\.(\d+)$/);
                            let fieldName, index;
                            if (match) {
                                fieldName = match[1];
                                index = parseInt(match[2]); 
                            } else {
                                fieldName = elementId;
                                index = null;
                            }
                            message = message.replace(elementId, fieldName);

                            let selector = $(`[name="${fieldName}[]"]`);
                            if (index !== null && selector.length > index) {
                                selector = selector.eq(index);
                            } else if (!selector.length) {
                                selector = $(`[name="${fieldName}"]`);
                            }

                            if (selector.length) {
                                selector.each(function() {
                                    const $formGroup = $(this).closest('.form-group');
                                    $formGroup.find(".error").remove();
                                    let errorHtml = `<div class="error text-danger mt-1">${message}</div>`;
                                    $formGroup.append(errorHtml);
                                });
                            }
                        }
                    }
                }

            });
        // }        
    });

    $(document).on("click", "#addPaymentBtn", function () {
        let newRow = $(".paymentRow:first").clone();
        newRow.find("input").val("");

        let $select = newRow.find("select.payment_way");
        $select.val($select.find("option:first").val()); 

        newRow.find(".select2-container").remove();

        newRow.find(".removePaymentBtn").show();
        newRow.find("#addPaymentBtn").remove();
        $("#paymentContainer").parent().append(newRow);

        newRow.find("select.payment_way").select2({
            width: '100%' 
        });
    });

    $(document).on("click", ".removePaymentBtn", function () {
        $(this).closest(".paymentRow").remove();
        $('.amount').last().trigger('input');
    });
    

});

function toggleVoucherField(select) {
    const selectedOption = select.options[select.selectedIndex];
    const customerType = selectedOption.dataset.type; 
    const voucherInput = document.getElementById('voucher_number');

    if (customerType === 'cash') {
        voucherInput.readOnly = true;
        voucherInput.value = ''; 
    } else {
        voucherInput.readOnly = false;
        voucherInput.placeholder = 'Enter Estimate Number';
    }
}
document.addEventListener('DOMContentLoaded', function() {
    const customerSelect = document.getElementById('customer_id');
    if(customerSelect.value) {
        toggleVoucherField(customerSelect);
    }
});
</script>
@endsection