@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: 5;
    }

    .autocomplete .searchResult li{
        background: #F2F3F4;
        padding: 10px;
        margin-bottom: 1px;
        white-space: break-spaces;
    }

    .autocomplete .searchResult li:nth-child(even){
        background: #E5E7E9;
        color: black;
    }

    .autocomplete .searchResult li:hover{
        cursor: pointer;
        background: #CACFD2;
    }

    .add_btn {
        height: 40px;
        width: 40px;
        font-size:16px;
        border-radius: 0 3.5px 3.5px 0;
        padding: 0;
    }
    .select2-selection {
        height: 40px !important;
    }
</style>
<style>
.ck-editor__editable_inline {
    min-height: 100px;
}
</style>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/12.1.10/css/intlTelInput.css">
<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" />
<!-- Include Flatpickr CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.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">Edit IPD Admission</li>
            </ol>
        </nav>
    </div>
    <div class="ms-auto">
        <div class="btn-group">
            <a href="{{route('ipd-admissions.show', $data->id)}}" 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.update', $data->id )}}" method="post" enctype='multipart/form-data' style="padding: 0px 0px 0px 9px;">
            @csrf
            @method('put')
            <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">
                            <div>
                                <label class="form-label">Patient <span class="text-danger"><b>*</b></span></label>
                            </div>
                            <div class="input-group autocomplete">
                                <input type="text" name="" value="{{ ($patient->account_title->name ?? '') . ' ' . ($patient->name ?? '') . ' - (' . ($patient->code ?? '') . '), ' . ($patient->account_contact->gender->name ?? '') . ', ' . (age($patient->account_contact->date_of_birth) ?? '') . ' Years , ' . ($patient->account_contact->phone_no ?? '') }}" id="patient_id" class="patient-select form-control" placeholder="Search Patient">
                                <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="{{ $data->patient_id }}">
                            </div>
                            <span class="text-danger error_patient_id" style="display:none;">This field is required.</span>
                        </div>
                        {{-- <div class="col-md-6">
                            <div>
                                <label class="form-label">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">
                                    <option class="searchResult"></option>
                                    @foreach ($consultants as $consultant)
                                        <option selected value="{{ $consultant->consultants->id }}">{{ $consultant->consultants->account_title->name . ' ' . $consultant->consultants->name . ' - (' . $consultant->consultants->code . '), ' . $consultant->consultants->account_contact->phone_no }}</option>
                                    @endforeach
                                </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="{{ ($consultant->consultants->account_title->name ?? ''). ' ' . ($consultant->consultants->name ?? ''). ' - (' . ($consultant->consultants->code ?? ''). '), ' . ($consultant->consultants->account_contact->phone_no ?? '')}}"
                                {{isset($opdBooking->getDoctorAccount->id)?'readonly':''}}>
                                <ul class="searchResult"></ul>
                                <input type="hidden" name="doctor_id"
                                value="{{ $consultant->consultants->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" value="{{ old('admission_date_time', $data->admission_date_time) }}" class="form-control datepicker" 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="number" value="{{ old('ipd_file_no', $data->ipd_file_no) }}" class="form-control" name="ipd_file_no" placeholder="IPD CASE/FILE NUMBER">
                        </div>
                        <div class="col-md-6">
                            <label for="casualty" class="form-label">Casualty(Emergency)</label>
                            <select class="form-control" name="casualty">
                                <option {{ ($data->casualty == '0' || old('casualty') == '0') ? 'selected' : '' }} value="0">No</option>
                                <option {{ ($data->casualty == '1' || old('casualty') == '1') ? 'selected' : '' }} value="1">Yes</option>
                            </select>
                        </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 $account)
                                    <option {{ ($data->tpa_account_id == $account->id || old('tpa_account_id') == $account->id) ? 'selected' : '' }} value="{{ $account->id }}">{{ $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 {{ ($data->patient_source_id == $source->id || old('patient_source_id') == $source->id) ? 'selected' : '' }} value="{{ $source->id }}">{{ $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 {{ ($data->referral_partner_id == $partner_account->id || old('referral_partner_id') == $partner_account->id) ? 'selected' : '' }} value="{{ $partner_account->id }}">{{ $partner_account->name }}</option>
                                @endforeach
                            </select>
                        </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">Additional Details</h5>
                        <hr class="mb-2">

                        <div class="col-md-12">
                            <label for="referal_from" class="form-label">Referral from</label>
                            <input type="text" value="{{ old('referal_from', $data->referal_from) }}" class="form-control" name="referal_from" placeholder="Referral from: any Hospital or Nursing Home Name">
                        </div>
                        <div class="col-md-12">
                            <input type="hidden" name="symptom_id" value="{{ $data->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($data->symptom_id)){{ $symptoms->symptoms_title ?? '' }} - ({{ $symptoms->code ?? '' }})@endif" {{ isset($symptom->id) ? 'readonly' : '' }}>
                                <ul class="searchResult"></ul>
                                <input type="hidden" name="symptom_id" value="{{ $data->symptom_id ?? '' }}">
                            </div>
                        </div>

                        <div class="col-md-12">
                            <label for="claim_number" class="form-label">Claim Number</label>
                            <input type="text" value="{{ old('claim_number', $data->claim_number) }}" class="form-control" name="claim_number" placeholder="Claim Number">
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-12" style="padding: 0 0 0 18px;">
                <div class="card">
                    <div class="card-body g-3 row">
                        <div class="col-md-12">
                            <label for="note" class="form-label">Chief Complaint</label>
                            <textarea class="form-textarea ckeditor" name="chief_complaint" placeholder="Chief Complaint">{{ old('chief_complaint', $data->chief_complaint) }}</textarea>
                        </div>
                        <div class="col-md-12">
                            <label for="note" class="form-label">History Of Illness</label>
                            <textarea class="form-textarea ckeditor" name="history_of_illness" placeholder="History Of Illness">{{ old('history_of_illness', $data->history_of_illness) }}</textarea>
                        </div>

                        <div class="col-md-12">
                            <label for="other_investigations" class="form-label">Other investigations</label>
                            <textarea rows="2" class="form-textarea ckeditor" name="other_investigations" placeholder="Other investigations">{{ old('other_investigations', $data->other_investigations) }}</textarea>
                        </div>
                        <div class="col-md-12">
                            <label for="primary_diagnosis" class="form-label">Primary Diagnosis</label>
                            <textarea rows="2" class="form-textarea ckeditor" name="primary_diagnosis" placeholder="Primary Diagnosis" id="primary_diagnosis">{{ $data->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 ckeditor" name="secondary_diagnosis" placeholder="Secondary Diagnosis" id="secondary_diagnosis">{{ $data->secondary_diagnosis ?? '' }}</textarea>
                        </div>

                        <div class="col-md-12">
                            <label for="previous_medical_issue" class="form-label">Previous medical issue</label>
                            <textarea class="form-textarea ckeditor" name="previous_medical_issue" placeholder="Previous medical issue">{{ old('previous_medical_issue', $data->previous_medical_issue) }}</textarea>
                        </div>
                        <div class="col-md-12">
                            <label for="note" class="form-label">Treatment Type</label>
                            <textarea class="form-textarea ckeditor" name="treatment_type" placeholder="Treatment Type">{{ old('treatment_type', $data->treatment_type) }}</textarea>
                        </div>
                        <div class="col-md-12">
                            <label for="note" class="form-label">Treatment Details</label>
                            <textarea class="form-textarea ckeditor" name="treatment_details" placeholder="Treatment Details">{{ old('treatment_details', $data->treatment_details) }}</textarea>
                        </div>
                        <div class="col-md-12">
                            <label for="note" class="form-label">Note</label>
                            <textarea class="form-textarea ckeditor" name="note" placeholder="Note">{{ old('note', $data->note) }}</textarea>
                        </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> Update IPD Admission</button>
                          </div>
                        </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 src="https://cdn.ckeditor.com/ckeditor5/41.4.2/super-build/ckeditor.js"></script>

<script type="text/javascript">
document.querySelectorAll('.ckeditor').forEach((element) => {
    CKEDITOR.ClassicEditor
      .create( element, {
        toolbar: {
                    items: [
                        'fontSize', 'fontFamily', 'fontColor', 'fontBackgroundColor', 'highlight', '|',
                        'heading', '|',
                        'bold', 'italic', 'strikethrough', 'underline', 'subscript', 'superscript', 'removeFormat', '|',
                        'bulletedList', 'numberedList', 'todoList', '|',
                        'outdent', 'indent', '|',
                        'undo', 'redo',
                        'alignment', '|',
                        'blockQuote', 'insertTable'
                    ],
                    shouldNotGroupWhenFull: true
                },
                // Changing the language of the interface requires loading the language file using the <script> tag.
                // language: 'es',
                list: {
                    properties: {
                        styles: true,
                        startIndex: true,
                        reversed: true
                    }
                },
                // https://ckeditor.com/docs/ckeditor5/latest/features/headings.html#configuration
                heading: {
                    options: [
                        { model: 'paragraph', title: 'Paragraph', class: 'ck-heading_paragraph' },
                        { model: 'heading1', view: 'h1', title: 'Heading 1', class: 'ck-heading_heading1' },
                        { model: 'heading2', view: 'h2', title: 'Heading 2', class: 'ck-heading_heading2' },
                        { model: 'heading3', view: 'h3', title: 'Heading 3', class: 'ck-heading_heading3' },
                        { model: 'heading4', view: 'h4', title: 'Heading 4', class: 'ck-heading_heading4' },
                        { model: 'heading5', view: 'h5', title: 'Heading 5', class: 'ck-heading_heading5' },
                        { model: 'heading6', view: 'h6', title: 'Heading 6', class: 'ck-heading_heading6' }
                    ]
                },
                // https://ckeditor.com/docs/ckeditor5/latest/features/editor-placeholder.html#using-the-editor-configuration
                placeholder: '',
                // https://ckeditor.com/docs/ckeditor5/latest/features/font.html#configuring-the-font-family-feature
                fontFamily: {
                    options: [
                        'default',
                        'Arial, Helvetica, sans-serif',
                        'Courier New, Courier, monospace',
                        'Georgia, serif',
                        'Lucida Sans Unicode, Lucida Grande, sans-serif',
                        'Tahoma, Geneva, sans-serif',
                        'Times New Roman, Times, serif',
                        'Trebuchet MS, Helvetica, sans-serif',
                        'Verdana, Geneva, sans-serif'
                    ],
                    supportAllValues: true
                },
                // https://ckeditor.com/docs/ckeditor5/latest/features/font.html#configuring-the-font-size-feature
                fontSize: {
                    options: [ 10, 12, 14, 'default', 18, 20, 22 ],
                    supportAllValues: true
                },
                // Be careful with the setting below. It instructs CKEditor to accept ALL HTML markup.
                // https://ckeditor.com/docs/ckeditor5/latest/features/general-html-support.html#enabling-all-html-features
                htmlSupport: {
                    allow: [
                        {
                            name: /.*/,
                            attributes: true,
                            classes: true,
                            styles: true
                        }
                    ]
                },
                // Be careful with enabling previews
                // https://ckeditor.com/docs/ckeditor5/latest/features/html-embed.html#content-previews
                htmlEmbed: {
                    showPreviews: false
                },
                // https://ckeditor.com/docs/ckeditor5/latest/features/link.html#custom-link-attributes-decorators
                link: {
                    decorators: {
                        addTargetToExternalLinks: true,
                        defaultProtocol: 'https://',
                        toggleDownloadable: {
                            mode: 'manual',
                            label: 'Downloadable',
                            attributes: {
                                download: 'file'
                            }
                        }
                    }
                },
                // https://ckeditor.com/docs/ckeditor5/latest/features/mentions.html#configuration
                mention: {
                    feeds: [
                        {
                            marker: '@',
                            feed: [
                                '@apple', '@bears', '@brownie', '@cake', '@cake', '@candy', '@canes', '@chocolate', '@cookie', '@cotton', '@cream',
                                '@cupcake', '@danish', '@donut', '@dragée', '@fruitcake', '@gingerbread', '@gummi', '@ice', '@jelly-o',
                                '@liquorice', '@macaroon', '@marzipan', '@oat', '@pie', '@plum', '@pudding', '@sesame', '@snaps', '@soufflé',
                                '@sugar', '@sweet', '@topping', '@wafer'
                            ],
                            minimumCharacters: 1
                        }
                    ]
                },
                // The "superbuild" contains more premium features that require additional configuration, disable them below.
                // Do not turn them on unless you read the documentation and know how to configure them and setup the editor.
                removePlugins: [
                    // These two are commercial, but you can try them out without registering to a trial.
                    // 'ExportPdf',
                    // 'ExportWord',
                    'AIAssistant',
                    'CKBox',
                    'CKFinder',
                    'EasyImage',
                    // This sample uses the Base64UploadAdapter to handle image uploads as it requires no configuration.
                    // https://ckeditor.com/docs/ckeditor5/latest/features/images/image-upload/base64-upload-adapter.html
                    // Storing images as Base64 is usually a very bad idea.
                    // Replace it on production website with other solutions:
                    // https://ckeditor.com/docs/ckeditor5/latest/features/images/image-upload/image-upload.html
                    // 'Base64UploadAdapter',
                    'MultiLevelList',
                    'RealTimeCollaborativeComments',
                    'RealTimeCollaborativeTrackChanges',
                    'RealTimeCollaborativeRevisionHistory',
                    'PresenceList',
                    'Comments',
                    'TrackChanges',
                    'TrackChangesData',
                    'RevisionHistory',
                    'Pagination',
                    'WProofreader',
                    // Careful, with the Mathtype plugin CKEditor will not load when loading this sample
                    // from a local file system (file://) - load this site via HTTP server if you enable MathType.
                    'MathType',
                    // The following features are part of the Productivity Pack and require additional license.
                    'SlashCommand',
                    'Template',
                    'DocumentOutline',
                    'FormatPainter',
                    'TableOfContents',
                    'PasteFromOfficeEnhanced',
                    'CaseChange'
                ]
      })
      .then( newEditor => {
          editor = newEditor;
      })
      .catch( error => {
          console.error( error );
      })
  });
      $(".ck-dropdown").find(`[data-cke-tooltip-text='Insert media']`).css("display", "none");


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

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

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

        if ($('#commonModal').find('form').hasClass('create_patient')) {
            if ($('#phone_no').val().trim() != '') {
                var dailcode_title = $('.phone_no_col .selected-flag').attr('title');
                var dailcode_array = dailcode_title.split("+");
                $('input[name="phone_no"]').val("+" + dailcode_array[1] + $('#phone_no').val());
            }

            if ($('#whatsapp_no').val().trim() != '') {
                var dailcode_title = $('.whatsapp_no_col .selected-flag').attr('title');
                var dailcode_array = dailcode_title.split("+");
                $('input[name="whatsapp_no"]').val("+" + dailcode_array[1] + $('#whatsapp_no').val());
            }

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

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

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

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

                            // hide modal
                            $('#commonModal').modal('hide');
                            $('#commonModal').find('.modal-body').html('');
                        } else {
                            toastr.error(response.message, 'Error!');
                        }
                    }
                })
                .fail(function(jqXHR, textStatus, errorThrown) {
                    console.log('AJAX request failed:', textStatus, errorThrown);
                    toastr.error('An error occurred during the request.', 'Error!');
                });
            }
        }
        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
                            $('.doctor-select').append(`<option value="${response.data.id}" selected>${response.data.name}</option>`);
                            $('.doctor-select').trigger('change');

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

            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 {
            $('.error_patient_id').hide();
            $('.error_doctor_id').hide();
            $('.error_admission_date').hide();
            var error = 0;

            if ($('input[name="patient_id"]').val().trim() == '') {
              $('.error_patient_id').show();
              error = 1;
            }
            if ($('[name="doctor_id"]').val() == '') {
              $('.error_doctor_id').show();
              error = 1;
            }
            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) {
        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(){
        $('#check_out_date').flatpickr({
            enableTime: true,
        });

        $('#admission_date').flatpickr({
            enableTime: true,
        });

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

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

     /************ 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');
                    });
                }
            });
        }
    })

     /************ 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');
                    });
                }
            });
        }
    });

    /*********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 ************/
    $(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();
        }
    });
</script>
@endsection
