@extends('layouts.app')
@section('title','IPD Admission')
@section('pages')
<style type="text/css">
  .breadcrumb-title {
    border-right: none;
  }
  .dataTables_filter {
      margin-bottom: 6px;
  }

  .ui-switcher {
        background-color: #da2a2a35;
        display: inline-block;
        height: 25px;
        width: 72px;
        border-radius: 50px;
        box-sizing: border-box;
        vertical-align: middle;
        position: relative;
        cursor: pointer;
        transition: border-color 0.25s;
        margin: 0;
        box-shadow: none;
    }

    .ui-switcher
    {
        background-color: #da2a2a35;
        display: inline-block;
        height: 25px;
        width: 77px;
        border-radius: 50px;
        box-sizing: border-box;
        vertical-align: middle;
        position: relative;
        cursor: pointer;
        transition: border-color 0.25s;
        margin: 0;
        box-shadow: none;
    }
    .ui-switcher[aria-checked=true]:after {
        left: 57px;
        font-size: 13px;
        font-weight: 600;

    }
    .invisible{
      display: none;
    }

    .clear{
        clear:both;
        margin-top: 20px;
    }


.intl-tel-input .country-list {
    z-index: 8;
}

.intl-tel-input {
    width: 100%;
}

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

.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_btn {
        height: 40px;
        width: 40px;
        font-size:16px;
        border-radius: 0 3.5px 3.5px 0;
        padding: 0;
    }
    .select2-selection {
        height: 40px !important;
    }

    .flatpickr-calendar {
        width: 308px !important;
        font-size: 12px !important;
    }
</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/jquery-datetimepicker/2.5.20/jquery.datetimepicker.css" integrity="sha512-bYPO5jmStZ9WI2602V2zaivdAnbAhtfzmxnEGh9RwtlI00I9s8ulGe4oBa5XxiC6tCITJH/QG70jswBhbLkxPw==" crossorigin="anonymous" referrerpolicy="no-referrer" />


<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/12.1.10/css/intlTelInput.css">
<!-- Include Flatpickr CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

<!-- 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 Admission </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="42" data-bs-toggle="modal" data-bs-target="#commonModal"></i>
                </li>
                <li class="breadcrumb-item" aria-current="page">IPD Admission</li>
                <li class="breadcrumb-item active" aria-current="page">
                    <i class="bi bi-dot"></i> Admission Details
                </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-4 col-md-4">
                <h5 class="mb-0">
                    {{ $patient->account_title ? $patient->account_title->name : '' }}
                    {{ $patient->name ? $patient->name : '' }}
                    ({{ $patient->code }})
                </h5>
            </div>
            <div class="col-lg-8 col-md-5">
                <div class="ms-auto float-md-end">

                    {{-- <div class="btn-group">
                        @if(!$dischargeExists)
                        @if (!is_null($sale_invoices->sale_invoices_name))
                            <a href="{{ route('ipd-billings.add-more', $admission->id) }}" class="btn btn-info new-bill">
                                 <i class="bx bx-plus-circle text-white"></i>  New Intent
                            </a>
                        @else
                            <a href="{{ route('ipd-billings.create', $admission->id) }}" class="btn btn-info new-bill">
                                 <i class="bx bx-plus-circle text-white"></i> New Bill
                            </a>
                        @endif
                        @endif
                    </div>--}}

                    {{-- <div class="btn-group">
                        @if (auth()->user()->can('pathology-lab-billing-list'))
                            <a href="{!! route('ipd-billings.index', $admission->id) !!}" class="btn btn-info">
                                <i class="bi bi-receipt-cutoff"></i> View All Intents
                            </a>
                        @endif
                    </div> --}}
                    <div class="btn-group">
                        {{-- @if(!$dischargeExists) --}}
                            @if (auth()->user()->can('pathology-lab-billing-list'))
                                <a href="{!! route('ipd-billings.verify-checklist', $admission->id) !!}" class="btn btn-info">
                                     <i class="bi bi-check-circle"></i> Initiate Discharge
                                </a>
                            @endif
                    </div>

                    <div class="btn-group">
                        <ul class="navbar-nav align-items-center">
                            <li class="nav-item dropdown dropdown-small me-0">
                                <a class="dropdown-toggle dropdown-toggle-nocaret btn btn-secondary" href="#"
                                      data-bs-toggle="dropdown">
                                      <div class="">
                                         <i class="bi bi-receipt"></i> Bills & Documents
                                      </div>
                                </a>
                            <ul class="dropdown-menu dropdown-menu-end bg-secondary text-white px-0">
                                <li>
                                    <a href="{!! route('ipd-certificate', $admission->id) !!}" class="py-2 dropdown-item text-white hover-dark">
                                        <i class="bi bi-file-medical"></i> Admission Certificate
                                    </a>
                                </li>
                                <li>
                                    <a class="py-2 dropdown-item text-white hover-dark" href="{!! route('ipd-invoice', $admission->id) !!}"> <i class="bi bi-printer text-white"></i> Consolidated Bill</a>
                                </li>
                                <li>
                                    <a href="{{ route('ipd-billings-summary-item-wise',  $admission->id) }}" class="py-2 dropdown-item text-white hover-dark">
                                        <i class="bi bi-plus-circle text-white"></i> Item Wise Bill
                                    </a>
                                </li>
                                <li>
                                    <a href="{{ route('ipd-billings-summary', $admission->id) }}" class="py-2 dropdown-item text-white hover-dark">
                                        <i class="bx bx-printer ms-0 me-1"></i>Bill Summary
                                    </a>
                                </li>
                                @if($dischargeExists)
                                    <li>
                                        <a href="{{ route('ipd-admissions.dischargestatement', $admission->id) }}" class="py-2 dropdown-item text-white hover-dark"><i class="bi bi-file-medical"></i> Discharge Statement</a>
                                    </li>
                                @endif
                            </ul>
                            </li>
                        </ul>
                    </div>
                    
                    <div class="btn-group">
                        <a href="{{ route('ipd-admissions.index') }}" 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-4">
                    <div class="card">
                        <div class="card-body g-3">
                            <div class="table-responsive">
                                <h5 class="mb-0">Admission Details 
                                    <div class="btn-group" style="float: inline-end;">
                                        <a href="{{ route('ipd-admissions.edit', $admission->id) }}"  class="btn btn-warning" title="Edit">
                                            <i class="bi bi-pencil-square"></i> Edit IPD
                                        </a>
                                    </div>
                                </h5>
                                <hr class="mb-2">
                                <table class="table table-bordered align-middle">
                                    <tr class="fw-bold">
                                        <td style="text-align:left;">Admission No </td>
                                        <td>{{ $admission->ipd_admission_no }}</td>
                                    </tr>
                                    <tr>
                                        <td style="text-align:left;">Admission Date</td>
                                        <td>{!! formatedDateTime($admission->admission_date_time) !!}</td>
                                    </tr>
                                    <tr>
                                        <td style="text-align:left;">IPD CASE/FILE NUMBER</td>
                                        <td>{{ $admission->ipd_file_no ?? 'N/A' }}</td>
                                    </tr>
                                    <tr>
                                        <td style="text-align:left;">Patient source</td>
                                        <td>{{ $patient_source->enquiry_source_name }}</td>
                                    </tr>
                                    <tr>
                                        <td style="text-align:left;">TPA</td>
                                        <td>{{ $tpa_account->name ?? 'N/A' }}</td>
                                    </tr>
                                    <tr>
                                        <td style="text-align:left;">Referral partner</td>
                                        <td>{{ $refferal_partner->name ?? 'N/A' }}</td>
                                    </tr>
                                    <tr>
                                        <td style="text-align:left;">Casualty</td>
                                        <td>{{ ($admission->casualty == '1') ? 'Yes' : 'No' }}</td>
                                    </tr>
                                    
                                   
                                    {{-- <tr>
                                        <td style="text-align:left;">Referred By</td>
                                        <td>{{ $admission->referal_from ?? 'N/A' }}</td>
                                    </tr> --}}
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card">
                        <div class="card-body g-3 row">
                            <div class="table-responsive">
                                <h5 class="mb-0">Patient Details 
                                    <div class="btn-group" style="float: inline-end;">
                                        <button  class="btn btn-warning edit_btn" title="Edit" id="edit_patient" type="button" data-id="{!! $patient->id !!}" data-bs-toggle="modal" data-bs-target="#commonModal">
                                            <i class="bi bi-pencil-square"></i> Edit Patient
                                        </button>
                                    </div>
                                </h5>
                                <hr class="mb-2">
                                <table class="table table-bordered align-middle">
                                <tr>
                                    <td style="text-align:left;"> 
                                        <b>Age/Gender</b>
                                    </td>
                                    <td> 
                                        @if(isset($patient->account_contact->date_of_birth) && !empty($patient->account_contact->date_of_birth))
                                            {{ age($patient->account_contact->date_of_birth) . ' Years' }}
                                        @else
                                        <b><span class="text-danger">Please Add Patient Day of Birth.</span></b>
                                        @endif
                                        @if(isset($patient->account_contact->gender->name) && !empty($patient->account_contact->gender->name))
                                            , {{ $patient->account_contact->gender->name ?? '' }}
                                        @else
                                        <b><span class="text-danger">Please Add Patient Gender.</span></b>
                                        @endif
                                    </td>
                                </tr>
                                <tr>
                                    <td><strong>DOB</strong></td>
                                    <td>
                                        @if(isset($patient->account_contact->date_of_birth) && !empty($patient->account_contact->date_of_birth))
                                         {{ formatedDate($patient->account_contact->date_of_birth) ?? '' }}
                                        @endif
                                    </td>
                                </tr>
                                <tr>
                                    <td><strong>Patient Contact</strong></td>
                                    <td>
                                        @if(isset($patient->account_contact->phone_no) && !empty($patient->account_contact->phone_no))
                                         {{ $patient->account_contact->phone_no ?? '' }}
                                         @else
                                         <b><span class="text-danger">Please Add Patient Contact.</span></b>
                                        @endif
                                    </td>
                                </tr>

                                <tr>
                                    <td><strong>Marital Status</strong></td>
                                    <td>
                                        @if(isset($marital_status->name ) && !empty($marital_status->name ))
                                            {{ $marital_status->name ?? '' }}
                                        @else
                                        <b><span class="text-danger">Please Add Patient Marital Status.</span></b>
                                        @endif
                                    </td>
                                </tr>
                                <tr>
                                    <td><strong>Blood Group</strong></td>
                                    <td>
                                        @if(isset($blood_group->group) && !empty($blood_group->group))
                                             {{ $blood_group->group ?? '' }}
                                        @else
                                        <b><span class="text-danger">Please Add Patient Blood Group.</span></b>
                                        @endif
                                    </td>
                                </tr>
                                {{-- <tr>
                                    <td><strong>Relation</strong></td>
                                    <td>
                                        @if(isset($patient->account_relative->relation_type) && !empty($patient->account_relative->relation_type))
                                         {{ $patient->account_relative->relation_type ?? '' }}
                                         @else
                                         <b><span class="text-danger">Please Add Patient Relation.</span></b>
                                        @endif
                                    </td>
                                </tr> --}}
                                <tr>
                                    <td><strong>Relative Name</strong></td>
                                    <td>
                                        @if(isset($patient->account_relative->relation_name) && !empty($patient->account_relative->relation_name))
                                            <b>{{ $patient->account_relative->relation_name ?? '' }}
                                            @if(isset($patient->account_relative->relation_type) && !empty($patient->account_relative->relation_type))
                                                {{ $patient->account_relative->relation_type ?? '' }}
                                            @endif
                                            ({{ $patient->account_contact->phone_no ?? '' }})</b>
                                        @else
                                        <b><span class="text-danger">Please Add Patient Relative Name.</span></b>
                                        @endif
                                    </td>
                                </tr>

                                {{-- <tr>
                                        <td style="text-align:left;">Previous medical issue</td>
                                        <td>{{ $admission->previous_medical_issue ?? 'N/A' }}</td>
                                    </tr> --}}
                                   
                                    @if ($patient->account_contact->any_known_allergies)
                                    <tr>
                                        <td style="text-align:left;">Any Known Allergies</td>
                                        <td>{{ $patient->account_contact->any_known_allergies }}</td>
                                    </tr>
                                    @endif
                                    @if ($admission->note)
                                    <tr>
                                        <td style="text-align:left;">Admission Note</td>
                                        <td>{{ $admission->note }}</td>
                                    </tr>
                                    @endif
                                    @if (in_array('nurse-notes-list', $authRolePermissions))
                                    <tr>
                                        <td style="text-align:left;">Nurse Notes</td>
                                        <td><a href="{{ route('nurse-notes.index', $admission->id) }}" class="btn btn-dark float-md-end">Nurse Notes</a></td>
                                    </tr>
                                    @endif
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- <div class="col-md-4">
                    <div class="card">
                        <div class="card-body g-3 row">
                            <div class="table-responsive" style="margin-bottom: 18px;">
                                @if (isset($patient->account_images->image) && $patient->account_images->image != '')
                                    <img src="{!! getTempUrl($patient->account_images->image) !!}" height="auto" id="createImage" data-bs-toggle="modal" data-bs-target="#commonModal" style="cursor: pointer; max-width: 120px; width: 120px;">
                                @else
                                    <img src="{!! asset('admin/images/avtaar.png') !!}" width="100%" height="auto" id="createImage" data-bs-toggle="modal" data-bs-target="#commonModal" style="cursor: pointer; max-width: 120px; width: 120px;">
                                @endif
                                <p class="pt-3" style="cursor: pointer;">
                                    <strong>Update Profile Image</strong>
                                </p>
                            </div>
                        </div>
                    </div>
                </div> -->
                <div class="col-md-4">
                    <div class="card">
                        <div class="card-body g-3" id="consultant_tables"></div>
                    </div>
                </div>
                <div class="col-md-12">
                    <div class="card">
                        <div class="card-body g-3" id="billings_tables"></div>
                    </div>
                </div>

                <div class="col-md-12">
                    <div class="card">
                        <div class="card-body g-3" id="beds_tables"></div>
                    </div>
                </div>
                <div class="col-md-12">
                    <div class="card">
                        <div class="card-body g-3" id="body_vitals_tables"></div>
                    </div>
                </div>
                <!-- <div class="col-md-12">
                    <div class="card">
                        <div class="card-body g-3" id="symptoms_tables"></div>
                    </div>
                </div> -->
                <div class="col-md-12">
                    <div class="card">
                        <div class="card-body g-3" id="surgeries_tables"></div>
                    </div>
                </div>
                <!-- BIRTH REGISTER -->
                @if (isset($ipd_admission_female))
                  <div class="col-12 justify-content-center mb-3">
                      <div class="accordion-item">
                          <h2 class="accordion-header" id="panelsStayOpen-headingTwo">
                              <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#panelsStayOpen-collapseTwo1" aria-expanded="false" aria-controls="panelsStayOpen-collapseTwo">
                                  Birth Register:
                              </button>
                          </h2>
                          <div id="panelsStayOpen-collapseTwo1" class="accordion-collapse collapse" aria-labelledby="panelsStayOpen-headingTwo">
                              <div class="card-body g-3" id="birth_register_tables"></div>
                          </div>
                      </div>
                  </div>
                @endif


                <!-- DEATH REGISTER -->
                  <div class="col-12 justify-content-center mb-3">
                      <div class="accordion-item">
                          <h2 class="accordion-header" id="panelsStayOpen-headingTwo">
                              <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#panelsStayOpen-collapseTwo2" aria-expanded="false" aria-controls="panelsStayOpen-collapseTwo">
                                  Death Register:
                              </button>
                          </h2>
                          <div id="panelsStayOpen-collapseTwo2" class="accordion-collapse collapse" aria-labelledby="panelsStayOpen-headingTwo">
                              <div class="card-body g-3" id="death_register_tables"></div>
                          </div>
                      </div>
                  </div>

    <!--end row-->

  <div class="row auto card " style="margin-left: 5px; margin-right: 5px;">
      <div class="col-xl-12 mx-auto">
          <div class="shadow-none radius-5 min-height ">
     @if(in_array('ipd-admission-delete', $authRolePermissions))
            <div class="btn-group card-body">
                <a data-url="{{route('ipd-admissions.destroy')}}"  data-id="{{$admission->id}}" class="btn btn-danger deleteIPDCustom" href="#" class="text-danger" data-bs-toggle="tooltip" data-bs-placement="bottom" title="Delete"> <i class="bi bi-trash"></i>
                   Delete IPD Admission
                </a>
            </div>
            @endif

            @if(isset($sale_invoices->sale_invoices_name))
              <div class="btn-group">
                  @if(!empty($sale_invoices->sale_returns_id))
                  <a href="{!! route('sale-return.edit', $sale_invoices->sale_returns_id) !!}" class="btn btn-warning me-1"><i class="bi bi-arrow-counterclockwise"></i> Sale Return</a>
                  @else
                  <a href="{!! route('sale-return-item-selection', ($sale_invoices->sale_returns_id ?? $sale_invoices->sale_invoices_name)) !!}" class="btn btn-warning me-1"><i class="bi bi-arrow-counterclockwise"></i> Sale Return</a>
                  @endif
              </div>
            @endif

          <div class="btn-group">
              <a href="{{ route('birth-registers.main') }}" class="btn btn-primary"><i class="bi bi-receipt"></i> Birth Register</a>
          </div> 
  </div>
      </div>
  </div>


@endsection

@section('js')
<!-- <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> -->
<script type="text/javascript" src="{{ asset('admin/plugins/datepicker/js/bootstrap-datepicker.js')}}"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-datetimepicker/2.5.20/jquery.datetimepicker.full.min.js" integrity="sha512-AIOTidJAcHBH2G/oZv9viEGXRqDNmfdPVPYOYKGy3fti0xIplnlgMHUGfuNRzC6FkzIo0iIxgFnr9RikFxK+sw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/12.1.10/js/intlTelInput.js"></script>
<!-- <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> -->

<!-- Include Flatpickr JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>

<script type="text/javascript">

  $(document).on('click', '#createImage', function(){
    $('#commonModalLabel').text('Upload New Image');
    $('.save_button_span').text('Upload Image');
    $.ajax({
      url:"{!! route('account-images.create_images', $patient->id) !!}",
      success:function(data){
        $('#commonModal').find('.modal-body').html('');
        $('#commonModal').find('.modal-body').html(data);
      }
    });
  });

  $(document).on('click', '#addConsultant', function(){
    $('#commonModalLabel').text('Add Consultant');
    $('.save_button_span').text('Save Consultant');
    $.ajax({
      url:"{!! route('ipd-admission-consultants.create', $admission->id) !!}",
      success:function(data){
        $('#commonModal').find('.modal-body').html('');
        $('#commonModal').find('.modal-body').html(data);
      }
    });
  });

  $(document).on('click', '#createBodyVitals', function(){
    $('#commonModalLabel').text('Add Body Vitals');
    $('.save_button_span').text('Save Body Vitals');
    $.ajax({
      url:"{!! route('ipd-admissions-body-vitals.create', $admission->id) !!}",
      success:function(data){
        $('#commonModal').find('.modal-body').html('');
        $('#commonModal').find('.modal-body').html(data);

        $('.datepicker').datepicker({
            "dateFormat": "yy-mm-dd",
            "changeMonth": true,
            "changeYear": true
        });
      }
    });
  });

  $(document).on('click', '.editBodyVitals', function(){
    $('#commonModalLabel').text('Edit Body Vitals');
    $('.save_button_span').text('Update Body Vitals');

    var id = $(this).data('id');
    var url = "{{ route('ipd-admissions-body-vitals.edit', ":id") }}";
    url = url.replace(':id', id);

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

  $(document).on('click', '#createBed', function(){
    $('#commonModalLabel').text('Select Bed');
    // $('.save_button').html('Next <i class="bx bx-right-arrow"></i>');
    $('.save_button').hide();
    $.ajax({
      url:"{!! route('ipd-admissions-beds.create', $admission->id) !!}",
      success:function(data){
        $('#commonModal').find('.modal-body').html('');
        $('#commonModal').find('.modal-body').html(data);
        $('#check_in_date_time').datetimepicker({
          format:'d/m/Y H:i A',
        });
        $('#check_out_date_time').datetimepicker({
          format:'d/m/Y H:i A',
        });
      }
    });
  });

  $(document).on('click', '.bedTransfer', function(){
    $('#commonModalLabel').text('Transfer Patient');
    // $('.save_button').html('Next <i class="bx bx-right-arrow"></i>');
    var bed_history_id  =$(this).data('id');
    $('.save_button').hide();
    $.ajax({
      url:"{!! route('ipd-admissions-beds.create', $admission->id) !!}?type=transfer&bed_history_id="+bed_history_id,
      success:function(data){
        $('#commonModal').find('.modal-body').html('');
        $('#commonModal').find('.modal-body').html(data);
        $('#check_in_date_time').datetimepicker({
          format:'d/m/Y H:i A',
        });
        $('#check_out_date_time').datetimepicker({
          format:'d/m/Y H:i A',
        });
      }
    });
  });

  /*$(document).on('click', '#createBed', function(){
    $('#commonModalLabel').text('Add Bed');
    $('.save_button_span').text('Assign Bed To Patient');
    $.ajax({
      url:"{!! route('ipd-admissions-beds.create', $admission->id) !!}",
      success:function(data){
        $('#commonModal').find('.modal-body').html('');
        $('#commonModal').find('.modal-body').html(data);
        $('#check_in_date_time').datetimepicker({
          format:'d/m/Y H:i A',
        });
        $('#check_out_date_time').datetimepicker({
          format:'d/m/Y H:i A',
        });
      }
    });
  });*/

  $(document).on('click', '.editBed', function(){
    $('#commonModalLabel').text('Edit Bed');
    $('.save_button_span').text('Update Bed');

    var id = $(this).data('id');
    var url = "{{ route('ipd-admissions-beds.edit', ":id") }}";
    url = url.replace(':id', id);

    $.ajax({
      url:url,
      success:function(data){
        $('#commonModal').find('.modal-body').html('');
        $('#commonModal').find('.modal-body').html(data);
        $('#check_in_date_time').datetimepicker({
            format:'d/m/Y H:i A',
        });
        $('#check_out_date_time').datetimepicker({
            format:'d/m/Y H:i A',
        });
      }
    });
  });


    // EDIT SYMPTOMS 
    $(document).on('click', '#editSymptoms', function(){

    $('#commonModalLabel').text('Edit Diagnosis');

    $('.save_button_span').text('Update Diagnosis');

        var id  = $(this).data('id');
        var url = "{{ route('ipd-admission-symptoms.edit', ':id') }}";
        url     = url.replace(':id', id);

        $.ajax({

        url :url,
        success:function(data){

        $('#commonModal').find('.modal-body').html('');
        $('#commonModal').find('.modal-body').html(data);
      }
    });
    });



// CREATE SYMPTOMS 
  $(document).on('click', '#addSymptom', function(){
    $('#commonModalLabel').text('Add Diagnosis');
    $('.save_button_span').text('Save Diagnosis');
    $.ajax({
      url:"{!! route('ipd-admission-symptoms.create', $admission->id) !!}",
      success:function(data){
        $('#commonModal').find('.modal-body').html('');
        $('#commonModal').find('.modal-body').html(data);
      }
    });
  });


// SURGERIES
  $(document).on('click', '#addSurgery', function(){
    $('#commonModalLabel').text('Add Surgery');
    $('.save_button_span').text('Save Surgery');
    $.ajax({
      url:"{!! route('ipd-surgeries.create', $admission->id) !!}",
      success:function(data){
        $('#commonModal').find('.modal-body').html('');
        $('#commonModal').find('.modal-body').html(data);

        $('#scheduled_date').datepicker({
            "dateFormat" : "yy-mm-dd",
            "changeMonth": true,
            "changeYear": true
        });
      }
    });
  });


// BIRTH-REGISTERS
   $(document).on('click', '#addBirthRegister', function(){
    $('#commonModalLabel').text('Add Birth Register');
    $('.save_button_span').text('Save Birth Register');
    $.ajax({
      url:"{!! route('birth-registers-account-create', $admission->id) !!}",
      success:function(data){
        $('#commonModal').find('.modal-body').html('');
        $('#commonModal').find('.modal-body').html(data);
      }
    });
  });

// DEATH-REGISTERS
   $(document).on('click', '#addDeathRegister', function(){
    $('#commonModalLabel').text('Add Death Register');
    $('.save_button_span').text('Save Death Register');
    $.ajax({
      url:"{!! route('death-registers-account-create', $admission->id) !!}",
      success:function(data){
        $('#commonModal').find('.modal-body').html('');
        $('#commonModal').find('.modal-body').html(data);
      }
    });
  });

// ASSIGN TEAMS
  $(document).on('click', '#assignTeam', function(){
    var id = $(this).data('id');
    var url = "{{ route('ipd-surgeries-assign-team.create', ':id') }}";
    url = url.replace(':id', id);
    var patientName = "{{ $patient->account_title ? $patient->account_title->name : '' }} {{ $patient->name ? $patient->name : '' }} ({{ $patient->code }})";
   
    $('#commonModalLabel').text('Surgery Team - ' + patientName); 
    $('.save_button_span').text('Save And Close');
    $.ajax({
      url : url,  
      success:function(data){
        $('#commonModal').find('.modal-body').html('');
        $('#commonModal').find('.modal-body').html(data);
      }
    });
  });

// Anesthesia
  $(document).on('click', '.anesthesia-create', function(){
    var id          = $(this).data('id');
    var url         = "{{ route('ipd-surgeries-anesthesia-create', ':id') }}";
    url             = url.replace(':id', id);
    var patientName = "{{ $patient->account_title ? $patient->account_title->name : '' }} {{ $patient->name ? $patient->name : '' }} ({{ $patient->code }})";
   
    $('#commonModalLabel').text('Surgery Anesthesia - ' + patientName); 
    $('.save_button_span').text('Save And Close');
    $.ajax({
      url : url,  
      success:function(data){
        $('#commonModal').find('.modal-body').html('');
        $('#commonModal').find('.modal-body').html(data);
      }
    });
  });

   $(document).on('click', '#SaveAssignTeamButton', function(){
    $.ajax({
      success:function(data){
        $('#assignTeamTable').html('');
        $('#assignTeamTable').html(data);
      }
    });
  });

  $(document).on('click', '.refresh', function(){
    var id = $(this).data('id');
    var url = "{!! route('refresh-bed-billing', ':id') !!}";

    $.ajax({
      url         : url.replace(':id',id),
      headers     : { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
      processData : false,
      contentType : false,
      type        : 'POST',
      success:function(data){
        if (data.success == true) {
          toastr.success(data.message, 'Error!');
          fetch_beds();
        } else {
          toastr.error(data.message, 'Error!');
        }
      }
    });
  });

$(document).on('click', '.save_button', function(event){
    event.preventDefault();
    var error = 0;

    if ($('#commonModal').find('form').hasClass('image')) {
        $('.error_file').hide();
        $('.error_title').hide();

        if ($('#commonModal').find('form').find('[name="file"]') == '') {
          $('.error_file').show();
          error = 1;
        }

        var account_id = $('#commonModal').find('form').find('input[name="account_id"]').data('id');
        $('#commonModal').find('form').find('input[name="account_id"]').val(account_id);

        if (error == 0) {
          $('#commonModal').find('form').submit();
        }
    }

    // CREATE SURGERY
    if ($('#commonModal').find('form').hasClass('create_surgery')) {
        if (error == 0) {
            let formdata = new FormData($('#create_surgery_form')[0]);
            $.ajax({
                url: $('#create_surgery_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="surgery_id"]').val(response.data.id);
                        $('#surgery_id').val(response.data.name);

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

    // EDIT SURGERY
    if ($('#commonModal').find('form').hasClass('edit_surgery')) {
      if (error == 0) {
          $.ajax({
              url: $('#edit_surgery_form').attr('action'),
              data: $('#edit_surgery_form').serialize(),
              // processData: false,
              // contentType: false,
              type: 'PUT',
              success: function (response) {
                  if (response.success === true) {
                      toastr.success(response.message, 'Success.');
                      $('[name="surgery_id"]').val(response.data.id);
                      $('#commonModal').modal('hide');
                      $('#commonModal').find('.modal-body').html('');

                      fetch_surgeries();
                      } else {
                          // Handle failure case
                          var ErroMsg = $(this).printErrorMsg(response.message);
                          $(this).Toastshow('error', ErroMsg);
                      }
              }
          })
          .fail(function(jqXHR, textStatus, errorThrown) {
              console.log('AJAX request failed:', textStatus, errorThrown);
              toastr.error('An error occurred during the request.', 'Error!');
          });
      }
    }

    // CREATE BIRTH REGISTER 
    if ($('#commonModal').find('form').hasClass('create_birth_register')) {
        if (error == 0) {
            let formdata = new FormData($('#create_birth_register_form')[0]);
            $.ajax({
                url: $('#create_birth_register_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="birth_registers_id"]').val(response.data.id);
                        $('#birth_registers_id').val(response.data.name);

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

    // EDIT BIRTH REGISTER 
    if ($('#commonModal').find('form').hasClass('edit_birth_register')) {
      if (error == 0) {
          $.ajax({
              url: $('#edit_birth_register_form').attr('action'),
              data: $('#edit_birth_register_form').serialize(),
              // processData: false,
              // contentType: false,
              type: 'POST',
              success: function (response) {
                  if (response.success === true) {
                      toastr.success(response.message, 'Success.');
                      $('[name="birth_registers_id"]').val(response.data.id);
                      $('#commonModal').modal('hide');
                      $('#commonModal').find('.modal-body').html('');

                      fetch_birth_register();
                      } else {
                          // Handle failure case
                          var ErroMsg = $(this).printErrorMsg(response.message);
                          $(this).Toastshow('error', ErroMsg);
                      }
              }
          })
          .fail(function(jqXHR, textStatus, errorThrown) {
              console.log('AJAX request failed:', textStatus, errorThrown);
              toastr.error('An error occurred during the request.', 'Error!');
          });
      }
    }

    // CREATE DEATH REGISTER 
    if ($('#commonModal').find('form').hasClass('create_death_register')) {
        if (error == 0) {
            let formdata = new FormData($('#create_death_register_form')[0]);
            $.ajax({
                url: $('#create_death_register_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="death_registers_id"]').val(response.data.id);
                        $('#death_registers_id').val(response.data.name);

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

    // EDIT DEATH REGISTER 
    if ($('#commonModal').find('form').hasClass('edit_death_register')) {
      if (error == 0) {
          $.ajax({
              url: $('#edit_death_register_form').attr('action'),
              data: $('#edit_death_register_form').serialize(),
              // processData: false,
              // contentType: false,
              type: 'POST',
              success: function (response) {
                  if (response.success === true) {
                      toastr.success(response.message, 'Success.');
                      $('[name="death_registers_id"]').val(response.data.id);
                      $('#commonModal').modal('hide');
                      $('#commonModal').find('.modal-body').html('');

                      fetch_death_register();
                      } else {
                          // Handle failure case
                          var ErroMsg = $(this).printErrorMsg(response.message);
                          $(this).Toastshow('error', ErroMsg);
                      }
              }
          })
          .fail(function(jqXHR, textStatus, errorThrown) {
              console.log('AJAX request failed:', textStatus, errorThrown);
              toastr.error('An error occurred during the request.', 'Error!');
          });
      }
    }

    // CREATE Symptoms 
    if ($('#commonModal').find('form').hasClass('create_symptom')) {

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

                url: $('#create_symptom_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="symptoms_id"]').val(response.data.id);
                        $('#symptoms_id').val(response.data.name);
                        // hide modal
                        $('#commonModal').modal('hide');
                        $('#commonModal').find('.modal-body').html('');
                        fetch_symptoms();
                    } 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!');
            });
        }
    }

    // EDIT DEATH REGISTER 
    if ($('#commonModal').find('form').hasClass('create_surgery_anesthesia')) {
      if (error == 0) {
          $.ajax({
              url: $('#commonModal').find('form').attr('action'),
              data:$('#commonModal').find('form').serialize(),
              // processData: false,
              // contentType: false,
              type: 'POST',
              success: function (response) {
                  if (response.success === true) {
                      toastr.success(response.message, 'Success.');

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

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

    // Edit Symptoms 
    if ($('#commonModal').find('form').hasClass('edit_symptom')) {
        if (error == 0) {
            let formdata = new FormData($('#edit_symptom_form')[0]);
            $.ajax({
                url: $('#edit_symptom_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="symptoms_id"]').val(response.data.id);
                        $('#symptoms_id').val(response.data.name);

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

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

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

    else if ($('#commonModal').find('form').hasClass('bed')) {
      $('.error_bed_no_id').hide();


      if ($('[name="bed_id"]').val() == '') {
        toastr.error('Please select a bed first!', 'Error!');
        error = 1;
      }

     

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

          $.ajax({
              url: "{!! route('ipd-admissions-beds.create-step-2', $admission->id) !!}",
              data: formdata,
              processData: false,
              contentType: false,
              type: 'POST',
              success: function (response) {
                $('#commonModalLabel').text('Assign Bed');
                $('.save_button').html('<i class="bx bx-save"></i> <span class="save_button_span">Save Bed</span>');
                $('#commonModal').find('.modal-body').html('');
                $('#commonModal').find('.modal-body').html(response);
                $('#check_in_date_time').datetimepicker({
                    format:'d/m/Y H:i A',
                  });
              }
          })
          .fail(function(jqXHR, textStatus, errorThrown) {
              console.log('AJAX request failed:', textStatus, errorThrown);
              toastr.error('An error occurred during the request.', 'Error!');
          });
      }
    }
    else if ($('#commonModal').find('form').hasClass('update-bed')) {
      if ($('[name="bed_no_id"]').val() == '') {
        toastr.error('Please select a bed first!', 'Error!');
        error = 1;
      }

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

          $.ajax({
              url: $('#add_bed').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('');

                      fetch_beds();
                  } else {
                      toastr.error(response.message, 'Error!');
                  }
              }
          })
          .fail(function(jqXHR, textStatus, errorThrown) {
              console.log('AJAX request failed:', textStatus, errorThrown);
              toastr.error('An error occurred during the request.', 'Error!');
          });
      }
    }
    else if ($('#commonModal').find('form').hasClass('consultant')) {
      $('.error_doctor_id').hide();

      if ($('#doctor_id').val() == '') {
        $('.error_doctor_id').show();
        error = 1;
      }

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

          $.ajax({
              url: $('#add_consultant').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('');

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

    else if ($('#commonModal').find('form').hasClass('body_vitals')) {
      $('.error_vital_columns').hide();

      error = 0;

      $('.vital_columns').each(function() {
        if ($(this).attr('required') && $(this).val() == '') {
            error = 1;
        }
      });

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

          $.ajax({
            url: $('#add_body_vitals').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('');

                    fetch_body_vitals();
                } else {
                    toastr.error(response.message, 'Error!');
                }
            }
          })
          .fail(function(jqXHR, textStatus, errorThrown) {
              console.log('AJAX request failed:', textStatus, errorThrown);
              toastr.error('An error occurred during the request.', 'Error!');
          });
      } else {
         toastr.error('Please fill all required fields!', 'Error!');
      }
    }
    else if ($('#commonModal').find('form').hasClass('license-types')) {
          $('.error_name').hide();
          $('.error_code').hide();
          $('.error_priority').hide();
          var error = 0;

          if ($('#commonModal').find('form').find('input[name="name"]').val().trim() == '') {
            $('.error_name').show();
            error = 1;
          }
          if ($('#commonModal').find('form').find('input[name="code"]').val().trim() == '') {
            $('.error_code').show();
            error = 1;
          }
          if ($('#commonModal').find('form').find('input[name="priority"]').val().trim() == '') {
            $('.error_priority').show();
            error = 1;
          }

          if (error == 0) {
            let formdata = new FormData($('#commonModal').find('form')[0]);

            $.ajax({
                url: "{!! route('license-types.store') !!}",
                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');

                      setTimeout(function() {
                          clickBTN();
                      }, 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!');

                // hide modal
                $('#commonModal').modal('hide');
                $('#commonModal').find('.modal-body').html('');
            });
          }
        }
    else if ($('#commonModal').find('form').hasClass('symptom')) {
      $('.error_symptom_type').hide();
      $('.error_symptom_title').hide();

      if ($('.symptom_type').val() == '') {
        $('.error_symptom_type').show();
        error = 1;
      }

      if ($('.symptom_title').val() == '' || $('.symptom_title').val() == null) {
        $('.error_symptom_title').show();
        error = 1;
      }

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

          $.ajax({
            url: $('#add_symptoms').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('');

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

$(document).ready(function(){
fetch_beds();
fetch_consultants();
fetch_body_vitals();
fetch_symptoms();
fetch_surgeries();
fetch_birth_register();
fetch_death_register();
fetch_billing();
});

function fetch_beds(){
$.ajax({
  url:"{!! route('ipd-admission-beds.index', $admission->id) !!}",
  success:function(data){
    $('#beds_tables').html('');
    $('#beds_tables').html(data);
    $(document).ready(function(){$.switcher();});
  }
})
}

function fetch_consultants(){
$.ajax({
  url:"{!! route('ipd-admission-consultants.index', $admission->id) !!}",
  success:function(data){
    $('#consultant_tables').html('');
    $('#consultant_tables').html(data);
  }
})
}

function fetch_body_vitals(){
$.ajax({
  url:"{!! route('ipd-admissions-body-vitals.index', $admission->id) !!}",
  success:function(data){
    $('#body_vitals_tables').html('');
    $('#body_vitals_tables').html(data);
  }
})
}

function fetch_symptoms(){
    return;
// $.ajax({
//   url:"{!! route('ipd-admission-symptoms.index', $admission->id) !!}",
//   success:function(data){
//     $('#symptoms_tables').html('');
//     $('#symptoms_tables').html(data);
//   }
// })
}

function fetch_billing(voucherType = ''){
    var billing_date_picker = $('.billing_date_picker').val()??'{!! date("m/d/Y") !!}';
    var from_date = $('.from_date').val()??'{!! date("m/d/Y", strtotime($admission->admission_date_time)) !!}';
    var url = "{!! route('ipd-billings.index', $admission->id) !!}?display=admission&voucherType="+voucherType+'&billing_date_picker='+billing_date_picker+'&from_date='+from_date;

    $.ajax({
      url:url,
      success:function(data){
        $('#billings_tables').html('');
        $('#billings_tables').html(data);
        // $(document).ready(function(){$.switcher();});

        $('.billing_date_picker').datepicker({
            "dateFormat" : "yy-mm-dd",
            "changeMonth": true,
            "changeYear": true
        });
        $('.from_date').datepicker({
            "dateFormat" : "yy-mm-dd",
            "changeMonth": true,
            "changeYear": true
        });
      }
    })
}
function fetch_surgeries(){
$.ajax({
  url:"{!! route('ipd-surgeries.index', $admission->id) !!}",
  success:function(data){
    $('#surgeries_tables').html('');
    $('#surgeries_tables').html(data);
    // $(document).ready(function(){$.switcher();});
  }
})
}


function fetch_birth_register(){
$.ajax({
  url:"{!! route('birth-registers.index' , $admission->id) !!}",
  success:function(data){
    $('#birth_register_tables').html('');
    $('#birth_register_tables').html(data);
    // $(document).ready(function(){$.switcher();});
  }
})
}


function fetch_death_register(){
$.ajax({
  url:"{!! route('death-registers.index' , $admission->id) !!}",
  success:function(data){
    $('#death_register_tables').html('');
    $('#death_register_tables').html(data);
    // $.switcher();
  }
})
}




// CREATE SURGERY TEAM
$(document).on('click', '#saveAssignTeamButton', function(event) {
    event.preventDefault();

    var error = 0;

    // Check if the form has the 'create_surgery_team' class
    if ($('#commonModal').find('form').hasClass('create_surgery_team')) {
        if (error === 0) {
            // Create FormData object from the form
            let formdata = new FormData($('#create_surgery_team_form')[0]);

            $.ajax({
                url: $('#create_surgery_team_form').attr('action'),
                data: formdata,
                processData: false,
                contentType: false,
                type: 'POST',
                success: function(response) {
                    if (response.success === true) {
                        toastr.success(response.message, 'Success.');
                        
                        var content = ``;
                        $.each(response.data, function (index,value) {
                            var url = "{!! route('surgery-team-destroy', ':id') !!}";
                            url = url.replace(':id', value.id);

                            console.log(url);
                          // console.log(value);
                           content += `<tr>
                                <td>${index + 1}</td>
                                <td class="text-left">
                                    <b>${value.surgent_name}</b><br>
                                    ${value.designation_name}
                                </td>
                                <td class="text-left">${value.responsibility}</td>
                                <td class="text-center">
                                    <a data-url="`+ url + `" class="btn btn-danger deleteDataCustom" data-bs-toggle="tooltip" data-bs-placement="bottom" title="Delete">
                                        <i class="bi bi-trash text-white"></i>
                                    </a>
                                </td>
                            </tr>`;
                        });
                        $('#assignTeamTable').html(content);
                        $('#doctor_name').val('');
                        $('#designation_id').val('');
                        $('#responsibility').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!');
            });
        }
    }
});


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

    Swal.fire({
        title: 'Are you sure you want to change status?',
        icon: 'warning',
        showDenyButton: true,
        showCancelButton: false,
        confirmButtonText: 'Yes',
        denyButtonText: 'No',
    }).then((result) => {
        if (result.isConfirmed) {
            $.ajax({
                url     : UrlValue,
                method  : 'post',
                data    :dataString,
                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_surgeries();
                    } else {
                        var ErroMsg = $(this).printErrorMsg(response.message);
                        if (ErroMsg === '') {
                            ErroMsg = "Something went wrong!";
                        }
                        $(this).Toastshow('error',ErroMsg);

                        if (status == 1) {
                            changeStatus.parent().find('.ui-switcher').attr('aria-checked', false);
                        } else {
                            changeStatus.parent().find('.ui-switcher').attr('aria-checked', true);
                        }
                    }
                },
                error: function (data) {
                    console.log("error ",data);

                    if (status == 1) {
                        changeStatus.parent().find('.ui-switcher').attr('aria-checked', false);
                    } else {
                        changeStatus.parent().find('.ui-switcher').attr('aria-checked', true);
                    }
                }
            });
        }
        else if (result.isDenied) {
          var page        = $('.pager').find('.active a').attr('href') == undefined ? 1 : $('.pager').find('.active a').attr('href').split('page=')[1];
          var column_name = $('.sorting').val()?$('.sorting').val():'';
          var sort_type   = $('#hidden_sort_type').val();
          var query       = $('#search').val()?$('#search').val():'';

          fetch_data(page, sort_type, column_name, query);
        }
        //return false;
    });
//return false;
});


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

  Swal.fire({
      title: 'Are you sure you want to delete this?',
      icon: 'warning',
      showDenyButton: true,
      showCancelButton: false,
      confirmButtonText: 'Yes',
      denyButtonText: 'No',
  }).then((result) => {
      if (result.isConfirmed) {
          $.ajax({
              url: UrlValue,
              method: 'delete',
              data: {
                  "_token": $('meta[name="csrf-token"]').attr('content'),
                  "id": $(this).data('id')
              },
              headers: {
                  'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
              },
              success: function(response) {
                  if (response.success) {
                 
                    $(this).Toastshow('success', response.message);// Refresh surgery team data
                    fetch_beds();
                    fetch_consultants();
                    fetch_body_vitals();
                    fetch_symptoms();
                    fetch_surgeries();
                    fetch_birth_register();
                    fetch_death_register();
                    fetch_billing();
                    $('#assignTeamTable').html('');
                    var content = ``;
                    $.each(response.data, function (index,value) {
                        var url = "{!! route('surgery-team-destroy', ':id') !!}";
                        url = url.replace(':id', value.id);

                        console.log(url);
                      // console.log(value);
                       content += `<tr>
                            <td>${index + 1}</td>
                            <td class="text-left">
                                <b>${value.surgent_name}</b><br>
                                ${value.designation_name}
                            </td>
                            <td class="text-left">${value.responsibility}</td>
                            <td class="text-center">
                                <a data-url="`+ url +`" class="btn btn-danger deleteDataCustom" data-bs-toggle="tooltip" data-bs-placement="bottom" title="Delete">
                                    <i class="bi bi-trash text-white"></i>
                                </a>
                            </td>
                        </tr>`;
                    })
               
                    $('#assignTeamTable').html(content);
                    $('#doctor_name').val('');
                    $('#designation_id').val('');
                    $('#responsibility').val('');
                  } else {
                      // Handle failure case
                      var ErroMsg = $(this).printErrorMsg(response.message);
                      $(this).Toastshow('error', ErroMsg);
                  }
              },
              error: function(data) {
                  console.log("error ", data);
              }
          });
      }
  });
});

/*********delete data**********/
$("body").on("click", '.deleteDataCustomBed', function(event) {
  var UrlValue = $(this).data('url');

  Swal.fire({
      title: 'Are you sure you want to delete this?',
      icon: 'warning',
      showDenyButton: true,
      showCancelButton: false,
      confirmButtonText: 'Yes',
      denyButtonText: 'No',
  }).then((result) => {
      if (result.isConfirmed) {
          $.ajax({
              url: UrlValue,
              method: 'post',
              data: {
                  "_token": $('meta[name="csrf-token"]').attr('content'),
                  "id": $(this).data('id')
              },
              headers: {
                  'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
              },
              success: function(response) {
                  if (response.success) {
                    $(this).Toastshow('success', response.message);// Refresh surgery team data
                    
                    fetch_beds();
                    fetch_symptoms();
                  } else {
                      // Handle failure case
                      var ErroMsg = $(this).printErrorMsg(response.message);
                      $(this).Toastshow('error', ErroMsg);
                  }
              },
              error: function(data) {
                  console.log("error ", data);
              }
          });
      }
  });
});
/*********delete data**********/
$("body").on("click",'.deleteIPDCustom', function(event){
    dataString    = {"id":$(this).data('id')};
    var UrlValue  = $(this).data('url');
    var btn = $(this);

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

                    $(this).Toastshow('success',ErroMsg);
                    window.location.href = "{!! route('ipd-admissions.index') !!}";
                }else{
                    var ErroMsg = $(this).printErrorMsg(response.message);
                    $(this).Toastshow('error',ErroMsg);
                }
            },
            error: function (data) {
              console.log("error ",data);
            }
        });
        }
    });
});


  //////////////////////////////////////////////IPD ADMSSION DOCTOR WALI JS ///////////////////////////////////////////////////////////////
  $(document).on('click', '#bodyVitals', function(){
        if ($('#bodyVitals').hasClass('hiddenVitals')) {
            $('.body_vitals_details').show();
            $('#bodyVitals').html('<i class="bx bx-minus"></i> Hide Vitals');
            $('#bodyVitals').removeClass('hiddenVitals');
        } else {
            $('.body_vitals_details').hide();
            $('#bodyVitals').html('<i class="bx bx-plus"></i> Add Vitals');
            $('#bodyVitals').addClass('hiddenVitals');
        }
    });
    function allNumeric(inputtxt) {
        onlyNumbers = inputtxt.replace(/[^0-9]/g, '');
        if (onlyNumbers.length > 16) {
            onlyNumbers = onlyNumbers.substring(0, 16);
        }
        return onlyNumbers;
    }
    $("#ipd_file_no").on('input', function() {
        const onlyNumbers = allNumeric($(this).val());
        $("#ipd_file_no").val(onlyNumbers);
    });
    $(document).on('click','.save_button', function(e) {
        e.preventDefault();
        
        if ($('#commonModal').find('form').hasClass('create_doctor')) {
            if ($('#phone_no').val() != '') {
                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_country_id').hide();
            var error = 0;

            if ($('input[name="name"]').val() == '') {
              $('.error_name').show();
              error = 1;
            }
            if ($('[name="country_id"]').val() == '') {
              $('.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_id').val(response.data.name);
                            $('#edit_doctor').prop('disabled', false);
                            // hide modal
                            $('#commonModal').modal('hide');
                            $('#commonModal').find('.modal-body').html('');
                        } else {
                            toastr.error(response.message, 'Error!');
                        }
                    }
                })
                .fail(function(jqXHR, textStatus, errorThrown) {
                    console.log('AJAX request failed:', textStatus, errorThrown);
                    toastr.error('An error occurred during the request.', 'Error!');
                });
            }
        }
        else if ($('#commonModal').find('form').hasClass('create_cities')) {
            console.log('tset');
            event.preventDefault();
            $('.error_name').hide();
            var error = 0;
            setTimeout(function() {
                $('.error_name').hide();
            }, 3000);


            if ($('#commonModal').find('form').find('input[name="name"]').val() == '') {
                $('.error_name').show();
                error = 1;
            }

            if (error == 0) {
                let formdata = new FormData($('#commonModal').find('form')[0]);

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

                            // var page = $('.pager').find('.active a').attr('href') == undefined ? 1 : $('.pager').find('.active a').attr('href').split('page=')[1];
                            // var column_name = $('.sorting').val() ? $('.sorting').val() : '';
                            // var sort_type = $('#hidden_sort_type').val();
                            // var query = $('#search').val() ? $('#search').val() : '';

                            // fetch_data(page, sort_type, column_name, query);

                            // hide modal
                            $('#commonModal').removeClass('create_cities');
                            $('#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!');

                // hide modal
                $('#commonModal').modal('hide');
                $('#commonModal').find('.modal-body').html('');
            });
            }
            error = 1;
        }
        else if ($('#commonModal').find('form').hasClass('update_doctor_details')) {
            console.log('as');
            if ($('#phone_no').val() != '') {
                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();
            var error = 0;

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

            }



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

                $.ajax({
                    url: $('#update_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_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!');
                });
            }
            // Check if the form has the 'create_surgery_team' class

        }
        else if ($('#commonModal').find('form').hasClass('update_patient')) {
            console.log('as');
            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());
            }
            $('#year').trigger("change")

            const yearInput  = $('#year').val();
            const monthInput = $('#month').val();
            const dayInput   = $('#day').val();
            const hourInput  = $('#hour').val();

            if (yearInput == '' & monthInput == '' &  dayInput == '' & hourInput == '' ) {
                // toastr.error('Date field is required!', 'Error');
                $('.error_date_of_birth').show();
                error = 1;
                setTimeout(function () {
                    $('.error_date_of_birth').hide();
                }, 3000);
            }

            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());
            }
            if ($('#relation_phone').val().trim() != '') {
                var dailcode_title = $('.relation_phone_col .selected-flag').attr('title');
                var dailcode_array = dailcode_title.split("+");
                $('input[name="relation_phone"]').val("+" + dailcode_array[1] + $('#relation_phone').val());
            }

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

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

            }

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

            }

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

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

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

            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;
              setTimeout(function () {
                $('.error_date_of_birth').hide();
                }, 3000);

            }

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

                $.ajax({
                    url: $('#update_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
                            location.reload();
                            // 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!');
                });
            }
        }

        ///SAVE AND CLOSE BUTTON FUNCTIONALITY
        if ($('#commonModal').find('form').hasClass('create_surgery_team')) {
            $.ajax({
                success: function(response) {
                    // Hide the modal and clear its content
                    $('#commonModal').modal('hide');
                    $('#commonModal').find('.modal-body').html('');
                }
            })
        }
    
        else {
            $('.error_doctor_id').hide();
            $('.error_admission_date').hide();
            $('.error_ipd_file_no').hide();

            var error = 0;

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

            }

            if ($('[name="admission_date_time"]').val() == '') {
              $('.error_admission_date').show();
              error = 1;
            }

            if (error == 0) {
                $('.ipd-admission-form').submit();
            }
        }

        error = 1;
    })

    function reinitializeTelInput(countryCode) {
        if ($('#relation_phone').length > 0) {
            var telInput = $('#commonModal').find('#phone_no , #whatsapp_no , #alternative_no, #relation_phone');
        } else {
            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
        });
    }
   

    /**************** create doctor ********************/
    $(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" : "yy-mm-dd",
                "maxDate": '0',
                "changeMonth": true,
                "changeYear": true
            }).datepicker("setDate",'now')
            .on('changeDate', function (ev) {
                 $(this).datepicker('hide');
            })
            .on('focusout', function (ev) {
                 $(this).datepicker('hide');
            });
          }
        })
    })

    /************* edit doctor *************/
     $(document).on('click', '#edit_doctor', function() {
      console.log('Working');
        var DoctortName = $('[name="doctor_id"]').val();

        if (DoctortName === "") {
            $('.error_doctor_id').show();
        } else {
            $('.error_doctor_id').hide();

            $('#commonModalLabel').text('Edit Doctor');
            $('.save_button_span').text('Update Doctor');
            var id = $('[name="doctor_id"]').val();

            var url = `{!! route('doctor-account-edit', ':id') !!}`.replace(':id', id);

            $.ajax({
                url: url,
                success: function(data) {
                    $('#commonModal').find('.modal-body').html('');
                    $('#commonModal').find('.modal-body').html(data);
                    $('[name="date_of_birth"]').datepicker('destroy');

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

    function CitySelected(id) {
        if ($('[name="city_id"]').length > 0) {
            $('[name="city_id"]').val(id);
        } else {
            setTimeout(function() {
                CitySelected(id);
            }, 1000);
        }
    }

     /**************** Create City ********************/
     $(document).on('click', '#create_city', function() {
        $('#commonModalLabel').text('Add New City');
        $('.save_button_span').text('Save City');
        $.ajax({
            url: "{!! route('cities.create') !!}",
            success: function(data) {
                $('#commonModal').find('.modal-body').html('');
                $('#commonModal').find('.modal-body').html(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;
        }
    };

    /******* Disabling & Enabling edit button of doctor ************/
    $(document).ready(function() {
        function toggleEditButton() {
            var DoctorId = $('[name="doctor_id"]').val();
            $('#edit_doctor').prop('disabled', DoctorId === "");
        }

        toggleEditButton();

        $('#doctor_id').on('input', function() {
            toggleEditButton();
        });

        $('#doctor_id').on('change', function() {
            toggleEditButton();
        });

        $('#edit_doctor').on('click', function() {
            var DoctortName = $('#doctor_id').val();

            if (DoctortName === "") {
                $('.error_doctor_id').show();
            } else {
                $('.error_doctor_id').hide();

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

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

        function enableEditButton() {
            $('#edit_doctor').prop('disabled', false);
        }

        function addValueToDoctorId(newValue) {
            $('[name="doctor_id"]').val(newValue);
            enableEditButton();
        }
    });


    // Edit Surgery Modal 
    $(document).on('click', '#editSurgery', function() {
    var id = $(this).data('id');
     $('#commonModalLabel').text('Edit Surgery');
        $('.save_button_span').text('Update Surgery');
        var url = `{!! route('ipd-surgeries.edit', ':id') !!}`.replace(':id', id);

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


    // EDIT BIRTH-REGISTER
    $(document).on('click', '#editBirthRegister', function() {
      var id = $(this).data('id');
       $('#commonModalLabel').text('Edit Birth Register');
          $('.save_button_span').text('Update Birth Register');
          var url = `{!! route('birth-registers.edit', ':id') !!}`.replace(':id', id);

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


     // EDIT DEATH-REGISTER
    $(document).on('click', '#editDeathRegister', function() {
        var id = $(this).data('id');
        $('#commonModalLabel').text('Edit Death Register');
        $('.save_button_span').text('Update Death Register');
            var url = `{!! route('death-registers.edit', ':id') !!}`.replace(':id', id);

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

</script>

<script>
    $(document).ready(function() {
        $(document).on('click', '.select-bed', function() {
            var old_selected = $('.select-bed');
            old_selected.removeClass('text-white');
            old_selected.addClass('btn-outline-success');
            old_selected.removeClass('btn-success');

            $('.save_and_confirm').removeClass('disabled');

            var bedName = $(this).data('bed-name');

            $('#bed_name').html(bedName);

            var bed = $(this).data('id');
            $('[name="bed_id"]').val(bed);
            $(this).addClass('btn-success');
            $(this).addClass('text-white');
            $(this).removeClass('btn-outline-success');
        });
    });


    $(document).on('click', '.save_and_confirm', function(event) {
        var error = 0;
        if ($('#commonModal').find('form').hasClass('bed')) {
            $('.error_bed_no_id').hide();

            if ($('[name="bed_id"]').val() == '') {
                toastr.error('Please select a bed first!', 'Error!');
                error = 1;
            }

            if ($('[name="type"]').val() == 'transfer') {
                if($('#current_bed').val()==''){
                    toastr.error('Please select Current bed first!', 'Error!');
                    error = 1;
                }
            }

            if (error == 0) {
                let formdata = new FormData($('#commonModal').find('form')[0]);

                var url = "{!! route('ipd-admissions-beds.create-step-2', ':id') !!}";
                var id  = $('#commonModal').find('form').data('id');
                url     = url.replace(':id',id);

                $.ajax({
                        url: url,
                        data: formdata,
                        processData: false,
                        contentType: false,
                        type: 'POST',
                        success: function(response) {
                            $('.save_button').show();
                            $('#commonModalLabel').text('Assign Bed');
                            $('.save_button').html('<i class="bx bx-save"></i> <span class="save_button_span">Save Bed</span>');
                            $('#commonModal').find('.modal-body').html('');
                            $('#commonModal').find('.modal-body').html(response);
                            $('#check_in_date_time').datetimepicker({
                                format: 'd/m/Y H:i A',
                            });
                        }
                    })
                    .fail(function(jqXHR, textStatus, errorThrown) {
                        console.log('AJAX request failed:', textStatus, errorThrown);
                        toastr.error('An error occurred during the request.', 'Error!');
                    });
            }
        }
    })


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

        var error = 0;

        if ($('#commonModal').find('form').hasClass('bed')) {
            $('.error_bed_no_id').hide();

            if ($('[name="bed_id"]').val() == '') {
                toastr.error('Please select a bed first!', 'Error!');
                error = 1;
            }

            if (error == 0) {
                let formdata = new FormData($('#commonModal').find('form')[0]);

                var url = "{!! route('ipd-admissions-beds.create-step-2', ':id') !!}";
                var id  = $('#commonModal').find('form').data('id');
                url     = url.replace(':id',id);

                $.ajax({
                        url: url,
                        data: formdata,
                        processData: false,
                        contentType: false,
                        type: 'POST',
                        success: function(response) {
                            $('#commonModalLabel').text('Assign Bed');
                            $('.save_button').html('<i class="bx bx-save"></i> <span class="save_button_span">Save Bed</span>');
                            $('#commonModal').find('.modal-body').html('');
                            $('#commonModal').find('.modal-body').html(response);
                            $('#check_in_date_time').datetimepicker({
                                format: 'd/m/Y H:i A',
                            });
                        }
                    })
                    .fail(function(jqXHR, textStatus, errorThrown) {
                        console.log('AJAX request failed:', textStatus, errorThrown);
                        toastr.error('An error occurred during the request.', 'Error!');
                    });
            }
        } else if ($('#commonModal').find('form').hasClass('store-bed')) {
            if ($('[name="bed_no_id"]').val() == '') {
                toastr.error('Please select a bed first!', 'Error!');
                error = 1;
            }

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

                $.ajax({
                        url: $('#add_bed').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('');

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

  $(document).on('change', '.billing-voucher-select', function(){
    if($(this).find(":selected").val() != '') {
        fetch_billing($(this).find(":selected").val());
    }
  });
  $(document).on('change', '.billing_date_picker, .from_date', function(){
    var from_date = $('.from_date').val()??'';
    var billing_date_picker = $('.billing_date_picker').val()??'';
    if(billing_date_picker != '' && from_date != '') {
        fetch_billing($('.billing-voucher-select').find(":selected").val());
    }
  });
</script>

<script>
    $(document).ready(function() {
        $('tr[data-bs-toggle="collapse"]').click(function() {
            var target = $(this).data('bs-target');
            var icon = $(this).find('i.bi');
            
            $(target).on('shown.bs.collapse', function () {
                icon.removeClass('bi-arrow-down-short').addClass('bi-arrow-up-short');
            });

            $(target).on('hidden.bs.collapse', function () {
                icon.removeClass('bi-arrow-up-short').addClass('bi-arrow-down-short');
            });
        });
    });


     /**************** edit patient ********************/
     $(document).on('click', '#edit_patient', function() {
        var id = $(this).data('id');
            $('#commonModalLabel').text('Edit Patient');
            $('.save_button_span').text('Update Patient');

            var url = `{!! route('patient-account-edit', ':id') !!}?redirect_back=ipd_admission`.replace(':id', id);

            $.ajax({
                url: url,
                success: function(data) {
                    $('#commonModal').find('.modal-body').html('');
                    $('#commonModal').find('.modal-body').html(data);
                    $('[name="date_of_birth"]').datepicker('destroy');

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