@extends('layouts.app')
@section('title','Lab Billing Report')
@section('pages')
<style type="text/css">
    .breadcrumb-title {
      border-right: none;
    }
    .input_error {
      border-color: red;
    }
       /* @foreach($style as $styles)
        .{{$styles->code}} {
            color: {{$styles->font_color}};
            background-color: {{$styles->bg_color}};
            font-family: {{$styles->font_family}};
            text-decoration: {{$styles->text_decoration}};
            font-size: {{$styles->font_size}};
            font-styles: {{$styles->font_styles}};
            font-weight: {{$styles->font_weight}};
            padding: {{$styles->font_padding}};
        }
    @endforeach */
    .ck-file-dialog-button {
      display: none !important;
    }
    .ck-editor__editable_inline {
        min-height: 200px;
    }
    .list-group {
      position: absolute;
      min-width: 160px;
      font-size: 14px;
      text-align: left;
      list-style: none;
      background-color: #fff;
      z-index: 1;
    }
    .list-group-item.active {
      z-index: 2;
      color: #fff;
      background-color: #596d89;
      border-color: #616a7a;
    }
    .list-group-item {
        position: relative;
        display: block;
        padding: .5rem 1rem;
        color: #ffffff;
        text-decoration: none;
        background-color: #596d89;
        border: 1px solid rgba(0,0,0,.125);
    }
    .list-group-item+.list-group-item {
        border-top-width: 0;
        background-color: aliceblue;
        color: #000;
    }
    .list-group-item+.list-group-item.active {
        margin-top: -1px;
        border-top-width: 1px;
        background-color: #596d89;
        color: #fff;
    }
</style>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" integrity="sha512-nMNlpuaDPrqlEls3IX/Q56H36qvBASwb3ipuo3MxeWbsQB1881ox0cRv7UPTgBlriqoynt35KjEwgGUeUXIPnw==" crossorigin="anonymous" referrerpolicy="no-referrer" />
  <!--breadcrumb-->
  <div class="page-breadcrumb row align-items-center justify-content-between mb-3 px-3 px-md-0">
    <div class="breadcrumb-title col-md-6"> Lab Billing Report
    </div>
    <div class="col-md-6">
      <nav aria-label="breadcrumb">
        <ol class="breadcrumb justify-content-md-end mb-0">
          <li class="breadcrumb-item"><i class="bi bi-info-circle-fill text-info show-help-support" data-id="28" data-bs-toggle="modal" data-bs-target="#commonModal"></i></li>
          <li class="breadcrumb-item" aria-current="page">Pathology</li>
        </ol>
      </nav>
    </div>
  </div>
  <!--end breadcrumb-->

  <div class="card style_table shadow-none radius-5 min-height">
    <div class="card-header py-3">
      @include('layouts.partials.nav-menu')
      <div class="row gx-2">
        <div class="col-lg-5 col-md-5 col-8">
             <div class="position-relative">
                <h3>Investigation Result</h3>
            </div>
        </div>

        <div class="col-lg-7 col-md-7">
          <div class="ms-auto float-md-end">

            <div class="btn-group">
                <a href="{{ request()->get('redirect_route') != '' ? route(request()->get('redirect_route')) : route('lab-reporting') }}" class="btn btn-outline-secondary me-1"><i class="bx bx-arrow-back ms-0 me-1"></i>Back</a>
            </div>

          </div>
        </div>
      </div>
    </div>
    <div class="card-header py-3">
      <div class="row gx-2">
        {{-- @php $companyName = @$sale_invoice->getCompany->name; @endphp
        @php
          $voucherTitle = $voucher_type->name;
          $voucherType = $voucher_type->code;
        @endphp
        @include('components.voucher-details') --}}
        <div class="row py-1 m-0">
          <div class="col-4 row border-right border-dark">
            <table>
              <tbody>
                <tr>
                  <td>Patient Name </td>
                  <td>: <b>{!! $sale_invoice->patent_name ?? '' !!}</b></td>
                </tr>
                <tr>
                  <td>Sex/Age </td>
                  <td>: <b>{!! $sale_invoice->gender ?? '' !!}</b></td>
                </tr>
                <tr>
                  <td>Address </td>
                  <td>: <b>{!! $sale_invoice->address_line1 ?? '' !!}</b></td>
                </tr>
                <tr>
                  <td>State Name </td>
                  <td>: <b>{!! $sale_invoice->state ?? '' !!}</b></td>
                </tr>
                <tr>
                  <td colspan="2">Remarks for Technician : {!! $sale_invoice->remarks_for_technician ?? '' !!}</td>
                </tr>
              </tbody>
            </table>
          </div>
          <div class="col-5 row">
            <table>
              <tbody>
                <tr>
                  <td>Invoice No </td>
                  <td>: <b>{!! $sale_invoice->voucher_type_invoice_no ?? '' !!}</b></td>
                </tr>
                <tr>
                  <td>Main Invoice No </td>
                  <td>: <b>{!! $sale_invoice->main_invoice_no ?? '' !!}</b></td>
                </tr>
                <tr>
                  <td>Invoice Date </td>
                  <td>: <b>{!! formatedDate($sale_invoice->invoice_date) ?? '' !!}</b></td>
                </tr>
                <tr>
                  <td>Phone No </td>
                  <td>: <b>{!! $sale_invoice->phone_no ?? '' !!}</b></td>
                </tr>
                @if (!empty($sale_invoice->special_case))
                  <tr>
                    <td>Special Case </td>
                    <td><b>{!! $sale_invoice->special_case ?? '' !!}</b></td>
                  </tr>
                @endif
              </tbody>
            </table>
          </div>
          <div class="col-2 text-center pt-1" style="width:auto !important;">
            <div class="">
                {!! DNS1D::getBarcodeHTML($sale_invoice->voucher_type_invoice_no, 'C93') !!}
                <h4>{!! $sale_invoice->voucher_type_invoice_no ?? '' !!}</h4>
            </div>
         </div>
        </div>
      </div>
    </div>
    @php
      $gender = $sale_invoice->account_gender_id ?? '1';
      $date_of_birth = $sale_invoice->date_of_birth ?? '';
      $age           = $date_of_birth != '' ? ageInHours($sale_invoice->date_of_birth) : 0;
    @endphp
    <div class="card-body">
        <div class="row auto">
            <div class="col-xl-12 mx-auto">
                <div class=" shadow-none radius-5 ">
                  <form class="row auto-width mt-0" action="{{ route('billing-report.store',$sale_invoice->id)}}" method="post" enctype='multipart/form-data' id="billing_report">


                    <div class="row auto-width p-2">
                        @csrf
                        @if(request()->get('redirect_route') != '')
                            <input type="hidden" name="redirect_route" value="{!! request()->get('redirect_route') !!}">
                        @endif
                        @foreach($testPackages as $key => $value)

                        @if ((request()->get('department') != '' &&
                          request()->get('department') == $value['department_id']) ||
                          request()->get('department') == ''
                        )
                          <div class="d-flex align-items-center justify-content-between mb-0 mb-3">
                        @elseif (request()->get('department') != '')
                          <div class="d-flex align-items-center justify-content-between mb-0 mb-3" style="display: none !important;">
                        @endif
                            <h5 class="mb-0 text-center flex-grow-1">{!! $value['department_name'] ?? '' !!}</h5>
                            <button class="btn btn-outline-secondary ms-auto me-1" style="width: 100px;" id="reset-all"><i class="bi bi-arrow-clockwise ms-0 me-1"></i>Reset All
                            </button>
                        </div>

                        @if ((request()->get('department') != '' &&
                          request()->get('department') == $value['department_id']) ||
                          request()->get('department') == ''
                        )
                          <div class="col-md-12 row mb-3 m-2">
                        @elseif (request()->get('department') != '')
                          <div class="col-md-12 row mb-3 m-2" style="display: none !important;">
                        @endif
                          <hr>
                            @foreach($value['test_packages'] as $test_packages)
                              <div class="d-flex align-items-center justify-content-between m-2" style="{!! request()->get('test_package') != '' && $test_packages->id != request()->get('test_package') ? 'display:none !important' : ''; !!}">
                                  <h5 class="mb-0">{!! $test_packages->name ?? '' !!}</h5>
                                  <button class="btn btn-sm btn-light reset" type="button" data-id="{!! $test_packages->id ?? '' !!}"><b><i class="bi bi-arrow-clockwise"></i></b> Reset</button>
                              </div>
                              @foreach($test_packages->testPackageGroups as $testPackageGroup)
                                @php $serial = 1; @endphp
                                <table class="table table-bordered align-middle" style="font-size: 14px;border: 1px solid #dee2e6;{!! request()->get('test_package') != '' && $testPackageGroup->test_package_id != request()->get('test_package') ? 'display:none !important' : ''; !!}">
                                  <thead class="table-light">
                                    <tr>
                                      <th width="10%">SL No</th>
                                      <th width="30%">Investigation</th>
                                      <th width="25%">Result</th>
                                      <th width="10%">Flag</th>
                                      <th width="25%">Reference Range</th>
                                    </tr>
                                  </thead>
                                  <tbody>
                                @foreach($testPackageGroup->test_package_group_test_items as $item_key => $items)
                                  @if($items->test_item->item_type == 'TEST_LABEL')
                                    <tr class="item-div">
                                      <td>{!! $serial !!}</td>
                                      <td colspan="4">
                                        <div class="test_label">
                                            <b>
                                                {!! $items->test_item->test_name ?? '' !!}
                                            </b>
                                        </div>
                                      </td>
                                    </tr>
                                  @else
                                    @php
                                     $answer     = $billing_report[$items->test_item->id . '_' . $test_packages->sale_invoice_detail_id] ?? '';
                                     $input_name = 'test_results['.$test_packages->sale_invoice_detail_id .']['.$items->test_package_id .']['. $items->test_package_group_id .']['. $items->test_item->id  .']';
                                     $test_flags = 'test_flags['.$test_packages->sale_invoice_detail_id .']['.$items->test_package_id .']['. $items->test_package_group_id .']['. $items->test_item->id  .']';
                                    @endphp
                                    <tr class="item-div package_{!! $test_packages->sale_invoice_detail_id ?? '' !!}">
                                      @if($items->test_item->input_type == 'SUMMER_NOTE')
                                        <td colspan="5">
                                          @if(isset($items->test_item->testItemTemplates))
                                          <div class="col-md-6 m-2">
                                            <label class="form-label">Select Template</label>
                                            <select class="form-select select-template" data-summernote="summernote{!! $testPackageGroup->test_package_id  . '_' . $item_key !!}">
                                              <option value=""> - Select - </option>
                                              @foreach($items->test_item->testItemTemplates as $template)
                                                <option value="{!! $template->template_text ?? '' !!}">{!! $template->template_title ?? '' !!}</option>
                                              @endforeach
                                            </select>
                                          </div>
                                          @endif
                                          <textarea class="summernote {!! $items->test_item->formula_code ?? '' !!} summernote{!! $testPackageGroup->test_package_id  . '_' . $item_key !!}" id="{!! $items->test_item->id !!}" name="{!! $input_name !!}" data-summernote="{!! $testPackageGroup->test_package_id  . '_' . $item_key !!}">{!! $answer->long_result ?? '' !!}</textarea>

                                        <input type="hidden" class="test_flag" name="{!! $test_flags !!}" value="{!! $answer->flag ?? '' !!}">
                                      </td>
                                      @else
                                      <td>{!! $serial !!}</td>
                                      <td>
                                        <label class="form-label" for="{!! $items->test_item->id !!}">{!! $items->test_item->test_name ?? '' !!}</label>
                                        <i style="color: #8b8b8b;"><br>{!! $items->test_item->test_method_name ?? '' !!}</i>
                                      </td>
                                      <td>
                                        @if($items->test_item->reference_value_type == 'OPTIONS' && isset($items->test_item->testItemOption))
                                          {{-- <select class="form-select select2 select-options {!! $items->test_item->formula_code ?? '' !!}" name="{!! $input_name !!}">
                                            <option value="">- Select -</option>
                                            @foreach($items->test_item->testItemOption as $option)
                                              <option value="{!! $option->name !!}" data-value="{!! strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $option->name))) !!}" {!! isset($answer) ? matchSelected($answer->result, $option->name) : '' !!} style="
                                                color:{!! $option->styleType->font_color ?? '#000000' !!};
                                                background-color:{!! $option->styleType->bg_color ?? 'white' !!};
                                                text-decoration:{!! $option->styleType->text_decoration ?? 'none' !!};
                                                font-style:{!! $option->styleType->font_style ?? 'normal' !!};
                                                font-weight:{!! $option->styleType->font_weight ?? 'normal' !!};
                                                padding:{!! $option->styleType->font_padding ?? 'normal' !!};
                                                ">{!! $option->name !!}</option>
                                            @endforeach
                                          </select>
                                          <input type="hidden" name="select_test_flag[{!! $items->test_package_id !!}][{!! $items->test_package_group_id !!}][{!! $items->test_item->id !!}]" value="1">--}}

                                          <textarea class="test_result_update form-textarea {!! $items->test_item->formula_code ?? '' !!}" id="{!! $items->test_item->id !!}" name="{!! $input_name !!}" data-id="{!! $items->test_item->id !!}">{!! $answer->result ?? '' !!}</textarea>

                                          <span id="test_option_list{!! $items->test_item->id !!}" style="cursor:pointer;" data-id="{!! $items->test_item->id !!}"></span>

                                        {{-- @elseif($items->test_item->input_type == 'NUMBER' || $items->test_item->reference_value_type == 'RANGE') --}}
                                        @elseif($items->test_item->input_type == 'NUMBER')
                                          <input type="number" class="form-control {!! $items->test_item->reference_value_type == 'RANGE' ? 'range' : '' !!} {!! $items->test_item->formula_code ?? '' !!}" name="{!! $input_name !!}" id="{!! $items->test_item->id !!}" placeholder="Test Result" value="{!! $answer->result ?? '' !!}">
                                        @elseif($items->test_item->input_type == 'TEXT')
                                          <input type="text" class="form-control {!! $items->test_item->reference_value_type == 'RANGE' ? 'range' : '' !!} {!! $items->test_item->formula_code ?? '' !!} {!! $items->test_item->reference_value_type == 'OPTIONS' ? 'option_input' : '' !!}" name="{!! $input_name !!}" id="{!! $items->test_item->id !!}" placeholder="Test Result" value="{!! $answer->result ?? '' !!}">
                                        @elseif($items->test_item->input_type == 'TIME')
                                          <input type="time" class="form-control {!! $items->test_item->formula_code ?? '' !!}" name="{!! $input_name !!}" id="{!! $items->test_item->id !!}" placeholder="Test Result" value="{!! $answer->result ?? '' !!}">
                                        @elseif($items->test_item->input_type == 'SUMMER_NOTE')
                                          <textarea class="summernote {!! $items->test_item->formula_code ?? '' !!}" id="{!! $items->test_item->id !!}" name="{!! $input_name !!}">{!! $answer->result ?? '' !!}</textarea>
                                        @elseif($items->test_item->input_type == 'IMAGE')
                                          <input type="file" class="form-control {!! $items->test_item->formula_code ?? '' !!}" name="{!! $input_name !!}" id="{!! $items->test_item->id !!}" placeholder="Test Result" accept="image">
                                        @elseif($items->test_item->input_type == 'PDF')
                                          <input type="file" class="form-control {!! $items->test_item->formula_code ?? '' !!}" name="{!! $input_name !!}" id="{!! $items->test_item->id !!}" placeholder="Test Result" accept=".pdf">
                                        @else
                                          <input type="text" class="form-control {!! $items->test_item->formula_code ?? '' !!}" name="{!! $input_name !!}" id="{!! $items->test_item->id !!}" placeholder="Test Result" value="{!! $answer->result ?? '' !!}">
                                        @endif
                                      </td>
                                      <td>
                                        @php
                                          $flag = isset($answer->flag) && $answer->flag == 'high' ? 'high' : (isset($answer->flag) && $answer->flag == 'low' ? 'low' : '');
                                        @endphp
                                        <b><span class="error_testitem {{ $flag }}" style="{!! $flag == '' ? 'display:none' : '' !!}">{!! $flag !!}</span></b>

                                        <input type="hidden" class="test_flag" name="{!! $test_flags !!}" value="{!! $answer->flag ?? '' !!}">
                                      </td>
                                      <td>
                                      @if($items->test_item->reference_value_type == 'RANGE' && isset($items->test_item->testItemNormalRange))
                                          @php $is_range = 0; @endphp
                                          @foreach($items->test_item->testItemNormalRange->where('gender_id', $gender) as $range)
                                          @if($age >= $range->from_age && $age <= $range->to_age)
                                              {!! $range->low_value !!} - {!! $range->high_value !!} {!! $items->test_item->unit ?? '' !!}<br>
                                              <input type="hidden" name="" class="range-start" value="{!! $range->low_value !!}">
                                              <input type="hidden" name="" class="range-end" value="{!! $range->high_value !!}">
                                              @php $is_range = 1; break; @endphp
                                          @endif
                                          @endforeach
                                          
                                          @if($is_range == 0 && !empty($range))
                                              {!! $range->low_value !!} - {!! $range->high_value !!} {!! $items->test_item->unit ?? '' !!}<br>
                                              <input type="hidden" name="" class="range-start" value="{!! $range->low_value !!}">
                                              <input type="hidden" name="" class="range-end" value="{!! $range->high_value !!}">
                                          @endif
                                      @endif
                                      @if($items->test_item->reference_value_type == 'OPTIONS' && isset($items->test_item->testItemOption))
                                          @foreach($items->test_item->testItemOption as $range)
                                              <input type="hidden" name="" class="{!! strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $range->name))) !!}" value="{!! $range->styleType->code !!}">
                                          @endforeach
                                      @endif
                                      @if($items->test_item->reference_value_type == 'TEXT' && $items->test_item->reference_value != '')
                                      Ref({!! $items->test_item->reference_value !!})<br>
                                      @endif
                                      </td>
                                      @endif
                                    </tr>
                                  @endif
                                  @php $serial += 1; @endphp
                                @endforeach
                                </tbody>
                                </table>
                              @endforeach
                            @endforeach
                          </div>
                        @endforeach

                        <div class="col-md-3 mt-2"></div>
                        <div class="col-md-6 mt-2">
                            <div class="d-grid gap-2 with-100">
                                <button class="btn btn-primary submit" style="width: 70%;margin:0 auto;" type="button"><i class="bx bx-save"></i> Update Report</button>
                            </div>
                        </div>
                        <div class="col-md-3 mt-2"></div>
                    </div>
                  </form>
                </div>
            </div>
        </div>
    </div>
@endsection

@section('js')
<script src="https://cdn.ckeditor.com/ckeditor5/41.3.1/classic/ckeditor.js"></script>
<script type="text/javascript" src="{{ asset('admin/js/report-formula.js')}}"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js" integrity="sha512-2ImtlRlf2VVmiGZsjm9bEyhjGW4dU7B6TNwh/hx/iSByxNENtj3WVE6o/9Lj4TJeVXPi4bnOIMXFIJJAeufa0A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script>
  var dynamicVariables = [];
  $('.summernote').each(function() {
    ClassicEditor
      .create( document.querySelector( '.summernote' + $(this).data('summernote') ) )
      .then( newEditor => {
          dynamicVariables['summernote' + $(this).data('summernote')] = newEditor;
      })
      .catch( error => {
          console.error( error );
      });
  })
</script>
<script type="text/javascript">

  $(document).ready(function() {
     /***************** Global Delay Fucntion ***************/
     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);
        };
    }
    $('.select2').select2({
    });
    $(document).on('keyup', '.test_result_update', function(e) {
      var keycode = e.which || e.keyCode;
      var test_id = $(this).data('id');
      var search_text = this.value;
      if (keycode == 38 || keycode == 40 || keycode == 13 || keycode == 9) {
        return false;
      }
      search_data(test_id, search_text);
    });

    $(document).on('click', '.test_result_update', function() {
      $('.test-group-ul').html('');
      $(this).select();
      var test_id = $(this).data('id');
      var search_text = this.value;
      search_data(test_id, search_text);
    });

    function slugify(text) {
        return text
            .trim() // Remove whitespace from both ends of the string
            .toLowerCase() // Convert the string to lowercase
            .replace(/[^a-z0-9-]+/g, '-') // Replace all non-alphanumeric characters (except hyphen) with hyphens
            .replace(/^-+|-+$/g, ''); // Remove leading or trailing hyphens
    }

    function search_data(test_id, search_text = '') {
      $.ajax({
        url: "{!! route('test-item-options') !!}",
        method: 'POST',
        data: {
          'test_id': test_id,
          'search_text': search_text
        },
        success: function(data) {
          var content = '<ul class="list-group">';
          content += data;
          content += '</ul>';
          $('#test_option_list' + test_id).html('').html(content);
        }
      });
    }


    $(document).on('keydown', '.test_result_update', function(e) {
      var keycode = e.which || e.keyCode;
      var li = $(this).closest('td').find('li');
      var liSelected = $(this).closest('td').find('li.active');

      if (keycode === 40) {
        if (liSelected) {
          liSelected.removeClass('active');
          next = liSelected.next();
          if (next.length > 0) {
            liSelected = next.addClass('active');
          } else {
            liSelected = li.eq(0).addClass('active');
          }
          $(this).val(liSelected.text());

          var value = liSelected.text();
          value = slugify(value);
          var flag = $(this).parent().parent().find('.' + value).val();
          // console.log('.' + value);
          if (flag != undefined && flag != '') {
              $(this).parent().parent().find('.error_testitem').show();
              $(this).parent().parent().find('.error_testitem').text(flag);
              $(this).parent().parent().find('.test_flag').val(flag);
          }
        } else {
          liSelected = li.eq(0).addClass('active');
          $(this).val(liSelected.text());
          var value = liSelected.text();
          value = slugify(value);
          var flag = $(this).parent().parent().find('.' + value).val();
          // console.log('.' + value);

          if (flag != undefined && flag != '') {
              $(this).parent().parent().find('.error_testitem').show();
              $(this).parent().parent().find('.error_testitem').text(flag);
              $(this).parent().parent().find('.test_flag').val(flag);
          }
        }
      } else if (keycode === 38) {
        if (liSelected) {
          liSelected.removeClass('active');
          next = liSelected.prev();
          if (next.length > 0) {
            liSelected = next.addClass('active');
          } else {
            liSelected = li.last().addClass('active');
          }
          $(this).val(liSelected.text());
          var value = liSelected.text();
          value = slugify(value);
          var flag = $(this).parent().parent().find('.' + value).val();
          console.log('.' + value);

          if (flag != undefined && flag != '') {
              $(this).parent().parent().find('.error_testitem').show();
              $(this).parent().parent().find('.error_testitem').text(flag);
              $(this).parent().parent().find('.test_flag').val(flag);
          }
        } else {
          liSelected = li.last().addClass('active');
          $(this).val(liSelected.text());
          var value = liSelected.text();
          value = slugify(value);
          var flag = $(this).parent().parent().find('.' + value).val();
          console.log('.' + value);

          if (flag != undefined && flag != '') {
              $(this).parent().parent().find('.error_testitem').show();
              $(this).parent().parent().find('.error_testitem').text(flag);
              $(this).parent().parent().find('.test_flag').val(flag);
          }
        }
      } else if (keycode == 9) {
        $('.test-group-ul').html('');
        var nxt_text_area = $(this).closest('tr').next('tr').find('textarea').data('id');
        $('textarea[data-id=' + nxt_text_area + ']').focus();
        search_data(nxt_text_area);
        return false;
        // console.log(x);
      } else if (keycode == 13) {
        $(this).val(liSelected.text());

          var value = liSelected.text();
          value = slugify(value);
          var flag = $(this).parent().parent().find('.' + value).val();
          console.log('.' + value);

          if (flag != undefined && flag != '') {
              $(this).parent().parent().find('.error_testitem').show();
              $(this).parent().parent().find('.error_testitem').text(flag);
              $(this).parent().parent().find('.test_flag').val(flag);
          }

        $('.test-group-ul').html('');
        var nxt_text_area = $(this).closest('tr').next('tr').find('textarea').data('id');
        $('textarea[data-id=' + nxt_text_area + ']').focus();
        search_data(nxt_text_area);
        return false;
      } else {
        $(this).val(liSelected.text());

          var value = liSelected.text();
          value = slugify(value);

          if (value != '') {
            var flag = $(this).parent().parent().find('.' + value).val();
            console.log('.' + value);

            if (flag != undefined && flag != '') {
                $(this).parent().parent().find('.error_testitem').show();
                $(this).parent().parent().find('.error_testitem').text(flag);
                $(this).parent().parent().find('.test_flag').val(flag);
            }

            $('.test-group-ul').html('');
            var nxt_text_area = $(this).closest('tr').next('tr').find('textarea').data('id');
            $('textarea[data-id=' + nxt_text_area + ']').focus();
            search_data(nxt_text_area);
            return false;
          }
      }
    });

    $(document).on('click', '.test-options', function() {
      var test_id = $(this).data('id');
      var text = $(this).text().trim();

      $('textarea[data-id=' + test_id + ']').val(text);
      $('.test-options').hide();

    });

    $(document).on('focusin', '.test_result_update', function() {
      $('.test-options').hide();
    });

    $(document).on('focusout', '.test_result_update', function() {
        var value = $(this).text();
        value = slugify(value);
        var flag = $(this).parent().parent().find('.' + value).val();

        if (flag != undefined && flag != '') {
            $(this).parent().parent().find('.error_testitem').show();
            $(this).parent().parent().find('.error_testitem').text(flag);
            $(this).parent().parent().find('.test_flag').val(flag);
        }

      setTimeout(function() {
        $('.test-options').hide();
      }, 200);
    });

      // $('.summernote').summernote();
      $(".ck-dropdown").find(`[data-cke-tooltip-text='Insert media']`).css("display", "none");

      $(document).on('click','.submit', function(e) {
        e.preventDefault();
        $('#billing_report').submit();
      });
      $(document).on('input', '.range', delay(function() {
        var rangeValue = parseFloat($(this).val());
        rangeValue     = rangeValue > 0 ? rangeValue : 0;
        var startValue = parseFloat($(this).parent().parent().find('.range-start').val());
        var endValue   = parseFloat($(this).parent().parent().find('.range-end').val());

        if (rangeValue < startValue) {
            $(this).parent().parent().find('.error_testitem').show();
            $(this).parent().parent().find('.error_testitem').text('Low');
            $(this).parent().parent().find('.error_testitem').addClass('low');
            $(this).parent().parent().find('.error_testitem').removeClass('high');
            $(this).parent().parent().find('.test_flag').val('low');
            $(this).addClass('input_error');
        } else if (rangeValue > endValue) {
            $(this).parent().parent().find('.error_testitem').show();
            $(this).parent().parent().find('.error_testitem').text('High');
            $(this).parent().parent().find('.error_testitem').addClass('high');
            $(this).parent().parent().find('.error_testitem').removeClass('low');
            $(this).parent().parent().find('.test_flag').val('high');
            $(this).addClass('input_error');
        } else {
            $(this).parent().parent().find('.error_testitem').hide();
            $(this).parent().parent().find('.test_flag').val('normal');
            $(this).parent().parent().find('.error_testitem').removeClass('high');
            $(this).parent().parent().find('.error_testitem').removeClass('low');
            $(this).removeClass('input_error');
        }
      }, 700));

      $(document).on('change', '.option_input',function() {
        var value      = $(this).val();
        var options    = $(this).parent().parent().find('.option');
        var isNotEqual = true;

        options.each(function() {
            if ($(this).val().toLowerCase() === value.toLowerCase()) {
                isNotEqual = false;
                return false;
            }
        });

        if (!isNotEqual) {
            $(this).css('border-color', 'green');
        } else {
            error = 1;
            $(this).parent().parent().find('.error_testitem').show();
            $(this).parent().parent().find('.error_testitem').text('Select from given options.');
            $(this).focus();
        }
      });

      $(document).on('click', '.reset', function() {
          var parentDiv = $(this).data('id');
          $('.package_'+parentDiv).find('input, select, textarea').val('');
          $('.package_'+parentDiv).find('textarea').text('');
          $('.package_'+parentDiv).find('.note-editable').text('');
      });

      $(document).on('click', '#reset-all', function() {
          $('#billing_report').find('table').find('input, select, textarea').val('');
          $('#billing_report').find('table').find('textarea').text('');
          $('#billing_report').find('table').find('.note-editable').text('');
      });

      $(document).on('change', '.select-options', function() {
        var value = $(this).find("option:selected").data("value");
        var flag = $(this).parent().parent().find('.' + value).val();

        if (flag != undefined && flag != '') {
            $(this).parent().parent().find('.error_testitem').show();
            $(this).parent().parent().find('.error_testitem').text(flag);
            $(this).parent().parent().find('.test_flag').val(flag);
        }

      });
    $(document).on('change', '.select-template', function() {
        var template   = $(this).val();
        var summernote = $(this).data('summernote');
        dynamicVariables[summernote].setData(template);
    });

    $(document).on('keyup', '.CBC-HEMOGLOBIN,.CBC-RBC,.CBC-PCV,.CBC-NEUTROPHILS,.CBC-LYMPHOCYTES,.CBC-MONOCYTES,.CBC-EOSINOPHILS,.CBC-PLATELET-COUNT,.CBC-MPV,.CBC-LEUKOCYTE-COUNT,.CBC-BASOPHILS', function() {
      calculate_cbc();
    });

    $(document).on('keyup', '.HBA1C-HEAMOGLOBIN', function() {
      calculate_HBA1C_val();
    });

    $(document).on('keyup', '.INR-PROTHROMBIN,.INR-NORMAL', function() {
      calculate_inr_val();
    });

    $(document).on('keyup', '.LIPID-SCHOLESTEROL,.LIPID-TRIGLYCERIDES,.LIPID-HDLCHOLESTEROL', function() {
      calculate_lipidprofile();
    });

    $(document).on('keyup', '.BLOOD-UREA', function() {
      calculate_blood_urea();
    });

    $(document).on('keyup', '.BILIRUBIN-TOTAL, .BILIRUBIN-DIRECT', function() {
      calculate_bilirubin_total();
    });

    $(document).on('keyup', '.RENAL-FUNCTION-TEST, .BLOOD-UREA', function() {
      calculate_urea_bun();
    });

    $(document).on('keyup', '.LIVER-FUNCTION-TEST, .TOTAL-PROTEIN, .ALBUMIN, .GLOBULIN, TOTAL-BILIRUBIN,.CONJUGATED-BILIRUBIN', function() {
      calculate_lft();
    });

    $(document).on('keyup', '.KFT-UREA', function() {
      calculate_kft();
    });

    $(document).on('keyup', '.PTIMEPATIENT, .PTIMECONTROL', function() {
      calculate_ptime();
    });
  });
</script>
@endsection
