@extends('layouts.app')
@section('title','IPD Admission')
@section('pages')

<style type="text/css">
    .clear{
        clear:both;
        margin-top: 20px;
    }

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

    .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" 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" type="text/css" href="{{ asset('admin/plugins/datepicker/less/datepicker.less') }}">
<link href="{{ asset('admin/plugins/datepicker/css/datepicker.css') }}" rel="stylesheet" />

<!-- <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/css/bootstrap-datetimepicker.css" rel="stylesheet"> -->

<!-- <link rel="stylesheet" type="text/css" href="{{ asset('admin\plugins\datetimepickr_new\jquery.datetimepicker.min.css') }}"> -->

<!--breadcrumb-->
<div class="page-breadcrumb d-flex align-items-center mb-3 px-3 px-md-0">
    <div class="breadcrumb-title pe-3"><i class="bi bi-list"></i> IPD Admission</div>
    <div class="ps-3">
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb mb-0 p-0">

                <li class="breadcrumb-item active" aria-current="page">Add New IPD Admission</li>
            </ol>
        </nav>
    </div>
    <div class="ms-auto">
        <div class="btn-group">
            <a href="{{route('ipd-admissions.index')}}" class="btn btn-info"><i class="bx bx-arrow-back ms-0 me-1"></i>Back</a>
        </div>
    </div>
</div>
<!--end breadcrumb-->

<div class="row auto">
    <div class="col-xl-12 mx-auto">
        <form class="row auto-width mt-0 ipd-admission-form" action="{{ route('ipd-admissions.store')}}" method="post" enctype='multipart/form-data' style="padding: 0px 0px 0px 9px;">
            @csrf
            <div class="card style_table">
                <div class="card-body pt-2 ps-3" style="border-radius:0px;">
                    <div class="row align-items-center">
                        <div class="col-md-6">
                            <input type="hidden" name="opd_booking_id" value="{{$opdBooking->id ?? ''}}">
                            <div>
                                <label class="form-label">Patient <span class="text-danger"><b>*</b></span></label>
                            </div>
                            <div class="input-group autocomplete">
                                <input type="text" name="" id="patient_id" class="patient-select form-control" placeholder="Search Patient" value="@if(isset($opdBooking->getPatient->id)){{$opdBooking->getPatient->account_title->name ?? ''}} {{$opdBooking->getPatient->name??''}} - ({{$opdBooking->getPatient->code??''}})@endif"
                                {{isset($opdBooking->getPatient->id)?'readonly':''}}>
                                <ul class="searchResult"></ul>
                                <div class="input-group-append" style="margin: auto 10px auto 0;">
                                    <button class="btn btn-secondary add_btn" id="create_patient" type="button" data-bs-toggle="modal" data-bs-target="#commonModal">+</button>
                                    <button style="height: 40px" class="btn btn-primary edit_btn" id="edit_patient" type="button" data-bs-toggle="modal" data-bs-target="#commonModal"><i class="bi bi-pencil-square"></i></button>
                                </div>
                                <input type="hidden" name="patient_id" value="{{$opdBooking->getPatient->id ?? ''}}">
                            </div>
                            <span class="text-danger error_patient_id" style="display:none;">This field is required.</span>
                        </div>

                        {{-- <div class="col-md-6">
                            <div>
                                <label class="form-label">Consultant Doctor <span class="text-danger"><b>*</b></span></label>
                            </div>
                            <div class="input-group autocomplete">
                                <select class="form-control doctor-select multiple-select" id="doctor_id" name="doctor_id[]" multiple="multiple"
                                {{isset($opdBooking->getDoctorAccount->id)?'disable':''}}>
                                    @if(isset($opdBooking->getDoctorAccount->id))
                                    <option selected value="{{$opdBooking->getDoctorAccount->id??''}}"> {{$opdBooking->getDoctorAccount->account_title->name ?? ''}}
                                            {{$opdBooking->getDoctorAccount->name ?? ''}} - ({{$opdBooking->getDoctorAccount->code??''}}),
                                            {{$opdBooking->getDoctorAccount->account_contact->gender->name ?? ''}},
                                            {{ isset($opdBooking->getPatient->account_contact->phone_no) ?'Ph:'. $opdBooking->getPatient->account_contact->phone_no:''}}
                                             </option>
                                    @endif
                                </select>
                                <div class="input-group-append" style="margin: auto 10px auto 0;">
                                    <button class="btn btn-secondary add_btn" id="create_doctor" type="button" data-bs-toggle="modal" data-bs-target="#commonModal"> + </button>
                                </div>
                            </div>
                            <span class="text-danger error_doctor_id" style="display:none;">This field is required.</span>
                        </div> --}}
                        <div class="col-md-6">
                            <div>
                                <label class="form-label">Consultant Doctor <span class="text-danger"><b>*</b></span></label>
                            </div>
                            <div class="input-group autocomplete">
                                <input type="text" name="" id="doctor_id" class="doctor-select form-control" placeholder="Search Doctor" autocomplete="off"
                                value="@if(isset($opdBooking->getDoctorAccount->id)){{$opdBooking->getDoctorAccount->account_title->name ?? ''}} {{$opdBooking->getDoctorAccount->name??''}} - ({{$opdBooking->getDoctorAccount->code??''}})@endif"
                                {{isset($opdBooking->getDoctorAccount->id)?'readonly':''}}>
                                <ul class="searchResult"></ul>
                                <input type="hidden" name="doctor_id" value="{{$opdBooking->getDoctorAccount->id??''}}">
                                <div class="input-group-append" style="margin: auto 10px auto 0;">
                                    <button class="btn btn-secondary add_btn" id="create_doctor" type="button" data-bs-toggle="modal" data-bs-target="#commonModal"> + </button>
                                    <button style="height: 40px" class="btn btn-primary edit_btn" id="edit_doctor" type="button" data-bs-toggle="modal" data-bs-target="#commonModal"><i class="bi bi-pencil-square"></i></button>
                                </div>
                            </div>
                            <span class="text-danger error_doctor_id" style="display:none;">This field is required.</span>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-md-6" style="padding: 0 0 0 9px;">
                <div class="card">
                    <div class="card-body g-3 row">

                        <h5 class="mb-0">IPD Admission</h5>
                        <hr class="mb-2">

                        <div class="col-md-6">
                            <label for="admission_date" class="form-label">Admission Date
                                <span class="text-danger"><b>*</b></span>
                            </label>
                            <input type="text" class="form-control datepicker" value="{{ old('admission_date_time', date('Y/m/d h:i A')) }}" id="admission_date" name="admission_date_time" placeholder="Admission Date"aria-describedby="inputGroupPrepend">
                            <span class="text-danger error_admission_date" style="display:none;">This field is required.</span>
                        </div>
                        <div class="col-md-6">
                            <label for="ipd_file_no" class="form-label">IPD CASE/FILE NUMBER</label>
                            <input type="text" class="form-control" value="{{ old('ipd_file_no') }}" id="ipd_file_no" name="ipd_file_no" placeholder="IPD CASE/FILE NUMBER">
                            <span class="text-danger error_ipd_file_no" style="display:none;">This field is required.</span>
                        </div>
                        <div class="col-md-6">
                            <label for="casualty" class="form-label">Casualty(Emergency)</label>
                            <select class="form-control" name="casualty">
                                <option {{ (old('casualty') == 'no' ? 'selected' : '') }} value="no">No</option>
                                <option {{ (old('casualty') == 'yes' ? 'selected' : '') }} value="yes">Yes</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <div>
                                <label for="tpa_account_id" class="form-label">TPA/Corporate Name</label>
                            </div>
                            <div class="input-group">
                                <select class="form-control tpa_account_id" name="tpa_account_id">
                                    <option value="">Select</option>
                                    @foreach($accounts as $tpa_account)
                                        <option value="{{ $tpa_account->id }}" {{ (old('tpa_account_id') == $tpa_account->id ? 'selected' : '') }}>{{ $tpa_account->name }}</option>
                                    @endforeach
                                </select>
                                <div class="input-group-append">
                                    <a href="{{route('accounts.create')}}?redirect_back=true&type=TPA/Corporates"  style="font-size: 16px" class="btn btn-secondary">+</a>
                                </div>
                            </div>
                            <span class="text-danger error_account_id" style="display:none;">This field is required.</span>
                        </div>
                       
                       
                        {{-- <div class="col-md-6">
                            <label for="tpa_account_id" class="form-label">TPA/Corporate Name</label>
                            <select class="form-control tpa_account_id" name="tpa_account_id">
                                <option value="">Select</option>
                                @foreach($accounts as $tpa_account)
                                    <option value="{{ $tpa_account->id }}" {{ (old('tpa_account_id') == $tpa_account->id ? 'selected' : '') }}>{{ $tpa_account->name }}</option>
                                @endforeach
                            </select>
                        </div> --}}
                        
                        <div class="col-md-6">
                            <label for="patient_source_id" class="form-label">Patient source</label>
                            <select class="form-control patient_source_id" name="patient_source_id">
                                @foreach($sources as $source)
                                    <option value="{{ $source->id }}" {{ (old('patient_source_id') == $source->id ? 'selected' : '') }}>{{ $source->enquiry_source_name }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label for="referral_partner_id" class="form-label">Referral partner</label>
                            <select class="form-control" name="referral_partner_id">
                                <option value="">Select</option>
                                @foreach($refferal_accounts as $partner_account)
                                    <option value="{{ $partner_account->id }}" {{ (old('referral_partner_id') == $partner_account->id ? 'selected' : '') }}>{{ $partner_account->name }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col-md-12">
                            <label for="note" class="form-label">Chief Complaint</label>
                            <textarea class="form-textarea" name="chief_complaint" placeholder="Chief Complaint">{{ old('chief_complaint') }}</textarea>
                        </div>
                        <div class="col-md-12">
                            <label for="referal_from" class="form-label">Referral from</label>
                            <input type="text" class="form-control" value="{{ old('referal_from') }}" name="referal_from" placeholder="Referral from: any Hospital or Nursing Home Name">
                        </div>
                        <div class="col-md-12">
                            <label for="note" class="form-label">History Of Illness</label>
                            <textarea class="form-textarea" name="history_of_illness" placeholder="History Of Illness">{{ old('history_of_illness') }}</textarea>
                        </div>
                       
                        {{-- <div class="card">
                   <div class="card-body g-3 row">
                        <h5 class="mb-0">Bed Details</h5>
                        <hr class="mb-2">
                        <div class="col-md-12">
                            <div>
                                <label for="bed_group_id" class="form-label">Bed Group</label>
                            </div>
                            <div class="input-group">
                                <select class="bed_group_id form-control" name="bed_group_id">
                                    <option value="">-Select-</option>
                                    @foreach($bed_groups as $bed_group)
                                <option value="{{ $bed_group->id }}" {{ (old('bed_group_id') == $bed_group->id ? 'selected' : '') }}>{{ $bed_group->name }}
                                </option>
                                @endforeach
                                </select>
                                <div class="input-group-append">
                                    <a href="{{route('bed-group.index')}}" style="font-size: 16px" class="btn btn-secondary" target="_blank">+</a>
                                    <div class="input-group-append" style="margin: auto 10px auto 0;">
                                    </div>
                                </div>
                            </div>
                            @if ($errors->has('account_tyxpe_id'))
                                <span class="text-danger">{{ $errors->first('bed_group_id') }}</span>
                            @endif
                            <span class="text-danger error_bed_group_id" style="display:none;">This field is required.</span>
                        </div>
                        <div class="col-md-12">
                            <div><label for="bed_group_id" class="form-label">Bed No</label></div>
                            <div class="input-group">
                                <select class="form-control bed_no_id" name="bed_no_id">
                                    <option value="">-- Please select Bed Group First -- </option>
                                </select>
                                <div class="input-group-append">
                                    <a href="{{route('beds.index')}}" class="btn btn-secondary" style="font-size:16px" target="_blank" >+</a>
                                </div>
                            </div>
                            @if ($errors->has('account_tyxpe_id'))
                                <span class="text-danger">{{ $errors->first('bed_no_id') }}</span>
                            @endif
                            <span class="text-danger error_bed_no_id" style="display:none;">This field is required.</span>
                        </div>


                    </div>
                </div>--}}
                    </div>
                    <div class="card-body g-3 row">
                        <div class="col-12" align="center">
                            <div class="d-grid gap-2 with-100">
                              <button class="btn btn-primary save_button" type="submit"><i class="bx bx-save"></i> Create IPD Admission</button>
                          </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-6" style="padding: 0 0 0 18px;">

                {{-- <div class="card">
                    <div class="card-body g-3 row">
                        <h5 class="mb-0">Bed Details</h5>
                        <hr class="mb-2">
                    </div>
                </div> --}}

                <div class="card">
                    <div class="card-body g-3 row">
                        <h5 class="mb-0">Diagnosis </h5>
                        <hr class="mb-2">
                        <div class="col-md-12">
                            <input type="hidden" name="symptom_id" value="{{ $symptom->id ?? '' }}">
                            <div>
                                <label class="form-label">Diagnosis Title</label>
                            </div>
                            <div class="input-group autocomplete">
                                <input type="text" id="symptom_id" class="symptoms-select form-control" placeholder="Search Symptom Title" value="@if(isset($symptom->id)){{ $symptom->symptoms_title ?? '' }} - {{ $symptom->code ?? '' }}@endif" {{ isset($symptom->id) ? 'readonly' : '' }}>
                                <ul class="searchResult"></ul>
                                <input type="hidden" name="symptom_id" value="{{ $symptom->id ?? '' }}">
                            </div>
                        </div>

                        <div class="col-md-12">
                            <label for="primary_diagnosis" class="form-label">Primary Diagnosis</label>
                            <textarea rows="2" class="form-textarea" name="primary_diagnosis" placeholder="Primary Diagnosis" id="primary_diagnosis"></textarea>
                        </div>

                        <div class="col-md-12">
                            <label for="secondary_diagnosis" class="form-label">Secondary Diagnosis</label>
                            <textarea rows="2" class="form-textarea" name="secondary_diagnosis" placeholder="Secondary Diagnosis" id="secondary_diagnosis"></textarea>
                        </div>
              
                        <div class="col-md-12">
                            <label for="previous_medical_issue" class="form-label">Previous medical issue</label>
                            <textarea rows="2" class="form-textarea" name="previous_medical_issue" placeholder="Previous medical issue">{{ old('previous_medical_issue') }}</textarea>
                        </div>
                        <div class="col-md-12">
                            <label for="note" class="form-label">Note</label>
                            <textarea rows="2" class="form-textarea" name="note" placeholder="Note">{{ old('note') }}</textarea>
                        </div>

                        <div class="col-md-12">
                            <label for="other_investigations" class="form-label">Other investigations</label>
                            <textarea rows="2" class="form-textarea" name="other_investigations" placeholder="Other investigations">{{ old('other_investigations') }}</textarea>
                        </div>
                    </div>

                </div>
            </div>
        </form>

    </div>
</div>
@endsection

@section('js')
<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>
<script type="text/javascript" src="{{ asset('admin/plugins/datepicker/js/bootstrap-datepicker.js') }}"></script>

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

<!-- <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment-with-locales.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/js/bootstrap-datetimepicker.min.js"></script> -->

<!-- //working -->
<!-- <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" />

<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>
    $(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_patient')) {
            $('.error_name').hide();
            $('.error_email').hide();
            $('.error_phone').hide();
            $('.error_country_id').hide();
            $('.error_date_of_birth').hide();
            var error = 0;
            if ($('#phone_no').val().trim() != '') {
                var dailcode_title = $('.phone_no_col .selected-flag').attr('title');
                var dailcode_array = dailcode_title.split("+");
                $('input[name="phone_no"]').val("+" + dailcode_array[1] + $('#phone_no').val());
            }
            if ($('#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());
            }
            $('#year').trigger("change")

            const yearInput = $('#age_years').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 ($('#age_years').val() == '') {
                $('.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 ($('input[name="name"]').val().trim() == '') {
              $('.error_name').show();
              error = 1;
              setTimeout(function () {
                $('.error_name').hide();
                }, 3000);
            }
            if ($('[name="country_id"]').val().trim() == '') {
              $('.error_country_id').show();
              error = 1;
            }
            if ($('input[name="phone_no"]').val().trim() == '') {
              $('.error_phone').show();
              error = 1;
              setTimeout(function () {
                    $('.error_phone').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;
            }
            if ($('input[name="relation_phone"]').val().trim() == '') {
              $('.error_relation_phone').show();
              error = 1;
              setTimeout(function () {
                    $('.error_relation_phone').hide();
                }, 3000);
            }

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

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

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

                $.ajax({
                    url: $('#create_patient_form').attr('action'),
                    data: formdata,
                    processData: false,
                    contentType: false,
                    type: 'POST',
                    success: function (response) {
                        if (response.success === true) {
                            toastr.success(response.message, 'Success.');
                            // append new category to selection
                            $('[name="patient_id"]').val(response.data.id);
                            $('#patient_id').val(response.data.name);
                            $('#edit_patient').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('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());
            }

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

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

            }

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

            }

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

            }
            if ($('#age_years').val() == '') {
                $('.error_date_of_birth').show();
                error = 1;
                setTimeout(function () {
                    $('.error_date_of_birth').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
                            $('[name="patient_id"]').val(response.data.id);
                            $('#patient_id').val(response.data.name);

                            // hide modal
                            $('#commonModal').modal('hide');
                            $('#commonModal').find('.modal-body').html('');
                        } else {
                            toastr.error(response.message, 'Error!');
                        }
                    }
                })
                .fail(function(jqXHR, textStatus, errorThrown) {
                    console.log('AJAX request failed:', textStatus, errorThrown);
                    toastr.error('An error occurred during the request.', 'Error!');
                });
            }
        }
        else if ($('#commonModal').find('form').hasClass('create_doctor')) {
            if ($('#phone_no').val().trim() != '') {
                var dailcode_title = $('.phone_no_col .selected-flag').attr('title');
                var dailcode_array = dailcode_title.split("+");
                $('input[name="phone_no"]').val("+" + dailcode_array[1] + $('#phone_no').val());
            }

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

            if ($('input[name="name"]').val().trim() == '') {
              $('.error_name').show();
              error = 1;
            }
            if ($('[name="country_id"]').val().trim() == '') {
              $('.error_country_id').show();
              error = 1;
            }

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

                $.ajax({
                    url: $('#create_doctor_form').attr('action'),
                    data: formdata,
                    processData: false,
                    contentType: false,
                    type: 'POST',
                    success: function (response) {
                        if (response.success === true) {
                            toastr.success(response.message, 'Success.');
                            // append new category to selection
                            $('[name="doctor_id"]').val(response.data.id);
                            $('#doctor_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().trim() == '') {
                $('.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('');
                            setTimeout(function() {
                                $('#create_patient').trigger('click');
                                CitySelected(response.data.id);
                            }, 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('');
            });
            }
            error = 1;
        }
        else if ($('#commonModal').find('form').hasClass('update_doctor_details')) {
            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());
            }



            $('.error_name').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 (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!');
                });
            }
        }
        else {
            $('.error_patient_id').hide();
            $('.error_doctor_id').hide();
            $('.error_admission_date').hide();
            $('.error_ipd_file_no').hide();

            var error = 0;

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

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

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

            // }
            if ($('[name="admission_date_time"]').val().trim() == '') {
              $('.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
        });
    }

    $(document).ready(function(){
        $('#admission_date').flatpickr({
            enableTime: true,
            dateFormat: "Y-m-d H:i",
            defaultDate: "now",
            clickOpens: true,
            onReady: function (selectedDates, dateStr, instance) {
                instance.setDate(new Date(), true);
            },
            onClose: function (selectedDates, dateStr, instance) {
                instance.close();
            }
        });

        // $('#admission_date').datetimepicker({
        //     // defaultDate: new Date(),
        //     format: 'YYYY-MM-DD HH:mm',
        // });


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

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

                $(this).val(ui.item.name + ' - (' + ui.item.code + ')' + gender + age + phone_no + "");
                $('[name="patient_id"]').val(ui.item.id);
                return false;
            }
        }).data("ui-autocomplete")._renderItem = function(ul, item) {
            var age      = item.date_of_birth != null ? ', ' + getAge(item.date_of_birth) + ' Years' : '';
            var gender   = item.gender != null ? ', ' + item.gender : '';
            var phone_no = item.phone_no != null ? ', ' + item.phone_no : '';

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

        // old doctor
        // $(".doctor-select").select2({
        //     ajax: {
        //         url: "{{ route('billings-search-doctors') }}",
        //         type: 'POST',
        //         dataType: 'json',
        //         data: function (params) {
        //             return {
        //                 search_text: params.term
        //             };
        //         },
        //         processResults: function (data) {
        //             if (data.error) {
        //                 $('[name="doctor_id"]').val('');
        //                 return { results: [] };
        //             }

        //             return {
        //                 results: $.map(data.result, function (item) {
        //                     var age = item.date_of_birth != null ? ', ' + getAge(item.date_of_birth) + ' yrs' : '';
        //                     var gender = item.gender != null ? ', ' + item.gender : '';
        //                     var phone_no = item.phone_no != null ? ', ' + item.phone_no : '';

        //                     return {
        //                         id: item.id,
        //                         text: item.name + ' - (' + item.code + ')' + gender + age + phone_no
        //                     };
        //                 })
        //             };
        //         }
        //     },
        //     minimumInputLength: 2,
        //     templateSelection: function (selectedData) {
        //         return selectedData.text;
        //     }
        // });

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

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

                $(this).val(ui.item.name + ' - (' + ui.item.code + ')' + gender + age + phone_no + "");
                $('[name="doctor_id"]').val(ui.item.id);
                return false;
            }
        }).data("ui-autocomplete")._renderItem = function(ul, item) {
            var age      = item.date_of_birth != null ? ', ' + getAge(item.date_of_birth) + ' Years' : '';
            var gender   = item.gender != null ? ', ' + item.gender : '';
            var phone_no = item.phone_no != null ? ', ' + item.phone_no : '';

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

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

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

    /**************** edit patient ********************/
    $(document).on('click', '#edit_patient', function() {
        var customerName = $('[name="patient_id"]').val();

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

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

            var url = `{!! route('patient-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');
                    });
                    reinitializeTelInput();
                }
            });
        }
    });

    /**************** create patient ********************/
    $(document).on('click', '#create_patient', function(){
        $('#commonModalLabel').text('Add New Patient');
        $('.save_button_span').text('Save Patient');
        $.ajax({
          url:"{!! route('patient-account-create') !!}?redirect_back=ipd_admission",
          success:function(data){
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);
            $( function() {
                $('#date_of_birth').datepicker();
            });
            reinitializeTelInput();
          }
        })
    })

    /**************** 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() {
        var customerName = $('[name="doctor_id"]').val();

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

            $('#commonModalLabel').text('Edit Patient');
            $('.save_button_span').text('Update Patient');
            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);
            }
        })
    })


    $(document).on('change', '.symptom_type', function(){
        $.ajax({
            type: 'POST',
            url: "{!! route('ipd-admissions.get-symptoms-title') !!}",
            data: {symptom_type: $('.symptom_type').val()},
            success: function (response) {
                if (response.success === true) {
                    $('.symptom_title').html('');
                    $('.symptoms_description').val('');
                    $('.symptom_title').append(response.data);
                    getSymptomTitle();
                } else {
                    toastr.error(response.message, 'Error!');
                }
            }
        });
    });

    $(document).on('change', '.symptom_title', function(){
        getSymptomTitle();
    });

    function getSymptomTitle() {
        $.ajax({
            type: 'POST',
            url: "{!! route('ipd-admissions.get-symptoms-description') !!}",
            data: {symptom_title: $('.symptom_title').val()},
            success: function (response) {
                if (response.success === true) {
                    $('.symptoms_description').val('');
                    $('.symptoms_description').val(response.data);
                } else {
                    toastr.error(response.message, 'Error!');
                }
            }
        });
    }

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

                $.ajax({
                    url: "{{ route('search-symptoms') }}",
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        search_text: request.term
                    },
                    success: function(json) {
                        if (json.error) {
                            $('[name="symptom_id"]').val('');
                            return false;
                        }
                        response($.map(json.result, function(item) {
                            return {
                                id: item.id,
                                name: item.symptoms_title,
                                code: item.code
                            };
                        }));
                    }
                });
            },
            select: function(event, ui) {
                event.preventDefault();

                var symptoms_title = ui.item.name ? ui.item.name : '';
                var code           = ui.item.code ? ' - (' + ui.item.code + ')' : '';

                $(this).val(symptoms_title + code);
                $('[name="symptom_id"]').val(ui.item.id);
                return false;
            }
        }).data("ui-autocomplete")._renderItem = function(ul, item) {
            var symptoms_title = item.name ? item.name : '';
            var code           = item.code ? ' - (' + item.code + ')' : '';

            return $("<li>")
                .append("<a>" + symptoms_title +  code + "</a>")
                .appendTo(ul);
        };
    });

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

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

                          $(this).Toastshow('success',ErroMsg);
                          fetch_cart();
                      }else{
                          var ErroMsg = $(this).printErrorMsg(response.message);
                          $(this).Toastshow('error',ErroMsg);
                      }
                  },
                  error: function (data) {
                    console.log("error ",data);
                  }
              });
              }
          });
    });

    function getAge(birthdate) {
        if (birthdate != '' && birthdate != null && birthdate != undefined) {
            var birthdateObj = new Date(birthdate);
            var now = new Date();
            var age = now.getFullYear() - birthdateObj.getFullYear();

            // Adjust age if birthday hasn't occurred this year yet
            if (now.getMonth() < birthdateObj.getMonth() || (now.getMonth() === birthdateObj.getMonth() && now.getDate() < birthdateObj.getDate())) {
                age--;
            }
            return age;
        }
    };

    /******* Disabling & Enabling edit button of patient ************/
    $(document).ready(function() {
        function toggleEditButton() {
            var patientId = $('[name="patient_id"]').val();
            $('#edit_patient').prop('disabled', patientId.trim() === "");
        }

        toggleEditButton();

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

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

        // $('#edit_patient').on('click', function() {
        //     var patientName = $('#patient_id').val().trim();

        //     if (patientName === "") {
        //         $('.error_patient_id').show();
        //     } else {
        //         $('.error_patient_id').hide();

        //         $('#commonModalLabel').text('Edit Customer');
        //         $('.save_button_span').text('Update Customer');
        //         var id = $('[name="patient_id"]').val();
        //         var url = `{!! route('patient-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_patient').prop('disabled', false);
        }

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

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

        toggleEditButton();

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

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

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

            if (patientName === "") {
                $('.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();
        }
    });
    /******* Dependent Dropdown of Beds  ************/
    $(document).on('change', '.bed_group_id', function(){
        $.ajax({
            type: 'POST',
            url: "{{ route('ipd-admissions.get-beds') }}",
            data: {bed_group_id: $(this).val()},
            success: function (response) {
                if (response.success) {
                    $('.bed_no_id').html(response.data);
                } else {
                    toastr.error('Failed to retrieve beds data.', 'Error!');
                }
            },
            error: function (xhr, status, error) {
                toastr.error('Error occurred while fetching data.', 'Error!');
            }
        });
    });

    $(document).on('change', '.bed_no_id', function(){
        getBeds();
    });
</script>

@endsection
