@extends('layouts.app')
@section('title','Receipt Vouchers')
@section('pages')
<style type="text/css">
    .clear {
        clear: both;
        margin-top: 20px;
    }

    .autocomplete {
        position: relative;
    }

    .autocomplete .searchResult {
        list-style: none;
        padding: 0px;
        width: 78%;
        position: absolute;
        margin: 0;
        margin-top: 40px;
        background: white;
        z-index: 5;
    }

    .autocomplete .searchResult li {
        background: #F2F3F4;
        padding: 10px;
        margin-bottom: 1px;
        white-space: break-spaces;
    }

    .autocomplete .searchResult li:nth-child(even) {
        background: #E5E7E9;
        color: black;
    }

    .autocomplete .searchResult li:hover {
        cursor: pointer;
        background: #CACFD2;
    }

    #add_reference i {
        height: 20px;
        width: 20px;
        background: #0d6efd25;
        color: #0d6efd;
        text-align: center;
        border-radius: 50px;
        line-height: 20px;
    }

    .add_btn {
        height: 40px;
        width: 40px;
        font-size: 16px;
        border-radius: 0 3.5px 3.5px 0;
        padding: 0;
    }

    /*    .custom_grid {
        padding-left:1rem;
        padding-right:1rem;
    }
    .custom_grid .input-group {
        position:relative;
    }
    .custom_grid .input-group .form-label {
        position:absolute;
        top:-10px;
        left:5px;
        font-size:12px;
        padding:0px 8px;
        background-color:#f7f8fa;
        z-index:5;
    }
    .custom_grid .input-group .form-control.br-0 {
        border-radius:0;
    }
    .custom_grid .btn {
        font-size:22px;
        padding: 0.15rem 0.75rem;
        border-top-left-radius:0px;
        border-bottom-left-radius:0px;
    }*/
    .select2-container--bootstrap4 .select2-selection {
        border-top-right-radius: 0px;
        border-bottom-right-radius: 0px;
    }

    .datepickers {
        cursor: pointer !important;
    }

    #amount_recieved {
        border: 2px solid #3be94d;
        background-color: #fff;
        font-weight: 600;
        font-size: 16px;
    }

    .amount_collection {
        border: 2px solid #fff579;
        /* background-color: #f9f2df; */
        font-weight: 600;
        font-size: 16px;
    }
</style>
<link rel="stylesheet/less" type="text/css" href="{{ asset('admin/plugins/datepicker/less/datepicker.less') }}">
<link href="{{ asset('admin/plugins/datepicker/css/datepicker.css')}}" rel="stylesheet" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/12.1.10/css/intlTelInput.css">

<!--breadcrumb-->
<div class="page-breadcrumb d-flex align-items-center mb-3 px-3 px-md-0">
    <div class="breadcrumb-title pe-3"><i class="bi bi-list"></i> Receipt Vouchers</div>
    <div class="ps-3">
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb mb-0 p-0">

                <li class="breadcrumb-item active" aria-current="page">New Receipt Voucher Entry</li>
            </ol>
        </nav>
    </div>
    <div class="ms-auto">
        <div class="btn-group">
            <a href="{{route('receipt-voucher.index')}}" class="btn btn-info"><i class="bx bx-arrow-back ms-0 me-1"></i>Back</a>
        </div>
    </div>
</div>
<!--end breadcrumb-->

<div class="row auto">
    <div class="col-xl-12 mx-auto">
        <form class="auto-width create_billing" id="create_receipt_voucher_form" action="{{ route('add-receipt-vouchers')}}" method="post" enctype='multipart/form-data'>
            <!-- For validation comment on -->
            <!-- <form class="row g-3 was-validated"> -->
            @csrf

            <div class="card style_table">
                <div class="card-body pt-2 px-3" style="border-radius:0px;">

                    <div class="row align-items-center">
                        <div class="col-md-6">
                            <div>
                                <label class="form-label">Party Account Name <span class="text-danger"><b>*</b></span></label>
                            </div>
                            <div class="input-group autocomplete">
                                <input type="text" name="" id="account_id" class="accounts-select form-control" placeholder="Search Account">
                                <ul class="searchResult"></ul>

                                <div class="input-group-append" style="margin: auto 10px auto 0;">
                                    <button class="btn btn-secondary add_btn" id="create_account" type="button" data-bs-toggle="modal" data-bs-target="#commonModal">+</button>
                                    <button class="btn btn-primary edit_btn" style="height: 40px;" id="edit_customer" type="button" data-bs-toggle="modal" data-bs-target="#commonModal"><i class="bi bi-pencil-square"></i></button>
                                </div>
                                <input type="hidden" name="account_id" value="">
                            </div>
                            <span class="text-danger error_account_id" style="display:none;">This field is required.</span>
                        </div>

                        <div class="col-md-3">
                            <div>
                                <label class="form-label">Receipt Date <span class="text-danger"><b>*</b></span></label>
                            </div>
                            <div class="input-group autocomplete">
                                <input type="text" readonly name="receipt_date" id="receipt_date" class="form-control datepickers" placeholder="Date" value="">
                            </div>
                            <span class="text-danger error_receipt_date" style="display:none;">This field is required.</span>
                        </div>
                        {{-- <div class="col-md-3">
                            <div>
                                <label class="form-label">#Receipt No</label>
                            </div>
                            <div class="input-group autocomplete">
                                <input type="text" name="receipt_no" id="receipt_no" class="patient-select form-control" placeholder="Search Voucher No">
                                <ul class="searchResult"></ul>
                            </div>
                            <span class="text-danger error_receipt_no" style="display:none;">This field is required.</span>
                        </div>--}}
                        <div class="col-md-3">
                            <div>
                                <label class="form-label">Financial Year<span class="text-danger"><b>*</b></span></label>
                            </div>
                            <div class="input-group autocomplete">
                                <select class="form-control br-0" id="financial_year_id" name="financial_year_id" required>
                                    @foreach($financialYears as $list)
                                    <option value="{{ $list->financialyearid}}" {!! $list->is_default == 1 ? 'selected' : '' !!} title="{{$list->financial_year_name}}">{{$list->financial_year_name}}</option>
                                    @endforeach
                                </select>
                            </div>
                            <span class="text-danger error_financial_year_id" style="display:none;">This field is required.</span>
                        </div>
                        {{-- <div class="col-md-3">
                            <div>
                                <label class="form-label">Receipt At<span class="text-danger"><b>*</b></span></label>
                            </div>
                            <div class="input-group autocomplete">
                                <input type="text" name="" id="receipt_at_id" class="receipt-at-select form-control" placeholder="Search Cash/Bank account">
                                <ul class="searchResult"></ul>
                                <input type="hidden" name="receipt_at_id" value="">
                            </div>
                            <span class="text-danger error_receipt_at_id" style="display:none;">This field is required.</span>
                        </div> --}}
                    </div>
                </div>
            </div>

            <div class="cart_products">
                <div class="card style_table shadow-none" style="margin-bottom:0.8rem;">
                    <div class="card-body pb-0">
                        <div class="table-responsive">
                            <table id="example" class="table table-bordered align-middle" style="width:100%">
                                <thead class="table-light">
                                    <tr>
                                        <th class="thbutton">Sr No.</th>
                                        <th class="text-start">Transaction Mode </th>
                                        <th class="text-start">Payment Mode </th>
                                        <th class="text-start">Transaction Reference</th>
                                        <th style="text-align: leftright;width: 20%">Amount</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @if(isset($accounting_group) && count($accounting_group) > 0)
                                    @foreach($accounting_group as $key => $list)
                                    <tr class="cart-products" data-patient_id="{{$list['account_id']}}">
                                        <td class="text-start">{{ $key + 1 }}</td>
                                        <td class="text-start">{{$list->name ?? ''}}</td>
                                        <td class="text-start">
                                            <select class="form-control" name="payment_mode[{!! $list->id !!}][transaction_mode_id]">
                                                @if(isset($list->chart_of_account_sub_type->paymentModes))
                                                @foreach($list->chart_of_account_sub_type->paymentModes as $value)
                                                <option value="{!! $value->id !!}" {!! matchselected($value->is_default, 1) !!}>{!! $value->mode !!}</option>
                                                @endforeach
                                                @endif
                                            </select>
                                        </td>
                                        <td class="text-start">
                                            <input type="text" name="payment_mode[{!! $list->id !!}][transaction_referrence]" class="form-control" placeholder="Transaction Referrence">
                                        </td>
                                        <td style="text-align: center;">
                                            <input type="number" class="form-control amount amount_collection" name="payment_mode[{!! $list->id !!}][amount]" value="0" style="text-align: right;">
                                        </td>
                                    </tr>

                                    @endforeach
                                    <tr>
                                        <td colspan="3"></td>
                                        <td class="text-start text-end">Total Paid</td>
                                        <td class="text-start">
                                            <input disabled type="number" class="form-control received_amount" id="amount_recieved" value="0" style="text-align: right;">
                                        </td>
                                    </tr>
                                    @else
                                    <tr>
                                        <td colspan="9">No Data Found</td>
                                    </tr>
                                    @endif

                                    <tr>
                                        <td colspan="4"></td>
                                        <td class="text-start">
                                            <div class="col-12 mt-4 mb-4" align="center">
                                                <div class="">
                                                    <input type="hidden" name="total_amount">
                                                    <button class="btn btn-md btn-primary save_reciept_button" type="button" style="width: 100%;height: 35px;"><i class="bx bx-save"></i> Submit To Save Receipt Voucher</button>
                                                </div>
                                            </div>
                                        </td>
                                    </tr>

                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <div class="card style_table">
                <div class="row align-items-end gx-0 mt-4 mb-3">
                    <div class="col-md-12 px-3">
                        <div>
                            <label class="form-label">Note / Description </label>
                        </div>
                        <div class="input-group">
                            <textarea class="form-textarea" name="remarks" id="remarks" rows="3"></textarea>
                        </div>
                        <span class="text-danger error_remarks" style="display:none;">This field is required.</span>
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>
<!--end row-->

@endsection

@section('js')
<script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/12.1.10/js/intlTelInput.js"></script>

<script type="text/javascript" src="{{ asset('admin/plugins/datepicker/js/bootstrap-datepicker.js')}}"></script>
<script>
    $(function() {
        // $('.datepickers').datepicker({
        //     format: 'mm/dd/yy',
        //     autoclose: true,
        // }).on('changeDate', function(ev) {
        //     $(this).datepicker('hide');
        //     validateDate();

        // });

        $('.datepickers').datepicker({
        format: "{!! $companyDateFormate??'dd-mm-yyyy' !!}",
        autoclose: true,
        //startDate: financialYearDates.fromDate,//optional
        //endDate: financialYearDates.toDate//optional
        }).datepicker("setDate", new Date())
    });

    $(document).ready(function() {
        // Disable the edit_customer button initially
        $('#edit_customer').prop('disabled', true);

        // Add input event listener to check the input field and enable/disable the button
        $('#account_id').on('input', function() {
            var customerName = $(this).val();
            var editCustomerBtn = $('#edit_customer');

            if (customerName.trim() === "") {
                // If the input is empty, disable the button
                editCustomerBtn.prop('disabled', true);
            } else {
                // If the input is not empty, enable the button
                editCustomerBtn.prop('disabled', false);
            }
        });

        $('.accounts-select').autocomplete({
            autoFocus: true,
            minLength: 0,
            source: function(request, response) {
                if (request.term.length < 2) {
                    $('[name="account_id"]').val('');
                    return false;
                }

                $.ajax({
                    url: "{{ route('journal-voucher-search-accounts') }}",
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        action: 'get_accounts_for_journal_voucher',
                        search_text: request.term
                    },
                    success: function(json) {
                        //  ;
                        if (json.error) {
                            $('[name="account_id"]').val('');
                            return false;
                        }
                        //  ;
                        response($.map(json.result, function(item) {
                            return {
                                id: item.id,
                                name: item.name,
                            };
                        }));
                    }
                });
            },
            select: function(event, ui) {
                //  ;
                event.preventDefault();
                $(this).val(ui.item.name + "");
                $('[name="account_id"]').val(ui.item.id);
                return false;
            }
        }).data("ui-autocomplete")._renderItem = function(ul, item) {
            //  ;
            return $("<li>")
                .append("<a>" + item.name + "</a>")
                .appendTo(ul);
        };
    });

    $(document).on('click', '.save_button', function(e) {
        e.preventDefault();

        if ($('#commonModal').find('form').hasClass('create_customer')) {
            if ($('#phone_no').val().trim() != '') {
                var dailcode_title = $('.phone_no_col .selected-flag').attr('title');
                var dailcode_array = dailcode_title.split("+");
                $('input[name="phone_no"]').val("+" + dailcode_array[1] + $('#phone_no').val());
            }

            if ($('#whatsapp_no').val().trim() != '') {
                var dailcode_title = $('.whatsapp_no_col .selected-flag').attr('title');
                var dailcode_array = dailcode_title.split("+");
                $('input[name="whatsapp_no"]').val("+" + dailcode_array[1] + $('#whatsapp_no').val());
            }

            $('.error_name').hide();
            $('.error_email').hide();
            $('.error_phone').hide();
            $('.error_country_id').hide();
            $('.error_accounting_group_id').hide();
            $('.error_account_type_id').hide();

            var error = 0;
            if ($('[name="accounting_group_id"]').val() == '' || $('[name="accounting_group_id"]').val() == null) {
                if ($('.account_type_id').find(':selected').attr('data-identifier') != 'student') {
                    $('.error_accounting_group_id').show();
                    error = 1;
                }
            }

            if ($('[name="account_type_id"]').val() == '' || $('[name="account_type_id"]').val() == null) {
                $('.error_account_type_id').show();
                error = 1;
            }

            if ($('input[name="name"]').val().trim() == '' || $('[name="account_title_id"]').val() == '') {
                $('.error_name').show();
                error = 1;
                setTimeout(function() {
                    $('.error_name').hide();
                }, 3000);

            }

            if ($('[name="country_id"]').val().trim() == '') {
                $('.error_country_id').show();
                error = 1;
                setTimeout(function() {
                    $('.error_country_id').hide();
                }, 3000);

            }

            if ($('input[name="phone_no"]').val().trim() == '') {
                $('.error_phone').show();
                error = 1;
                setTimeout(function() {
                    $('.error_phone').hide();
                }, 3000);

            }

            if (error == 0) {
                let formdata = new FormData($('#create_customer_form')[0]);

                $.ajax({
                        url: $('#create_customer_form').attr('action'),
                        data: formdata,
                        processData: false,
                        contentType: false,
                        type: 'POST',
                        success: function(response) {
                            if (response.success === true) {
                                toastr.success(response.message, 'Success.');
                                // append new category to selection
                                $('[name="account_id"]').val(response.data.id);
                                $('#account_id').val(response.data.name);

                                // hide modal
                                $('#commonModal').modal('hide');
                                $('#commonModal').find('.modal-body').html('');
                                $('#edit_customer').prop('disabled', true);
                            } else {
                                toastr.error(response.message, 'Error!');
                            }
                        }
                    })
                    .fail(function(jqXHR, textStatus, errorThrown) {
                        console.log('AJAX request failed:', textStatus, errorThrown);
                        toastr.error('An error occurred during the request.', 'Error!');
                    });
            }
        } else if ($('#commonModal').find('form').hasClass('edit_customer')) {
            if ($('#phone_no').val().trim() != '') {
                var dailcode_title = $('.phone_no_col .selected-flag').attr('title');
                var dailcode_array = dailcode_title.split("+");
                $('input[name="phone_no"]').val("+" + dailcode_array[1] + $('#phone_no').val());
            }

            if ($('#whatsapp_no').val().trim() != '') {
                var dailcode_title = $('.whatsapp_no_col .selected-flag').attr('title');
                var dailcode_array = dailcode_title.split("+");
                $('input[name="whatsapp_no"]').val("+" + dailcode_array[1] + $('#whatsapp_no').val());
            }

            $('.error_name').hide();
            $('.error_email').hide();
            $('.error_phone').hide();
            $('.error_country_id').hide();
            $('.error_date_of_birth').hide();
            var error = 0;

            if ($('input[name="name"]').val().trim() == '' || $('[name="account_title_id"]').val() == '') {
                $('.error_name').show();
                error = 1;
                setTimeout(function() {
                    $('.error_name').hide();
                }, 3000);

            }

            if ($('[name="country_id"]').val().trim() == '') {
                $('.error_country_id').show();
                error = 1;
                setTimeout(function() {
                    $('.error_country_id').hide();
                }, 3000);

            }

            if ($('input[name="phone_no"]').val().trim() == '') {
                $('.error_phone').show();
                error = 1;
                setTimeout(function() {
                    $('.error_phone').hide();
                }, 3000);

            }

            if (error == 0) {
                let formdata = new FormData($('#edit_customer_form')[0]);

                $.ajax({
                        url: $('#edit_customer_form').attr('action'),
                        data: formdata,
                        processData: false,
                        contentType: false,
                        type: 'POST',
                        success: function(response) {
                            if (response.success === true) {
                                toastr.success(response.message, 'Success.');
                                // append new category to selection
                                $('[name="account_id"]').val(response.data.id);
                                $('#account_id').val(response.data.name);

                                // hide modal
                                $('#commonModal').modal('hide');
                                $('#commonModal').find('.modal-body').html('');
                            } else {
                                toastr.error(response.message, 'Error!');
                            }
                        }
                    })
                    .fail(function(jqXHR, textStatus, errorThrown) {
                        console.log('AJAX request failed:', textStatus, errorThrown);
                        toastr.error('An error occurred during the request.', 'Error!');
                    });
            }
        } else if ($('#commonModal').find('form').hasClass('create_patient')) {
            if ($('#phone_no').val().trim() != '') {
                var dailcode_title = $('.phone_no_col .selected-flag').attr('title');
                var dailcode_array = dailcode_title.split("+");
                $('input[name="phone_no"]').val("+" + dailcode_array[1] + $('#phone_no').val());
            }

            if ($('#whatsapp_no').val().trim() != '') {
                var dailcode_title = $('.whatsapp_no_col .selected-flag').attr('title');
                var dailcode_array = dailcode_title.split("+");
                $('input[name="whatsapp_no"]').val("+" + dailcode_array[1] + $('#whatsapp_no').val());
            }

            $('.error_name').hide();
            $('.error_email').hide();
            $('.error_phone').hide();
            $('.error_country_id').hide();
            $('.error_date_of_birth').hide();
            var error = 0;

            if ($('input[name="name"]').val().trim() == '' || $('[name="account_title_id"]').val() == '') {
                $('.error_name').show();
                error = 1;
            }

            if ($('[name="country_id"]').val().trim() == '') {
                $('.error_country_id').show();
                error = 1;
            }

            if ($('input[name="phone_no"]').val().trim() == '') {
                $('.error_phone').show();
                error = 1;
            }

            if ($('input[name="date_of_birth"]').val().trim() == '' &&
                $('input[name="year"]').val().trim() == '' &&
                $('input[name="month"]').val().trim() == '' &&
                $('input[name="day"]').val().trim() == ''
            ) {
                $('.error_date_of_birth').show();
                error = 1;
            }

            if (error == 0) {
                let formdata = new FormData($('#create_patient_form')[0]);

                $.ajax({
                        url: $('#create_patient_form').attr('action'),
                        data: formdata,
                        processData: false,
                        contentType: false,
                        type: 'POST',
                        success: function(response) {
                            if (response.success === true) {
                                toastr.success(response.message, 'Success.');
                                // append new category to selection
                                $('[name="account_id"]').val(response.data.id);
                                $('#account_id').val(response.data.name);

                                // hide modal
                                $('#commonModal').modal('hide');
                                $('#commonModal').find('.modal-body').html('');
                            } else {
                                toastr.error(response.message, 'Error!');
                            }
                        }
                    })
                    .fail(function(jqXHR, textStatus, errorThrown) {
                        console.log('AJAX request failed:', textStatus, errorThrown);
                        toastr.error('An error occurred during the request.', 'Error!');
                    });
            }
        }

        error = 1;
    })

    $(document).on('click', '.save_reciept_button', function(e) {

        e.preventDefault();

        $('.error_receipt_at_id').hide();
        $('.error_receipt_date').hide();
        $('.error_account_id').hide();
        $('.error_financial_year_id').hide();
        $('.error_remarks').hide();
        var error = 0;

        /*if ($('[name="receipt_at_id"]').val().trim() == '') {
          $('.error_receipt_at_id').show();
          error = 1;
        }*/

        if ($('input[name="receipt_date"]').val().trim() == '') {
            $('.error_receipt_date').show();
            error = 1;
        }

        if ($('[name="financial_year_id"]').val() == null || $('[name="financial_year_id"]').val() == '') {
            $('.error_financial_year_id').show();
            error = 1;
        } else if (validateDate()) {
            toastr.error('Selected date must be in between Financial Years!', 'Error!');
            error = 1;
        }

        if ($('input[name="account_id"]').val().trim() == '') {
            toastr.error('Party Account is required!', 'Error!');
            error = 1;
        }

        /*if ($('[name="remarks"]').val().trim() == '') {
          $('.error_remarks').show();
          error = 1;
        }*/

        var totalAmount = 0;
        $('.amount').each(function() {
            totalAmount += parseFloat($(this).val()) || 0;
        });

        if (totalAmount == '' || totalAmount == 0) {
            toastr.error('Transaction amount can not be 0!', 'Error!');
            error = 1;
        }


        if (error == 0) {
            $('.save_reciept_button').attr('disabled', true);
            $('[name="total_amount"]').val(totalAmount);

            let formdata = new FormData($('#create_receipt_voucher_form')[0]);
            /* formdata.append( 'receipt_date', $('#receipt_date').val());
             formdata.append( 'receipt_no', $('#receipt_no').val());
             formdata.append( 'remarks', $('#remarks').val());
             formdata.append( 'account_id', $('input[name="receipt_at_id"]').val());
             formdata.append( 'total_amount', parseInt($('#totalAmount').text().trim().replace ( /[^\d.]/g, '' )));*/
            $.ajax({
                    url: "{!! route('receipt-voucher-submit') !!}",
                    data: formdata,
                    processData: false,
                    contentType: false,
                    type: 'POST',
                    success: function(response) {
                        if (response.success === true) {
                            toastr.success(response.message, 'Success.');
                            $('#receipt_date').val('');
                            $('#receipt_no').val('');
                            $('#remarks').val('');
                            $('#receipt_at_id').val('');
                            $('input[name="receipt_at_id"]').val('');

                            setTimeout(function() {
                                var url = "{!! route('print-receipt-voucher', ':id') !!}";
                                window.location.href = url.replace(':id', response.voucher);
                            }, 1000);


                            return false;
                        } else {
                            toastr.error(response.message, 'Error!');

                            $('.save_reciept_button').attr('disabled', false);
                        }
                    }
                })
                .fail(function(jqXHR, textStatus, errorThrown) {
                    console.log('AJAX request failed:', textStatus, errorThrown);
                    toastr.error('An error occurred during the request.', 'Error!');
                });
        }
    });


    $(document).on('click', '.add_to_cart', function(e) {
        e.preventDefault();

        //$('.error_receipt_no').hide();
        $('.error_receipt_date').hide();
        $('.error_account_id').hide();
        //$('.error_remarks').hide();
        //$('.error_details_narration').hide();
        $('.error_duplicate_receipt_no').hide();
        var error = 0;
        /*
        if ($('input[name="receipt_no"]').val().trim() == '') {
          $('.error_receipt_no').show();
          error = 1;
        }
        */
        if ($('[name="receipt_date"]').val().trim() == '' || $('[name="receipt_date"]').val() == undefined) {
            $('.error_receipt_date').show();
            error = 1;
        }
        if ($('[name="account_id"]').val() == '' || $('[name="account_id"]').val() == undefined) {
            $('.error_account_id').show();
            error = 1;
        }
        /*
        if ($('#remarks').val() == '' || $('#remarks').val() == undefined) {
          $('.error_remarks').show();
          error = 1;
        }
        */
        /*if ($('[name="details_narration"]').val() == '' || $('[name="details_narration"]').val() == undefined) {
          $('.error_details_narration').show();
          error = 1;
        }*/
        /*var productIds = $('.cart-products').map(function() {
            return $(this).data('receipt_no').toString();
        }).get();
        */
        if (error == 0) {
            let formdata = new FormData($('.create_billing')[0]);

            $.ajax({
                    url: $('.create_billing').attr('action'),
                    data: formdata,
                    processData: false,
                    contentType: false,
                    type: 'POST',
                    success: function(response) {
                        if (response.success === true) {
                            toastr.success(response.message, 'Success.');
                            fetch_cart();

                            $('#details_narration').val('');
                            $('#account_id').val('');
                            $('[name="amount"]').val('');
                            $('[name="credit"]').val('');
                            $('[name="account_id"]').val('');

                        } else {
                            toastr.error(response.message, 'Error!');
                        }
                    }
                })
                .fail(function(jqXHR, textStatus, errorThrown) {
                    console.log('AJAX request failed:', textStatus, errorThrown);
                    toastr.error('An error occurred during the request.', 'Error!');
                });
        }

        error = 1;
    })

    $(document).on('click', '#create_patient', function() {
        $('#commonModalLabel').text('New Patient Registration');
        $('.save_button_span').text('Save Patient');
        $.ajax({
            url: "{!! route('patient-account-create') !!}",
            success: function(data) {
                $('#commonModal').find('.modal-body').html('');
                $('#commonModal').find('.modal-body').html(data);
                reinitializeTelInput();
                $('[name="date_of_birth"]').datepicker('destroy');

                $('[name="date_of_birth"]').datepicker({
                        "dateFormat": "dd-mm-yy",
                        "maxDate": '0',
                        "changeMonth": true,
                        "changeYear": true
                    }).datepicker("setDate", 'now')
                    .on('changeDate', function(ev) {
                        $(this).datepicker('hide');
                    })
                    .on('focusout', function(ev) {
                        $(this).datepicker('hide');
                    });
            }
        })
    })

    const patientSelect = document.querySelector(".accounts-select");
    const ReceiptAtSelect = document.querySelector(".receipt-at-select");
    const querySelector = document.querySelector(".searchResult");

    document.addEventListener("click", (event) => {
        if (event.target !== patientSelect && event.target !== querySelector) {
            $(".searchResult").empty();
        }
    });

    $(document).on('click change', '#account_id', function() {
        $('[name="search_product"]').val('');
        $('.create_billing [name="product_price"]').val('');
        $('#search_product').val('');
    })

    /*********delete data**********/
    $("body").on("click", '.deleteDataCustom', function(event) {
        dataString = {
            "id": $(this).data('id')
        };
        var UrlValue = $(this).data('url');
        var btn = $(this);

        Swal.fire({
            title: 'Are you sure you want to delete this?',
            icon: 'warning',
            showDenyButton: true,
            showCancelButton: false,
            confirmButtonText: 'Yes',
            denyButtonText: 'No',
        }).then((result) => {
            /* Read more about isConfirmed, isDenied below */
            if (result.isConfirmed) {
                $.ajax({
                    url: UrlValue,
                    method: 'post',
                    data: {
                        "_token": $('meta[name="csrf-token"]').attr('content'),
                        "id": $(this).data('id')
                    },
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                    beforeSend: function(xhr) {
                        // xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
                    },
                    success: function(response) {
                        if (response.success) {
                            toastr.success(response.message, 'Success.');
                            fetch_cart();
                        } else {
                            var ErroMsg = $(this).printErrorMsg(response.message);
                            $(this).Toastshow('error', ErroMsg);
                        }
                    },
                    error: function(data) {
                        console.log("error ", data);
                    }
                });
            }
        });
    });

    function getAge(birthdate) {
        if (birthdate != '' && birthdate != null && birthdate != undefined) {
            var birthdateObj = new Date(birthdate);
            var now = new Date();
            var age = now.getFullYear() - birthdateObj.getFullYear();

            // Adjust age if birthday hasn't occurred this year yet
            if (now.getMonth() < birthdateObj.getMonth() || (now.getMonth() === birthdateObj.getMonth() && now.getDate() < birthdateObj.getDate())) {
                age--;
            }
            return age;
        }
    };

   

    function validateDate() {
        //debugger;
        // Your date input field ID
        var dateInput = $("#receipt_date").val();
       
        var selectedDate = parseDateString(dateInput);
       
        var selectedOption = $("#financial_year_id option:selected");

        // Get the title attribute of the selected option
        var selectedTitle = selectedOption.attr("title");
        var dateParts = selectedTitle.split('-');

        // Extract individual values
        var startYear = dateParts[0];
        var endYear = dateParts[1];

        // Get the selected date from the input field
       //var selectedDate = new Date(dateInput.val());

        if (selectedDate >= new Date(startYear, 0, 1) && selectedDate <= new Date(endYear, 11, 31)) {
            return false;
        } else {
            return true;
        }
    };

    function parseDateString(dateString) {
    const formats = [
        'MM/DD/YYYY',
        'MM-DD-YYYY',
        'YYYY/MM/DD',
        'YYYY-MM-DD',
        'DD/MM/YYYY',
        'DD-MM-YYYY',
        'dd/mm/YYYY'
        // Add more formats as needed
    ];

    for (const fmt of formats) {
        const date = moment(dateString, fmt, true); // The `true` flag is for strict parsing
        if (date.isValid()) {
            return date.toDate(); // Convert moment object to JavaScript Date object
        }
    }

    console.error("Invalid date format");
    return null;
}

    /*************** Create Customer **************/
    $(document).on('click', '#create_account', function() {
        $('#commonModalLabel').text('New Party');
        $('.save_button_span').text('Save Party');
        $.ajax({
            url: "{!! route('party-account-create') !!}",
            success: function(data) {
                $('#commonModal').find('.modal-body').html('');
                $('#commonModal').find('.modal-body').html(data);

            }
        })
    })

    // Click event for the disabled edit_customer button
    $('#edit_customer').on('click', function() {
        var customerName = $('[name="account_id"]').val();

        if (customerName.trim() === "") {
            $('.error_account_id').show();

            setTimeout(function() {
                $('.error_account_id').hide();
            }, 3000);
        } else {
            $('.error_account_id').hide();

            $('#commonModalLabel').text('Edit Party');
            $('.save_button_span').text('Update Party');
            var id = $('[name="account_id"]').val();
            var url = `{!! route('party-account-edit', ':id') !!}`.replace(':id', id);

            $.ajax({
                url: url,
                success: function(data) {
                    $('#commonModal').modal('show');
                    $('#commonModal').find('.modal-body').html('');
                    $('#commonModal').find('.modal-body').html(data);
                }
            });
        }
    });

    var telInput = $('#phone_no , #whatsapp_no , #alternative_no');
    telInput.intlTelInput({
        utilsScript: 'https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.13/js/utils.js', // Update the URL to the correct one
        initialCountry: '{!! $countryCode  !!}', // Set the new country code
        separateDialCode: true
    });



    $(document).on('change input', '.amount', function(e) {
        var totalAmount = 0;
        var setZero = 0;

        $('.amount').each(function() {
            totalAmount += parseFloat($(this).val()) || 0;
        });

        
        
        var total = parseInt(totalAmount);
        $('#amount_recieved').val(total);

        
    });
</script>
@endsection