@extends('layouts.app')
@section('title', $sale_invoice->main_invoice_no . ' - '. ($sale_invoice->invoice_date ? formatedDate($sale_invoice->invoice_date) : '') . ' - ' . ($sale_invoice->getPatient->name ?? ''))
@section('pages')

<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">
<style type="text/css">
    .breadcrumb-title {
      border-right: none;
    }
    .dataTables_filter{
        margin-bottom: 6px;
    }
</style>
  <!--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"> IPD Billings 
    </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="178" data-bs-toggle="modal" data-bs-target="#commonModal"></i></li>
          <li class="breadcrumb-item" aria-current="page">IPD-In Patient</li>
            <li class="breadcrumb-item active" aria-current="page"><i class="bi bi-dot"></i> IPD Billing</li>
        </ol>
      </nav>
    </div>
  </div>
  <!--end breadcrumb-->
  <div class="card style_table shadow-none radius-5 min-height my-auto">
    <div class="card-header py-3">
      @include('layouts.partials.nav-menu')
      <div class="row gx-2">
        <div class="col-lg-12 col-md-12">
           <b style="font-size: 14px" > Invoice Number :
        {{ $sale_invoice->voucher_type_invoice_no }}</b>
          <div class="ms-auto float-md-end">


            <div class="btn-group">
                <a href="javascript:history.back()" 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>

  <div class="row auto">
      <div class="col-xl-12 mx-auto">
          <div class="shadow-none radius-5 min-height">
              <div class="row">
                  {{-- <div class="col-md-12">
                      <div class="card">
                          <div class="card-body">
                              <div class="row text-left p-0" id="header">
                                  <div class="col-7" style="line-height: 1.2;padding-bottom:5px">
                                      <h3 class="m-0 p-0">{!! $sale_invoice->getCompany->name ?? '' !!}</h3>
                                      <p class="p-0 m-0 font-weight-normal font-12">ADDRESS: {!! $sale_invoice->getCompany->getCompanyAddress->address_1 ?? '' !!}</p>
                                      <p class="p-0 m-0 font-weight-normal font-12">STATE: {!! $sale_invoice->getCompany->getCompanyAddress->getComapnyState->name ?? '' !!}</p>
                                      <p class="p-0 m-0 font-weight-normal font-12">MOBILE: {!! $sale_invoice->getCompany->mobile_number ?? '' !!}{!! $sale_invoice->getCompany->phone_number ? ', '. $sale_invoice->getCompany->phone_number : '' !!}</p>
                                      <p class="p-0 m-0 font-weight-normal font-12">EMAIL: {!! $sale_invoice->getCompany->email ?? '' !!}{!! $sale_invoice->getCompany->website ? ', ' . $sale_invoice->getCompany->website : '' !!}</p>
                                  </div>
                                  <div class="col-4 text-right ">
                                      @if(isset($sale_invoice->getCompany->logo) && $sale_invoice->getCompany->logo != '')
                                        <img class="img-thumbnail border-0" src="{!! $sale_invoice->getCompany->logo !!}" alt="Upload Letter Head Logo" height="90" width="70%">
                                      @else
                                        <img class="img-thumbnail border-0" src="https://master.cloudpatholab.com/uploads/letterheads/images/1/c7ba6041869fc6929fe5e9c6e4be52bf.png" alt="Upload Letter Head Logo" height="90" width="200">
                                      @endif
                                  </div>
                              </div>
                          </div>
                      </div>
                  </div> --}}
                  <div class="col-md-6">
                      <div class="card">
                          <div class="card-body g-3">
                              <div class="table-responsive">
                                  <div class="d-flex justify-content-between">
                                      <h5 class="mb-0">Patient Details</h5>

                                      <button data-id="{{ $sale_invoice->id }}" class="btn btn-white edit_patient" data-bs-toggle="modal" data-bs-target="#commonModal" title="Edit">
                                          <i class="bi bi-pencil-square"></i>
                                      </button>
                                  </div>
                                  <hr class="mb-2">
                                  <table class="table table-bordered align-middle">
                                    <tr>
                                        <td style="text-align:left;">Admission No: 	 </td>
                                        {{-- @dd($sale_invoice); --}}
                                        <td>{!! $sale_invoice->admission_no ?? '' !!}</td>
                                    </tr>
                                    <tr>
                                        <td style="text-align:left;">Admission DT: 	 </td>
                                        <td>{!! $sale_invoice->admission_date_time ?? '' !!}</td>
                                    </tr>
                                    <tr>
                                        <td style="text-align:left;">Patient Name </td>
                                        <td>{!! $sale_invoice->getPatient->account_title->name ?? '' !!}{!! $sale_invoice->getPatient->name ?? '' !!} - {!! $sale_invoice->getPatient->code ?? '' !!} </td>
                                    </tr>
                                    @php
                                        $date_of_birth = $sale_invoice->getPatient->account_contact->date_of_birth ?? '';
                                        $age           = $date_of_birth != '' ? age($sale_invoice->getPatient->account_contact->date_of_birth) : 0;
                                    @endphp
                                    <tr>
                                        <td style="text-align:left;">Sex/Age </td>
                                        <td>
                                          {!! $sale_invoice->getPatient->account_contact->gender->name ?? '' !!}/{!! $age !!} Years
                                        </td>
                                    </tr>
                                    <tr>
                                        <td style="text-align:left;">Address</td>
                                        <td>{!! $sale_invoice->getPatient->first_account_address->address_line1 ?? '' !!}</td>
                                    </tr>
                                    <tr>
                                        <td style="text-align:left;">State Name </td>
                                        <td>{!! $sale_invoice->getPatient->first_account_address->state->name ?? '' !!}</td>
                                    </tr>
                                    <tr>
                                        <td style="text-align:left;">Bed No: 	 </td>
                                        <td>{!! $sale_invoice->bed_name ?? '' !!}</td>
                                    </tr>
                                  </table>
                              </div>
                          </div>
                      </div>
                  </div>
                  @if(isset($sale_invoice->getDoctor))
                    <div class="col-md-6">
                        <div class="card">
                            <div class="card-body g-3 row">
                                <div class="table-responsive">
                                  <div class="d-flex justify-content-between">
                                      <h5 class="mb-0">Doctor Details</h5>

                                      <button data-id="{{ $sale_invoice->id }}" class="btn btn-white edit_doctor" data-bs-toggle="modal" data-bs-target="#commonModal" title="Edit">
                                          <i class="bi bi-pencil-square"></i>
                                      </button>
                                  </div>

                                    <hr class="mb-2">
                                    <table class="table table-bordered align-middle">
                                      <tr>
                                          <td style="text-align:left;">Doctor Name</td>
                                          <td>{{ ucfirst($sale_invoice->getDoctor->name) }}</td>
                                      </tr>
                                      <tr>
                                          <td style="text-align:left;">Address</td>
                                          <td>{{$sale_invoice->getDoctor->first_account_address->address_line1 ?? ''}}</td>
                                      </tr>
                                      <tr>
                                          <td style="text-align:left;">Email</td>
                                          <td>{{$sale_invoice->getDoctor->account_contact->email ?? ''}}</td>
                                      </tr>
                                      <tr>
                                          <td style="text-align:left;">Phone No</td>
                                          <td>{{$sale_invoice->getDoctor->account_contact->phone_no ?? ''}}</td>
                                      </tr>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                  @endif
                  @if(isset($sale_invoice->getCollectionAgent))
                    <div class="col-md-6">
                        <div class="card">
                            <div class="card-body g-3 row">
                                <div class="table-responsive">
                                  <div class="d-flex justify-content-between">
                                      <h5 class="mb-0">Collection Agent Details</h5>

                                      <button data-id="{{ $sale_invoice->id }}" class="btn btn-white edit_coll_agent" data-bs-toggle="modal" data-bs-target="#commonModal" title="Edit">
                                          <i class="bi bi-pencil-square"></i>
                                      </button>
                                  </div>
                                    <hr class="mb-2">
                                    <table class="table table-bordered align-middle">
                                      <tr>
                                          <td style="text-align:left;">Collection Agent Name</td>
                                          <td>{{ ucfirst($sale_invoice->getCollectionAgent->name) }}</td>
                                      </tr>
                                      <tr>
                                          <td style="text-align:left;">Address</td>
                                          <td>{{$sale_invoice->getCollectionAgent->first_account_address->address_line1 ?? ''}}</td>
                                      </tr>
                                      <tr>
                                          <td style="text-align:left;">Email</td>
                                          <td>{{$sale_invoice->getCollectionAgent->account_contact->email ?? ''}}</td>
                                      </tr>
                                      <tr>
                                          <td style="text-align:left;">Phone No</td>
                                          <td>{{$sale_invoice->getCollectionAgent->account_contact->phone_no ?? ''}}</td>
                                      </tr>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                  @endif
                  @if(isset($sale_invoice->getRefferalLab))
                    <div class="col-md-6">
                        <div class="card">
                            <div class="card-body g-3 row">
                                <div class="table-responsive">
                                  <div class="d-flex justify-content-between">
                                      <h5 class="mb-0">Refferal Lab Details</h5>

                                      <button data-id="{{ $sale_invoice->id }}" class="btn btn-white edit_referal_lab" data-bs-toggle="modal" data-bs-target="#commonModal" title="Edit">
                                          <i class="bi bi-pencil-square"></i>
                                      </button>
                                  </div>
                                    <hr class="mb-2">
                                    <table class="table table-bordered align-middle">
                                      <tr>
                                          <td style="text-align:left;">Refferal Laboratory</td>
                                          <td>{{ ucfirst($sale_invoice->getRefferalLab->name) }}</td>
                                      </tr>
                                      <tr>
                                          <td style="text-align:left;">Address</td>
                                          <td>{{$sale_invoice->getRefferalLab->first_account_address->address_line1 ?? ''}}</td>
                                      </tr>
                                      <tr>
                                          <td style="text-align:left;">Email</td>
                                          <td>{{$sale_invoice->getRefferalLab->account_contact->email ?? ''}}</td>
                                      </tr>
                                      <tr>
                                          <td style="text-align:left;">Phone No</td>
                                          <td>{{$sale_invoice->getRefferalLab->account_contact->phone_no ?? ''}}</td>
                                      </tr>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                  @endif
              </div>

              <div class="row">
                  <div class="col-12">
                      <div class="card">
                          <div class="table-responsive">
                              <table class="table table-bordered-print w-100" id="quotation_products">
                                  <thead>
                                      <tr>
                                          <th>Sl.No</th>
                                          <th>ITEM NAME & DETAILS </th>
                                          <th>HSN/SAC</th>
                                          <th class="text-end">MRP</th>
                                          <th class="text-end">QTY</th>
                                          <th class="text-end">Dis(%)</th>
                                          <th class="text-end">PRICE</th>
                                          <th class="text-end">GST%</th>
                                          <th class="text-end">IGST</th>
                                          <th class="text-end">CGST</th>
                                          <th class="text-end">SGST</th>
                                          <th class="text-end">CESS</th>
                                          <th class="text-end">BASIC</th>
                                          <th class="text-end">TOTAL</th>
                                      </tr>
                                  </thead>
                                  <tbody>

                                      @php
                                          $total_gst_amount = 0;
                                          $IGST = $CGST = $SGST = 0;
                                      @endphp
                                      @foreach($sale_invoice->getSaleInvoiceDetails as $key => $value)
                                          <tr>
                                              <td>{!! $key + 1 !!}</td>
                                              <td>{!! $value->getProduct->name ?? '' !!}</td>
                                              <td>{!! $value->getProduct->hsncode ?? '' !!}</td>
                                              <td style="text-align: right !important;">
                                                  {!! isset($value->getProduct->getProductPrice->mrp) ? convertDecimelPoint($value->getProduct->getProductPrice->mrp) : '' !!}</td>
                                              <td style="text-align: right !important;">
                                                  {!! isset($value->main_qty) ? convertDecimelPoint($value->main_qty) : '' !!}
                                              </td>
                                              <td style="text-align: right !important;">
                                                  {!! isset($value->discount_amount) ? convertDecimelPoint($value->discount_amount) : '' !!} ({!! $value->discount_percentage ?? '' !!})</td>
                                              <td style="text-align: right !important;">
                                                  {!! convertDecimelPoint($value->basic_amount) !!}</td>
                                              @php
                                                  $gst = $value->getProduct->getTaxMaster->total_percentage ?? 0;
                                                  $gst_amount = ($gst > 0 ? (($gst / 100) * $value->total_amount) : 00);
                                                  $total_gst_amount +=$gst_amount
                                              @endphp
                                              <td style="text-align: right !important;">{!! $gst !!}% ({!! convertDecimelPoint($gst_amount) !!})</td>
                                              @php
                                                  if (isset($value->getProduct->getTaxMaster->getTaxMasterSub)) {
                                                      foreach($value->getProduct->getTaxMaster->getTaxMasterSub as $tax) {
                                                          if ($tax->name == 'IGST') {
                                                              $IGST = $tax->percentage ?? 0;
                                                          } else if ($tax->name == 'CGST') {
                                                              $CGST = $tax->percentage ?? 0;
                                                          } else if ($tax->name == 'SGST') {
                                                              $SGST = $tax->percentage ?? 0;
                                                          }
                                                      }
                                                  }
                                              @endphp
                                              <td style="text-align: right !important;">{!! $IGST !!}%</td>
                                              <td style="text-align: right !important;">{!! $CGST !!}%</td>
                                              <td style="text-align: right !important;">{!! $SGST !!}%</td>
                                              <td style="text-align: right !important;">{!! convertDecimelPoint($value->tax_cess_amount) ?? '' !!}</td>
                                              <td style="text-align: right !important;">
                                                  {!! convertDecimelPoint($value->total_amount) ?? '' !!}</td>
                                              <td style="text-align: right !important;">
                                                  {!! convertDecimelPoint($value->total_amount + $gst_amount) ?? '' !!}</td>
                                          </tr>
                                      @endforeach
                                  </tbody>
                              </table>
                          </div>
                      </div>
                  </div>
              </div>
              <div class="row">
                  <div class="col-12">
                      <div class="card">
                          <div class="table-responsive">
                            <table class="table table-bordered-print w-100">
                                <thead>
                                    <tr>
                                        <th>Sl.No</th>
                                        <th>Test Package </th>
                                        <th>Created Date</th>
                                        <th>Report Delivery Date</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @foreach($sale_invoice->getSaleInvoiceSubDetail as $key => $value)
                                        @php
                                          $created_at          = $value->getTestPackage->created_at ?? '';
                                          $report_delivery_tat = $value->getTestPackage->report_delivery_tat ?? '';
                                          $report_delivery_date = reportDeliveryDate($created_at,$report_delivery_tat);
                                        @endphp
                                        <tr>
                                            <td>{!! $key + 1 !!}</td>
                                            <td>{!! $value->getTestPackage->name ?? '' !!}</td>
                                            <td>{!! formatedDate($value->getTestPackage->created_at ?? '') !!}</td>
                                            <td>{!! $report_delivery_date ?? '' !!}</td>
                                        </tr>
                                    @endforeach
                                </tbody>
                            </table>
                          </div>
                      </div>
                  </div>
              </div>
          </div>
      </div>
  </div>

    <!--end row-->
@endsection
@section('js')

  <script type="text/javascript" src="{{ asset('admin/plugins/datepicker/js/bootstrap-datepicker.js')}}"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/12.1.10/js/intlTelInput.js"></script>
<script type="text/javascript">

    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', '.edit_patient', function(){
      $('#commonModalLabel').text('Edit Patient');
      $('.save_button_span').text('Update Patient');
      var id  = $(this).data('id');
      var url = `{!! route('billings-edit-patient', ':id') !!}`.replace(':id', id);

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

    $(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', '.edit_doctor', function(){
      $('#commonModalLabel').text('Edit Doctor');
      $('.save_button_span').text('Update Doctor');
      var id  = $(this).data('id');
      var url = `{!! route('billings-edit-doctor', ':id') !!}`.replace(':id', id);

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

    $(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', '.edit_coll_agent', function(){
      $('#commonModalLabel').text('Edit Collection Agent');
      $('.save_button_span').text('Update Collection Agent');
      var id  = $(this).data('id');
      var url = `{!! route('billings-edit-agent', ':id') !!}`.replace(':id', id);

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

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

    $(document).on('click', '.edit_referal_lab', function(){
      $('#commonModalLabel').text('Edit Referral Lab');
      $('.save_button_span').text('Update Referral Lab');
      var id  = $(this).data('id');
      var url = `{!! route('billings-edit-referral-lab', ':id') !!}`.replace(':id', id);

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

    $(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','.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) {
                            // hide modal
                            $('#commonModal').modal('hide');
                            $('#commonModal').find('.modal-body').html('');

                            toastr.success(response.message, 'Success.');

                            setTimeout(function() {
                              $('.edit_patient').trigger('click');
                            }, 1000);
                        } 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('update-patient')) {
            $('.error_patient_id').hide();
            var error = 0;

            if ($('input[name="patient_id"]').val() == '') {
              $('.error_patient_id').show();
              error = 1;
            }

            if (error == 0) {
                let formdata = new FormData($('.update-patient')[0]);

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

                            // hide modal
                            $('#commonModal').modal('hide');
                            $('#commonModal').find('.modal-body').html('');
                            setTimeout(function() {
                              location.reload();
                            }, 1000);
                        } 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.');

                            // hide modal
                            $('#commonModal').modal('hide');
                            $('#commonModal').find('.modal-body').html('');

                            setTimeout(function() {
                              $('.edit_doctor').trigger('click');
                            }, 1000);
                        } 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('update-doctor')) {
            $('.error_doctor_id').hide();
            var error = 0;

            if ($('input[name="doctor_id"]').val() == '') {
              $('.error_doctor_id').show();
              error = 1;
            }

            if (error == 0) {
                let formdata = new FormData($('.update-doctor')[0]);

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

                            // hide modal
                            $('#commonModal').modal('hide');
                            $('#commonModal').find('.modal-body').html('');

                            setTimeout(function() {
                              location.reload();
                            }, 1000);
                        } 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.');

                            setTimeout(function() {
                              $('.edit_coll_agent').trigger('click');
                            }, 1000);

                            // 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('update-agent')) {
            $('.error_collection_id').hide();
            var error = 0;

            if ($('input[name="collection_id"]').val() == '') {
              $('.error_collection_id').show();
              error = 1;
            }

            if (error == 0) {
                let formdata = new FormData($('.update-agent')[0]);

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

                            // hide modal
                            $('#commonModal').modal('hide');
                            $('#commonModal').find('.modal-body').html('');

                            setTimeout(function() {
                              location.reload();
                            }, 1000);
                        } 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.');

                            setTimeout(function() {
                              $('.edit_referal_lab').trigger('click');
                            }, 1000);

                            // 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('update-referral-lab')) {
            $('.error_refferal_id').hide();
            var error = 0;

            if ($('input[name="refferal_id"]').val() == '') {
              $('.error_refferal_id').show();
              error = 1;
            }

            if (error == 0) {
                let formdata = new FormData($('.update-referral-lab')[0]);

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

                            // hide modal
                            $('#commonModal').modal('hide');
                            $('#commonModal').find('.modal-body').html('');

                            setTimeout(function() {
                              location.reload();
                            }, 1000);
                        } 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!');
                });
            }
        }
    })

    function getAge(birthdate) {
        if (birthdate != '' && birthdate != '0000-00-00' && 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;
        }
        return '';
    };
</script>
@endsection
