@extends('layouts.app')
@section('title','IPD Billings')
@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;
    }
    .breadcrumb-title {
        border: none;
    }
</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> IPD Billings</div>
    <!-- <div class="ps-3">
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb mb-0 p-0">

                <li class="breadcrumb-item active" aria-current="page">Add New Ipd Admission Billing</li>
            </ol>
        </nav>
    </div> -->
    <div class="ms-auto">
        <div class="btn-group">
            <a href="javascript:history.back()" 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" action="{{ route('ipd-products-add-to-cart')}}" 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-header d-flex align-items-center justify-content-between">
                            <h6 class="mb-0">Billing Information</h6>
                            <a href="javascript:void(0)" class="hiddenReferral fw-bold" id="add_reference"><i class="bx bx-plus"></i> Add Refferal</a>
                        </div>
                    <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">Patient Name <span class="text-danger"><b>*</b></span></label>
                            </div>
                            <div class="input-group autocomplete">
                                <input disabled type="text" name="" id="patient_id" class="patient-select form-control" placeholder="Search Patient" value="{{ $patient_details->account_title->name . ' ' . $patient_details->name . ' - (' . $patient_details->code . '), ' . $patient_details->account_contact->gender->name . ', ' . age($patient_details->account_contact->date_of_birth) . ' Years, ' . $patient_details->account_contact->phone_no }}">
                                <input type="hidden" name="patient_id" value="{!! $patient_details->id ?? '' !!}">
                            </div>
                            <span class="text-danger error_patient_id" style="display:none;">This field is required.</span>
                        </div>
                        <div class="col-md-6">
                            <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 ?? '' !!}">
                                <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"> + </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">Patient Name <span class="text-danger"><b>*</b></span></label>
                            </div>
                            <div class="input-group autocomplete">
                                <input type="text" name="" id="patient_id" readonly disabled class="patient-select form-control" placeholder="Search Patient" value="{!! $patient->full_name ?? '' !!}">
                                <!-- <ul class="searchResult"></ul>
                                <div class="input-group-append" style="margin: auto 10px auto 0;">
                                    <button class="btn btn-secondary add_btn" id="create_patient" type="button" data-bs-toggle="modal" data-bs-target="#commonModal">+</button>
                                </div> -->
                                <input type="hidden" name="patient_id" value="{!! $patient->id ?? '' !!}">
                            </div>
                            <span class="text-danger error_patient_id" style="display:none;">This field is required.</span>
                        </div>

                        <div class="col-md-6">
                            <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 class="references mt-3" {!! isset($refferal_lab) && $refferal_lab != '' ? '' : 'style="display:none;"' !!}>
                            <label class="form-label">Refferal Lab / Partner Name</label>
                            <div class="input-group autocomplete">
                                <input type="text" name="" class="refferal-select form-control" placeholder="Search Referral Lab.." value="{!! $refferal_lab->full_name ?? '' !!}">
                                <ul class="searchResult"></ul>
                                <div class="input-group-append" style="margin: auto 10px auto 0;">
                                    <button class="btn btn-secondary add_btn" id="create_referral_lab" type="button" data-bs-toggle="modal" data-bs-target="#commonModal"> + </button>
                                </div>
                                <input type="hidden" name="refferal_id" value="{!! $refferal_lab->id ?? '' !!}">
                            </div>
                            <span class="text-danger error_refferal_id" style="display:none;">This field is required.</span>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="references mt-3" {!! isset($collection_agent) && $collection_agent != '' ? '' : 'style="display:none;"' !!}>
                            <label class="form-label">Collection Agent Name</label>
                            <div class="input-group autocomplete">
                                <input type="text" name="" class="collection-select form-control" placeholder="Search Collection Agent.." value="{!! $collection_agent->full_name ?? '' !!}">
                                <ul class="searchResult"></ul>
                                <div class="input-group-append" style="margin: auto 10px auto 0;">
                                    <button class="btn btn-secondary add_btn" id="create_collection_lab" type="button" data-bs-toggle="modal" data-bs-target="#commonModal"> + </button>
                                </div>
                                <input type="hidden" name="collection_id" value="{!! $collection_agent->id ?? '' !!}">
                            </div>
                            <span class="text-danger error_collection_id" style="display:none;">This field is required.</span>
                            </div>
                        </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">
                                <label class="form-label">Brand / Category <span class="text-danger"><b>*</b></span></label>
                                <select class="form-control br-0" id="brand_id" name="brand_id" required>
                                    @foreach($brands as $list)
                                    <option value="{{ $list->id}}" {!! $list->is_default == 1 ? 'selected' : '' !!}>{{$list->name}}</option>
                                    @endforeach
                                </select>
                            </div>
                            <span class="text-danger error_brand_id" style="display:none;">This field is required.</span>
                        </div>
                        <div class="col-md-3">
                            <div class="input-group autocomplete">
                                <label class="form-label">Test / Item Name <span class="text-danger"><b>*</b></span></label>
                                <input type="text" name="" id="search_product" class="search_product form-control" placeholder="Write Test Name or Test Code">
                                <ul class="searchResult" style="width: 100%;"></ul>
                                <input type="hidden" name="search_product" value="">
                            </div>
                            <span class="text-danger error_search_product" style="display:none;">This field is required.</span>
                        </div>
                        <div class="col-md-2">
                            <div class="input-group">
                                <label for="product_price" class="form-label">Item Price</label>
                                <input type="number" name="product_price" class="form-control br-0" value="" placeholder="Enter Item Price">
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="input-group">
                                <label for="flat_discount" class="form-label">Discount (Flat)</label>
                                <input type="number" name="flat_discount" class="form-control br-0" value="" placeholder="Enter Item Discount">
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="input-group">
                                <label for="per_discount" class="form-label">Discount (%)</label>
                                <input type="number" name="per_discount" class="form-control br-0" value="" placeholder="Enter Item Discount">
                            </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_patient_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('ipd-billing-product-cart', $id) !!}?page=billingEdit",
        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_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() == '') {
              $('.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() == '' &&
                $('input[name="year"]').val() == '' &&
                $('input[name="month"]').val() == '' &&
                $('input[name="day"]').val() == ''
            ) {
              $('.error_date_of_birth').show();
              error = 1;
            }

            if ($('#age_years').val() == '') {
                $('.error_date_of_birth').show();
                error = 1;
                setTimeout(function () {
                    $('.error_date_of_birth').hide();
                }, 3000);
            }

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

        if ($('#commonModal').find('form').hasClass('create_referral')) {
            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_organization').hide();
            var error = 0;

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

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

                $.ajax({
                    url: $('#create_referral_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="refferal_id"]').val(response.data.id);
                            $('.refferal-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!');
                });
            }
        }

        if ($('#commonModal').find('form').hasClass('create_collection_lab')) {
            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() == '') {
              $('.error_name').show();
              error = 1;
            }
            if ($('input[name="phone_no"]').val().trim() == '') {
              $('.error_phone').show();
              error = 1;
            }

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

                $.ajax({
                    url: $('#create_collection_lab_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="collection_id"]').val(response.data.id);
                            $('.collection-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_patient_id').hide();
        $('.error_doctor_id').hide();
        $('.error_search_product').hide();
        $('.error_brand_id').hide();
        $('.error').removeClass('error');
        var error = 0;

        if ($('input[name="patient_id"]').val().trim() == '') {
          $('.error_patient_id').show();
          error = 1;
        }
        if ($('[name="doctor_id"]').val().trim() == '') {
          $('.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="brand_id"]').val() == '' || $('[name="brand_id"]').val() == undefined) {
          $('#brand_id').addClass('error');
          $('#brand_id').focus();
          error = 1;
        }
        var productIds = $('.cart-products').map(function() {
            return $(this).data('patient_id').toString();
        }).get();

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



        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();

                        $('.create_billing #search_product').val('');
                        $('.create_billing [name="search_product"]').val('');
                        $('.create_billing [name="product_price"]').val('');
                        $('.create_billing [name="flat_discount"]').val('');
                        $('.create_billing [name="per_discount"]').val('');
                        $('.create_billing [name="price_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(){
        $('.patient-select').autocomplete({
            autoFocus: true,
            minLength: 0,
            source: function(request, response) {
                if (request.term.length < 2) {
                    $('[name="patient_id"]').val('');
                    return false;
                }

                $.ajax({
                    url: '{{ route('billings-search-patients') }}',
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        action: 'get_patients_for_billing',
                        search_text: request.term
                    },
                    success: function(json) {
                        if (json.error) {
                            $('[name="patient_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      = 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="patient_id"]').val(ui.item.id);

                $.ajax({
                  url     : '{!! route("cart-product-update") !!}',
                  method  : 'post',
                  data    : {
                        "_token": $('meta[name ="csrf-token"]').attr('content'),
                        "patient_id": ui.item.id,
                  }
                });
                return false;
            }
        }).data("ui-autocomplete")._renderItem = function(ul, item) {
            var age      = 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      = 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      = 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);
        };

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

                $.ajax({
                    url: '{{ route('billings-search-referral') }}',
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        search_text: request.term
                    },
                    success: function(json) {
                        if (json.error) {
                            $('[name="refferal_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      = 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="refferal_id"]').val(ui.item.id);

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

                return false;
            }
        }).data("ui-autocomplete")._renderItem = function(ul, item) {
            var age      = 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);
        };

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

                $.ajax({
                    url: '{{ route('billings-search-collection') }}',
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        search_text: request.term
                    },
                    success: function(json) {
                        if (json.error) {
                            $('[name="collection_id"]').val('');
                            return false;
                        }
                        response($.map(json.result, function(item) {
                            return {
                                id: item.id,
                                code: item.code,
                                name: item.name,
                                gender: item.gender ,
                                phone_no: item.phone_no,
                                date_of_birth: item.date_of_birth,
                            };
                        }));
                    }
                });
            },
            select: function(event, ui) {
                event.preventDefault();
                var age      = 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="collection_id"]').val(ui.item.id);

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

                return false;
            }
        }).data("ui-autocomplete")._renderItem = function(ul, item) {
            var age      = 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', '[name="product_price"], [name="flat_discount"], [name="per_discount"]', function(event) {
            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('');
                    return false;
                }

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

                $.ajax({
                    url: '{{ route('ipd-billings-search-product') }}',
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        brand_id: brand_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
                            };
                        }));
                    }
                });
            },
            select: function(event, ui) {
                $('.create_billing #search_product').val(ui.item.name);
                $('.create_billing [name="search_product"]').val(ui.item.id);
                $('.create_billing [name="product_price"]').val(ui.item.mrp);
                $('.create_billing [name="price_id"]').val(ui.item.price_id);
                return false;
            }
        }).data("ui-autocomplete")._renderItem = function(ul, item) {
            return $("<li>")
                .addClass("custom-ui-li")
                .append("<a>" + item.name + " | Price:" + item.mrp + "</a>")
                .appendTo(ul);
        };
    });

    const patientSelect = document.querySelector(".patient-select");
    const doctorSelect  = document.querySelector(".doctor-select");
    const querySelector = document.querySelector(".searchResult");

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

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

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

    $(document).on('click', '#create_referral_lab', function(){
        $('#commonModalLabel').text('Add New Referral Laboratory');
        $('.save_button_span').text('Save Referral Laboratory');
        $.ajax({
          url:"{!! route('referral-lab-account-create') !!}",
          success:function(data){
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);
            reinitializeTelInput();
          }
        })
    })

    $(document).on('click', '#create_collection_lab', function(){
        $('#commonModalLabel').text('Add New Collection Agent');
        $('.save_button_span').text('Save Collection Agent');
        $.ajax({
          url:"{!! route('collection-agent-account-create') !!}",
          success:function(data){
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);
            reinitializeTelInput();
          }
        })
    })

    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('click', '#add_reference', function(){
        if ($('#add_reference').hasClass('hiddenReferral')) {
            $('.references').show();
            $('#add_reference').html('<i class="bx bx-minus"></i> Hide Referral');
            $('#add_reference').removeClass('hiddenReferral');
        } else {
            $('.references').hide();
            $('#add_reference').html('<i class="bx bx-plus"></i> Add Referral');
            $('#add_reference').addClass('hiddenReferral');
            $('.refferal-select').val('');
            $('.collection-select').val('');
            $('[name="refferal_id"]').val('');
            $('[name="collection_id"]').val('');
        }
    })

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

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

        $.ajax({
          url     : '{!! route("cart-product-update") !!}',
          method  : 'post',
          data    : {
                "_token": $('meta[name ="csrf-token"]').attr('content'),
                "id": $(this).data('patient_id'),
                "product_details": $(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', '[name="vial_code"]', function(){
        var product_id = $(this).data('product_id');

        $.ajax({
          url     : '{!! route("cart-product-update") !!}',
          method  : 'post',
          data    : {
                "_token": $('meta[name ="csrf-token"]').attr('content'),
                "id": $(this).data('patient_id'),
                "vial_code": $(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_price"]', function(){
        var product_id = $(this).data('product_id');

        $.ajax({
          url     : '{!! route("cart-product-update") !!}',
          method  : 'post',
          data    : {
                "_token": $('meta[name ="csrf-token"]').attr('content'),
                "id": $(this).data('patient_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="per_discount"]', function(){
        var product_id = $(this).data('product_id');

        $.ajax({
          url     : '{!! route("cart-product-update") !!}',
          method  : 'post',
          data    : {
                "_token": $('meta[name ="csrf-token"]').attr('content'),
                "id": $(this).data('patient_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);
          }
        });
    })

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

        $.ajax({
          url     : '{!! route("cart-product-update") !!}',
          method  : 'post',
          data    : {
                "_token": $('meta[name ="csrf-token"]').attr('content'),
                "id": $(this).data('patient_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("cart-product-update") !!}',
          method  : 'post',
          data    : {
                "_token": $('meta[name ="csrf-token"]').attr('content'),
                "id": $(this).data('patient_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('patient_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;
        }
    };
</script>
@endsection
