@extends('layouts.app')
@section('title','Sale Return')
@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;
    }

    .error {
        border: solid red 1px;
    }
</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> Sale Return</div>
    <div class="ps-3">
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb mb-0 p-0">

                <li class="breadcrumb-item active" aria-current="page">Edit Sale Return</li>
            </ol>
        </nav>
    </div>
    <div class="ms-auto">
        <div class="btn-group">
            <a href="{{route('sale-return.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_sale" action="{{ route('sale-return-product-add-to-cart')}}" method="post" enctype='multipart/form-data' id="create_sale">
            <!-- For validation comment on -->
            <!-- <form class="row g-3 was-validated"> -->
            @csrf

            <input type="hidden" name="invoice_id" id="invoice_id" value="{!! $sale_invoice->voucher_type_id??'' !!}">
            <div class="card style_table">
                <div class="card-body pt-2 ps-3" style="border-radius:0px;">
                    <div class="row align-items-center">
                        <div class="col-md-6">
                            <div>
                                <label class="form-label">Customer Name <span class="text-danger"><b>*</b></span></label>
                            </div>
                            <div class="input-group autocomplete">
                                <input type="text" name="" id="customer_id" class="customer-select form-control" placeholder="Search Customer" value="{!! $customer->full_name ?? '' !!}" {!! $customer->full_name ?'readonly': '' !!}>
                                <ul class="searchResult"></ul>
                                <div class="input-group-append" style="margin: auto 10px auto 0;">
                                    <button class="btn btn-secondary add_btn" id="create_customer" type="button" data-bs-toggle="modal" data-bs-target="#commonModal">+</button>
                                    <button class="btn btn-outline-secondary edit_btn" 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="customer_id" value="{!! $customer->id ?? '' !!}">
                            </div>
                            <span class="text-danger error_customer_id" style="display:none;">This field is required.</span>
                        </div>
                        <div class="col-md-2">
                            <div>
                                <label class="form-label">Referral Doctor <span class="text-danger"><b>*</b></span></label>
                            </div>
                            <div class="input-group autocomplete">
                                <select class="form-select" id="is_doctor" name="is_doctor">
                                    <option value="0" {!! isset($doctor->full_name) && $doctor->full_name != '' ? '' : 'selected' !!}>Self</option>
                                    <option value="1" {!! isset($doctor->full_name) && $doctor->full_name != '' ? 'selected' : '' !!}>Doctor</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div>
                                <label class="form-label">Doctor Name</label>
                            </div>
                            <div class="input-group autocomplete">
                                <input type="text" name="" id="doctor_id" class="doctor-select form-control" placeholder="Search Doctor" value="{!! $doctor->full_name ?? '' !!}" {!! isset($doctor->full_name) && $doctor->full_name != '' ? 'readonly disabled' : '' !!}>
                                <ul class="searchResult"></ul>
                                <div class="input-group-append" style="margin: auto 10px auto 0;">
                                    <button class="btn btn-secondary add_btn" id="create_doctor" type="button" data-bs-toggle="modal" data-bs-target="#commonModal" {!! isset($doctor->full_name) && $doctor->full_name != '' ? '' : 'disabled' !!}> + </button>
                                </div>
                                <input type="hidden" name="doctor_id" value="{!! $doctor->id ?? '' !!}">
                            </div>
                            <span class="text-danger error_doctor_id" style="display:none;">This field is required.</span>
                        </div>

                        <div class="col-md-6">
                            <div>
                                <label class="form-label">Items / Products <span class="text-danger"><b>*</b></span></label>
                            </div>
                            <div class="input-group autocomplete">
                                <input type="text" name="" id="search_product" class="search_product form-control" placeholder="Write Item Name or Item Code">
                                <ul class="searchResult" style="width: 100%;"></ul>
                                <input type="hidden" name="search_product" value="">
                                <input type="hidden" name="product_stock" value="">
                            </div>
                            <span class="text-danger error_product_id" style="display:none;">This field is required.</span>
                        </div>

                    </div>
                </div>

                <div class="row custom_grid align-items-end gx-0 mt-4 mb-3">
                    <div class="col-md-2">
                        <div class="input-group">
                            <input type="hidden" name="price_id">
                            <input type="hidden" name="batch_name">
                            <input type="hidden" name="expiry_date">
                            <input type="hidden" name="sale_invoice_detail_id" id="sale_invoice_detail_id" value="">
                            <label class="form-label">Batch. No <span class="text-danger"><b>*</b></span></label>
                            <select class="form-control br-0" id="batch" name="batch" required>
                            </select>
                        </div>
                        <span class="text-danger error_batch" style="display:none;">This field is required.</span>
                    </div>

                    <div class="col-md-1">
                        <div class="input-group">
                            <label for="main_qty" class="form-label">Main QTY</label>
                            <input type="number" name="main_qty" class="form-control br-0" value="" placeholder="Enter Main Qty">
                        </div>
                    </div>
                    <div class="col-md-1">
                        <div class="input-group">
                            <label for="loose_qty" class="form-label">Alt QTY</label>
                            <input type="number" name="loose_qty" class="form-control br-0" value="" placeholder="Enter Alt Qty">
                        </div>
                    </div>
                    <div class="col-md-1">
                        <div class="input-group">
                            <label for="free_qty" class="form-label">Free QTY</label>
                            <input type="number" name="free_qty" class="form-control br-0" value="" placeholder="Enter Free Qty">
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="input-group">
                            <label for="product_price" class="form-label">Product Price</label>
                            <input type="number" name="product_price" class="form-control br-0" value="" placeholder="Enter Product Price">
                        </div>
                    </div>
                    <div class="col-md-1">
                        <div class="input-group">
                            <label for="per_discount" class="form-label">Dis (%)</label>
                            <input type="number" name="per_discount" class="form-control br-0" value="" placeholder="Enter Discount %">
                        </div>
                    </div>
                    <div class="col-md-1">
                        <div class="input-group">
                            <label for="flat_discount" class="form-label">Dis (Amt)</label>
                            <input type="number" name="flat_discount" class="form-control br-0" value="" placeholder="Enter Discount Amount">
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="input-group">
                            <label for="product_detail" class="form-label">Product Note</label>
                            <input type="text" name="product_detail" class="form-control br-0" value="" placeholder="Enter Product Note">
                        </div>
                    </div>
                    <div class="col-md-1">
                        <button class="btn btn-primary add_to_cart w-100" type="button"><i class="bx bx-plus"></i></button>
                    </div>
                    <span class="text-danger error_duplicate_customer_id" style="display:none;">This Item is already added to cart.</span>
                </div>
            </div>

        </form>
        <div class="cart_products">
        </div>
    </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>
    $(document).ready(function() {
        fetch_cart();
    });

    function fetch_cart() {
        $.ajax({
            url: "{!! route('sale-return-product-cart', $id) !!}",
            success: function(data) {
                $('.cart_products').html('');
                $('.cart_products').html(data);
            }
        })
    }

    $(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();
            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($('#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="customer_id"]').val(response.data.id);
                                $('#customer_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!');
                    });
            }
        }
        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="customer_id"]').val(response.data.id);
                                $('#customer_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!');
                    });
            }
        }

        if ($('#commonModal').find('form').hasClass('create_doctor')) {
            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());
            }

            $('.error_name').hide();
            $('.error_email').hide();
            $('.error_phone').hide();
            $('.error_country_id').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 (error == 0) {
                let formdata = new FormData($('#create_doctor_form')[0]);

                $.ajax({
                        url: $('#create_doctor_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="doctor_id"]').val(response.data.id);
                                $('.doctor-select').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('change', '#is_doctor', function(e) {
        if ($('select[name="is_doctor"]').val() == '1') {
            $("#doctor_id").attr("readonly", false);
            $("#doctor_id").attr("disabled", false);
            $("#create_doctor").attr("readonly", false);
            $("#create_doctor").attr("disabled", false);
        } else {
            $("#doctor_id").attr("readonly", true);
            $("#doctor_id").val('');
            $("#doctor_id").attr("disabled", true);
            $("#create_doctor").attr("readonly", true);
            $("#create_doctor").attr("disabled", true);
        }
    });


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

        $('.error_customer_id').hide();
        $('.error_search_product').hide();
        $('.error_doctor_id').hide();
        $('.error_batch').hide();
        $('.error_duplicate_customer_id').hide();
        $('.error').removeClass('error');
        var error = 0;

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

        }
        if ($('[name="doctor_id"]').val().trim() == '' && $('select[name="is_doctor"]').val() == '1') {
            $('.error_doctor_id').show();
            error = 1;
        }
        if ($('select[name="is_doctor"]').val() == '') {
            $('#is_doctor').addClass('error');
            error = 1;
        }
        if ($('[name="search_product"]').val().trim() == '') {
            $('#search_product').addClass('error');
            $('#search_product').focus();
            error = 1;
        }
        if ($('[name="batch"]').val() == '' || $('[name="batch"]').val() == undefined) {
            $('#batch').addClass('error');
            $('#batch').focus();
            error = 1;
        }
        var productIds = $('.cart-products').map(function() {
            return $(this).data('price_id').toString();
        }).get();

        var isPresent = $.inArray($('[name="price_id"]').val(), productIds) !== -1;

        if (isPresent) {
            $('.error_duplicate_customer_id').show();
            error = 1;
        }

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

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

                            $('#create_sale #search_product').val('');
                            $('#create_sale [name="search_product"]').val('');
                            $('#create_sale [name="product_price"]').val('');
                            $('#create_sale [name="flat_discount"]').val('');
                            $('#create_sale [name="per_discount"]').val('');
                            $('#create_sale [name="main_qty"]').val('1');
                            $('#create_sale [name="alt_qty"]').val('');
                            $('#create_sale [name="free_qty"]').val('');
                            $('#create_sale [name="product_detail"]').val('');
                            $('#create_sale_return [name="sale_invoice_detail_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;
    })

    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).ready(function() {
        $('.customer-select').autocomplete({
            autoFocus: true,
            minLength: 0,
            source: function(request, response) {
                if (request.term.length < 2) {
                    $('[name="customer_id"]').val('');
                    return false;
                }

                $.ajax({
                    url: "{{ route('customer-account-search') }}",
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        search_text: request.term
                    },
                    success: function(json) {
                        if (json.error) {
                            $('[name="customer_id"]').val('');
                            return false;
                        }
                        response($.map(json.result, function(item) {
                            return {
                                id: item.id,
                                name: item.name,
                                code: item.code,
                                gender: item.gender,
                                phone_no: item.phone_no,
                                date_of_birth: item.date_of_birth,
                            };
                        }));
                    }
                });
            },
            select: function(event, ui) {
                event.preventDefault();
                var age = isNumber(ui.item.date_of_birth) && ui.item.date_of_birth != null ? ', ' + getAge(ui.item.date_of_birth) + ' Years' : '';
                var gender = ui.item.gender != null ? ', ' + ui.item.gender : '';
                var phone_no = ui.item.phone_no != null ? ', ' + ui.item.phone_no : '';
                var code = ui.item.code != null ? ', ' + ui.item.code : '';

                $(this).val(ui.item.name + code + gender + age + phone_no + "");
                $('[name="customer_id"]').val(ui.item.id);
                $.ajax({
                    url: '{!! route("cart-product-update") !!}',
                    method: 'post',
                    data: {
                        "_token": $('meta[name ="csrf-token"]').attr('content'),
                        "customer_id": ui.item.id,
                    }
                });
                return false;
            }
        }).data("ui-autocomplete")._renderItem = function(ul, item) {
            var age = isNumber(item.date_of_birth) && item.date_of_birth != null ? ', ' + getAge(item.date_of_birth) + ' Years' : '';
            var gender = item.gender != null ? ', ' + item.gender : '';
            var phone_no = item.phone_no != null ? ', ' + item.phone_no : '';
            var code = item.code != null ? ', ' + item.code : '';

            return $("<li>")
                .append("<a>" + item.name + code + gender + age + phone_no + "</a>")
                .appendTo(ul);
        };


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

                $.ajax({
                    url: "{{ route('billings-search-doctors') }}",
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        search_text: request.term
                    },
                    success: function(json) {
                        if (json.error) {
                            $('[name="doctor_id"]').val('');
                            return false;
                        }
                        response($.map(json.result, function(item) {
                            return {
                                id: item.id,
                                name: item.name,
                                code: item.code,
                                gender: item.gender,
                                phone_no: item.phone_no,
                                date_of_birth: item.date_of_birth,
                            };
                        }));
                    }
                });
            },
            select: function(event, ui) {
                event.preventDefault();
                var age = isNumber(ui.item.date_of_birth) && ui.item.date_of_birth != null ? ', ' + getAge(ui.item.date_of_birth) + ' Years' : '';
                var gender = ui.item.gender != null ? ', ' + ui.item.gender : '';
                var phone_no = ui.item.phone_no != null ? ', ' + ui.item.phone_no : '';
                var code = ui.item.code != null ? ', ' + ui.item.code : '';

                $(this).val(ui.item.name + code + gender + age + phone_no + "");
                $('[name="doctor_id"]').val(ui.item.id);

                $.ajax({
                    url: '{!! route("cart-product-update") !!}',
                    method: 'post',
                    data: {
                        "_token": $('meta[name ="csrf-token"]').attr('content'),
                        "doctor_id": ui.item.id,
                    }
                });

                return false;
            }
        }).data("ui-autocomplete")._renderItem = function(ul, item) {
            var age = isNumber(item.date_of_birth) && item.date_of_birth != null ? ', ' + getAge(item.date_of_birth) + ' Years' : '';
            var gender = item.gender != null ? ', ' + item.gender : '';
            var phone_no = item.phone_no != null ? ', ' + item.phone_no : '';
            var code = item.code != null ? ', ' + item.code : '';

            return $("<li>")
                .append("<a>" + item.name + code + gender + age + phone_no + "</a>")
                .appendTo(ul);
        };

        $(document).on('keyup change input', '#search_product,[name="product_price"], [name="flat_discount"], [name="per_discount"]', function(event) {
            if ($('[name="search_product"]').val().trim() != '') {
                if (event.keyCode === 13) {
                    $(".add_to_cart").trigger('click');
                }
            }
        });
        $('#search_product').autocomplete({
            autoFocus: true,
            minLength: 0,
            source: function(request, response) {
                if (request.term.length < 2) {
                    $('.create_billing [name="search_product"]').val('');
                    $('.create_billing [name="product_price"]').val('');
                    $('.create_billing [name="price_id"]').val('');
                    $('.create_billing [name="sale_invoice_detail_id"]').val('');
                    return false;
                }

                var batch = $('#batch option:selected').val();
                var invoice_id = $('#invoice_id').val();

                $.ajax({
                    url: "{{ route('customer-return-search-products') }}",
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        batch: batch,
                        invoice_id: invoice_id,
                        search: request.term,
                    },
                    success: function(json) {
                        if (json.error) {
                            $('.add_to_cart').attr('id', '');
                            $('.add_to_cart').data('id', '');
                            return false;
                        }
                        response($.map(json.result, function(item) {
                            return {
                                id: item.id,
                                price_id: item.price_id,
                                name: item.name,
                                code: item.shortcode,
                                short: item.hsncode,
                                mrp: item.mrp,
                                main_qty: item.main_qty,
                                sale_invoice_detail_id: item.sale_invoice_detail_id
                            };
                        }));
                    }
                });
            },
            select: function(event, ui) {
                $('#batch').empty();

                $('#search_product').val(ui.item.name);
                $('[name="search_product"]').val(ui.item.id);
                $('[name="product_price"]').val(ui.item.mrp);
                $('[name="price_id"]').val(ui.item.price_id);
                $('[name="batch"]').val(ui.item.batch);
                $('[name="main_qty"]').val(ui.item.main_qty);
                $('[name="sale_invoice_detail_id"]').val(ui.item.sale_invoice_detail_id);

                getBatchInformation(ui.item.id, ui.item.price_id, ui.item.batch);

                $('#search_product').trigger('keypress', {
                    which: 9
                });

                return false;
            }
        }).data("ui-autocomplete")._renderItem = function(ul, item) {
            return $("<li>")
                .addClass("custom-ui-li")
                .append("<a>" + item.name + "</a>")
                .appendTo(ul);
        };

        function getBatchInformation(productId, selectedBatchId) {
            $.ajax({
                url: "{{ route('get-batch-wise-price-information') }}",
                type: 'POST',
                dataType: 'json',
                data: {
                    productId: productId,
                    moduleCode: 'SALE_RETURN'
                },
                success: function(response) {
                    if (response.error) {
                        console.error(response.error);
                    } else {
                        updateBatchDropdown(response.batchInfo, selectedBatchId);
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Error retrieving batch information:', error);
                }
            });
        }

        function updateBatchDropdown(batchInfo, selectedBatchId) {
            var $batchDropdown = $('#batch');
            var $mrpInput = $('input[name="product_price"]'); // The input field where you want to assign the MRP value

            $batchDropdown.empty();

            $batchDropdown.append('<option value="">Select Batch</option>');

            $.each(batchInfo, function(index, batchOption) {
                console.log(batchOption);
                // Original date as a string
                let dateStr = batchOption.exp_date;

                // Create a new Date object
                let dateObj = new Date(dateStr);

                // Array of month names
                let monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

                // Get the month and year
                let month = monthNames[dateObj.getMonth()]; // Adding 1 to move to June
                let year = dateObj.getFullYear().toString().slice(-2); // Get the last two digits of the year

                // Concatenate the month and year
                let formattedDate = `${month}-${year}`;

                if (batchOption) {
                    var option = $('<option>', {
                        value: batchOption.id,
                        text: 'Batch: ' + batchOption.batch + ' | Ex.:' + formattedDate + ' | MRP: ' + batchOption.mrp + ' | Stock: ' + batchOption.current_stock,
                        'data-mrp': batchOption.mrp,
                        'data-batch_name': batchOption.batch ?? '',
                        'data-stock': batchOption.current_stock ?? '',
                        'data-expiry': formattedDate ?? '',
                    });

                    $batchDropdown.append(option);

                    // Check if this is the selected batch and set the MRP input value
                    if (batchOption.id == selectedBatchId) {
                        $mrpInput.val(batchOption.mrp);
                        $('input[name="price_id"]').val(batchOption.id);
                        $('input[name="batch_name"]').val(batchOption.batch);
                        $('input[name="product_stock"]').val(batchOption.current_stock);
                        $('input[name="expiry_date"]').val(formattedDate);
                    }
                }
            });

            // If no batch was pre-selected, set the MRP for the first batch
            if (!$batchDropdown.find('option:selected').val()) {
                var firstBatchMrp = batchInfo.length > 0 ? batchInfo[0].mrp : '';
                var firstBatchId = batchInfo.length > 0 ? batchInfo[0].id : '';
                var batch_name = batchInfo.length > 0 ? batchInfo[0].batch : '';
                var stock = batchInfo.length > 0 ? batchInfo[0].current_stock : '';
                // Original date as a string
                let dateStr = batchInfo[0].exp_date;

                // Create a new Date object
                let dateObj = new Date(dateStr);

                // Array of month names
                let monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

                // Get the month and year
                let month = monthNames[dateObj.getMonth()]; // Adding 1 to move to June
                let year = dateObj.getFullYear().toString().slice(-2); // Get the last two digits of the year

                // Concatenate the month and year
                let formattedDate = `${month}-${year}`;

                $mrpInput.val(firstBatchMrp);
                $('input[name="price_id"]').val(firstBatchId);
                $('input[name="batch_name"]').val(batch_name);
                $('input[name="product_stock"]').val(stock);
                $('input[name="expiry_date"]').val(formattedDate);
            }

            $batchDropdown.find('option:eq(1)').prop('selected', true);

            $('#create_sale_return [name="main_qty"]').focus();
        };

        $('#batch').on('change', function() {
            var priceId = $(this).val();
            var selectedMrp = $(this).find('option:selected').data('mrp');
            var selectedBatch = $(this).find('option:selected').data('batch_name');
            var selectedStock = $(this).find('option:selected').data('stock');
            var selectedExpiry = $(this).find('option:selected').data('expiry');
            var search_product = $('#search_product').val();

            $('input[name="product_price"]').val(selectedMrp);
            $('input[name="price_id"]').val(priceId);
            $('input[name="batch_name"]').val(selectedBatch);
            $('input[name="product_stock"]').val(selectedStock);
            $('input[name="expiry_date"]').val(selectedExpiry);
            $('#create_sale_return [name="main_qty"]').focus();
            if (selectedStock == 0) {
                $('#selectedProduct').html(search_product)
                $('#selectedBatch').html(selectedBatch)
                $('#current_stock_div').css('display', 'block');
            } else {
                $('#selectedProduct').html('')
                $('#selectedBatch').html('')
                $('#current_stock_div').css('display', 'none');
            }
        });


    });

    const customerSelect = document.querySelector(".customer-select");
    const doctorSelect = document.querySelector(".doctor-select");
    const querySelector = document.querySelector(".searchResult");

    document.addEventListener("click", (event) => {
        if (event.target !== customerSelect && event.target !== doctorSelect && event.target !== querySelector) {
            $(".searchResult").empty();
        }
    });
    /*************** Create Customer **************/
    $(document).on('click', '#create_customer', function() {
        $('#commonModalLabel').text('New Customer');
        $('.save_button_span').text('Save Customer');
        $.ajax({
            url: "{!! route('customer-account-create') !!}",
            success: function(data) {
                $('#commonModal').find('.modal-body').html('');
                $('#commonModal').find('.modal-body').html(data);

            }
        })
    })

    $(document).ready(function() {

        $(document).on('click', '#create_doctor', function() {
            $('#commonModalLabel').text('Add New Doctor');
            $('.save_button_span').text('Save Doctor');
            $.ajax({
                url: "{!! route('doctor-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');
                        });
                }
            })
        })


        // 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
        $('#customer_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);
            }
        });

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

            if (customerName.trim() === "") {
                $('.error_customer_id').show();
            } else {
                $('.error_customer_id').hide();

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

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



    function reinitializeTelInput(countryCode) {
        var telInput = $('#commonModal').find('#phone_no , #whatsapp_no , #alternative_no');
        telInput.intlTelInput('destroy'); // Destroy the existing instances

        telInput.intlTelInput({
            utilsScript: "https://cdn.jsdelivr.net/npm/intl-tel-input@18.2.1/build/js/utils.js",
            initialCountry: countryCode || '{!! $countryCode !!}',
            separateDialCode: true
        });
    }



    $(document).on('focusout', '.cart-products [name="tax_per"]', function() {
        var product_id = $(this).data('product_id');

        $.ajax({
            url: '{!! route("sale-return-cart-product-update") !!}',
            method: 'post',
            data: {
                "_token": $('meta[name ="csrf-token"]').attr('content'),
                "id": $(this).data('price_id'),
                "tax_per": $(this).val(),
            },
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                if (response.success) {
                    fetch_cart();
                }
            },
            error: function(data) {
                console.log("error ", data);
            }
        });
    })

    $(document).on('focusout', '.cart-products [name="loose_qty"]', function() {
        var product_id = $(this).data('product_id');

        $.ajax({
            url: '{!! route("sale-return-cart-product-update") !!}',
            method: 'post',
            data: {
                "_token": $('meta[name ="csrf-token"]').attr('content'),
                "id": $(this).data('price_id'),
                "loose_qty": $(this).val(),
            },
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                if (response.success) {
                    fetch_cart();
                }
            },
            error: function(data) {
                console.log("error ", data);
            }
        });
    })

    $(document).on('focusout', '.cart-products [name="product_detail"]', function() {
        var product_id = $(this).data('product_id');

        $.ajax({
            url: '{!! route("sale-return-cart-product-update") !!}',
            method: 'post',
            data: {
                "_token": $('meta[name ="csrf-token"]').attr('content'),
                "id": $(this).data('price_id'),
                "product_detail": $(this).val(),
            },
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                if (response.success) {
                    fetch_cart();
                }
            },
            error: function(data) {
                console.log("error ", data);
            }
        });
    })

    function updateCartQuantity(productId, quantity) {
        $.ajax({
            url: '{!! route("sale-return-cart-product-update") !!}',
            method: 'post',
            data: {
                "_token": $('meta[name ="csrf-token"]').attr('content'),
                "id": productId,
                "main_qty": quantity,
            },
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                if (response.success) {
                    fetch_cart();
                }
            },
            error: function(data) {
                console.log("error ", data);
            }
        });
    }


    $(document).on('focusout', '.cart_products [name="product_price"]', function() {
        var product_id = $(this).data('product_id');

        $.ajax({
            url: '{!! route("sale-return-cart-product-update") !!}',
            method: 'post',
            data: {
                "_token": $('meta[name ="csrf-token"]').attr('content'),
                "id": $(this).data('price_id'),
                "product_price": $(this).val(),
            },
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                if (response.success) {
                    fetch_cart();
                }
            },
            error: function(data) {
                console.log("error ", data);
            }
        });
    })

    $(document).on('focusout', '.cart_products [name="flat_discount"]', function() {
        var product_id = $(this).data('product_id');

        $.ajax({
            url: '{!! route("sale-return-cart-product-update") !!}',
            method: 'post',
            data: {
                "_token": $('meta[name ="csrf-token"]').attr('content'),
                "id": $(this).data('price_id'),
                "flat_discount": $(this).val(),
            },
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                if (response.success) {
                    fetch_cart();
                }
            },
            error: function(data) {
                console.log("error ", data);
            }
        });
    })

    $(document).on('focusout', '.cart_products [name="per_discount"]', function() {
        var product_id = $(this).data('product_id');

        $.ajax({
            url: '{!! route("sale-return-cart-product-update") !!}',
            method: 'post',
            data: {
                "_token": $('meta[name ="csrf-token"]').attr('content'),
                "id": $(this).data('price_id'),
                "per_discount": $(this).val(),
            },
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                if (response.success) {
                    fetch_cart();
                }
            },
            error: function(data) {
                console.log("error ", data);
            }
        });
    })

    /*********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('price_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) {
                            var ErroMsg = $(this).printErrorMsg(response.message);

                            $(this).Toastshow('success', ErroMsg);
                            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 isNumber(value) {
        return typeof value === 'number';
    }

    function delay(callback, ms) {
        var timer = 0;
        return function() {
            var context = this,
                args = arguments;
            clearTimeout(timer);
            timer = setTimeout(function() {
                callback.apply(context, args);
            }, ms || 0);
        };
    }
    // Listen for focusout event on the quantity input field
    $(document).on('focusout', '.cart_products [name="main_qty"]', delay(function() {
        updateCartQuantity($(this).data('price_id'), $(this).val());
    }, 700));
</script>
@endsection