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

    .flatpickr-calendar {
        width: 308px !important;
        font-size: 12px !important;
    }
    .form-label {
        font-weight: bold;
        font-size: 16px;
    }
</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" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.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" />

<!--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 Patient Discharged</div>
    <div class="ms-auto">
        <div class="btn-group">
            <a href="{!! route('ipd-admissions.show', $admission->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">
            <div class="row">
            <div class="col-12 " style="background-color: white;"> 
                        <div class="row " style="padding-top: 4px; padding-bottom: 4px;border-bottom: 1px solid #565656;
                        border-top: 1px solid #565656 ; background-color: white; margin-top: 10px;margin-bottom: 10px;">
                            <div class="col-6 border-right " >
                                <table class="table table-borderless mb-1 w-100 table-line-height1-2">
                                    <tbody>
                                        <tr class="fw-bold">
                                            <td style="width:20%">Patient Name</td>
                                            <td>:</td>
                                            <td colspan="3" style="padding-left: 2px">
                                                {{ $admission->contacts->name . ' - (' . $admission->contacts->code . ')' }}
                                            </td>
                                        </tr>
                                        <tr class="fw-bold">
                                            <td style="width:30%">Admission No</td>
                                            <td>:</td>
                                            <td colspan="3" style="padding-left: 2px">
                                                {!! $admission->ipd_admission_no !!}
                                            </td>
                                        </tr>
                                        <tr>
                                            <td width="35%">Admission Date</td>
                                            <td>:</td>
                                            <td colspan="3" style="padding-left: 2px">
                                                {!! formatedDateTime($admission->admission_date_time) !!}
                                            </td>
                                        </tr>
                                       <tr class="">
                                            <td width="35%">IPD CASE/FILE NUMBER</td>
                                            <td>:</td>
                                            <td colspan="3" style="padding-left: 2px"> {{ $admission->ipd_file_no ?? 'N/A' }}</td>
                                        </tr>
                                         <tr>
                                            <td>Date of Birth</td>
                                            <td>:</td>
                                            <td style="padding-left: 2px">
                                              {{ formatedDate($admission->contacts->account_contact->date_of_birth) }}
                                            </td>
                                        </tr>
                                        <tr>
                                            <td>Consultant Name</td>
                                            <td>:</td>
                                            <td style="padding-left: 2px">
                                              {{ $admission->consultantHistory->consultants->name . ' - (' . $admission->consultantHistory->consultants->code . ')' }}
                                            </td>
                                        </tr>  
                                    </tbody>
                                </table>
                            </div>
                            <div class="col-6 line-height1-2 ">
                            <table class="table table-borderless mb-1 w-100 table-line-height1-2" style="margin-left: -3.9px;">
                                    <tbody>
                                        <tr class="fw-bold">
                                            <td width="35%">Marital Status</td>
                                            <td>:</td>
                                            <td colspan="3" style="padding-left: 2px"> {{ $admission->contacts->account_contact->marital_status ?? 'N/A' }}</td>
                                        </tr>
                                        <tr>
                                            <td>Gender</td>
                                            <td>:</td>
                                            <td style="padding-left: 2px">{{ $admission->contacts->account_contact->gender->name ?? '' }}</td>
                                        </tr>
                                        <tr>
                                            <td>Age</td>
                                            <td>:</td>
                                            <td style="padding-left: 2px">{{ age($admission->contacts->account_contact->date_of_birth) . ' Years' }}</td>
                                        </tr>
                                         <tr>
                                            <td>Referred By</td>
                                            <td>:</td>
                                            <td style="padding-left: 2px">{{ $admission->referal_from ?? 'N/A' }}</td>
                                        </tr>
                                        <tr>
                                            <td width="35%">Blood Group</td>
                                            <td>:</td>
                                            <td colspan="3" style="padding-left: 2px">{{ $blood_group->group ?? 'N/A' }}</td>
                                        </tr>
                                        <tr>
                                            <td width="35%">TPA - (Third Party Administrator)</td>
                                            <td>:</td>
                                            <td colspan="3" style="padding-left: 2px">{{ $tpa_account->name ?? 'N/A' }}</td>
                                        </tr>    
                                    </tbody>
                                </table>
                         </div>
                    </div>
                </div>
            </div>

        <form class="row auto-width mt-0 ipd-patient-discharged" action="{{ route('ipd-admissions.patientdischargeupdate', $id) }}" method="post" enctype='multipart/form-data' style="padding: 0px 0px 0px 9px;">
            @csrf
            <div class="col-md-12 mt-4 " style="padding: 0 0 0 9px;">
                <div class="card">
                    <div class="card-body g-3 row">

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

                        <div class="col-md-3">
                            <label for="Discharge Type" class="form-label">Discharge Type <span class="text-danger"><b>*</b></span></label>
                            <select class="form-control discharge_type_code" name="discharge_type_code">
                                @foreach ($discharge_types as $type)
                                <option {{ isset($data) ? matchSelected($data->discharge_type_code, $type->code) : '' }} data-code="{{ $type->code }}" value="{{ $type->code }}">{{ $type->name }}</option>
                                @endforeach
                            </select>
                            <span class="text-danger error_discharge_type_code" style="display:none;">This field is required.</span>
                        </div>
                        <div class="col-md-3">
                            <label for="Discharge Date and Time" class="form-label">Discharge Date/Time <span class="text-danger"><b>*</b></span></label>
                            <!-- <input class="form-control datetimepicker" value="{{ !empty($data->discharge_datetime) && $data->discharge_datetime != '0000-00-00 00:00:00' ? date('m-d-Y H:i', strtotime($data->discharge_datetime)) : '' }}" type="text" id="discharge_datetime" name="discharge_datetime"> -->
                            <input class="form-control datepicker" type="text" value="{{ now()->format('m/d/Y'); }}" id="discharge_datetime" name="discharge_datetime" autocomplete="off">
                            <span class="text-danger error_discharge_datetime" style="display:none;">This field is required.</span>
                        </div>
                        <div class="col-md-3 row" style="    margin-top: 1.0rem !important;">
                            <label for="Re-visit after" class="form-label">Follow Up After </span></label>
                            <div class="col-md-6">
                                <select id = "num" class="form-control" >
                                    @for($i = 0 ; $i < 31 ; $i++)
                                    <option > {{ $i }} </option>
                                    @endfor
                                </select>
                            </div>
                            <div class="col-md-6 ">
                                <select id="value" class="form-control">
                                    <option >Days</option>
                                    <option >Month</option>
                                    <option >Year</option>
                                </select>
                            </div>
                        </div>

                         <div class="col-md-3">
                            <label for="Next Follow Up Date" class="form-label">Next Follow Up Date</label>
                            <input class="form-control " type="text" id="next_follow_up_date" name="next_follow_up_date" autocomplete="off" value="{{ isset($data) ? $data->next_follow_up_date : '' }}">
                        </div>
                        <div style="display: none" class="g-3 row referral_discharge_fields mt-0">
                            <div class="col-md-6">
                                <label for="Referral Date and Time" class="form-label">Referral Date and Time <span class="text-danger"><b>*</b></span></label>
                                <!-- <input value="{{ !empty($data->referral_date_time) && $data->referral_date_time != '0000-00-00 00:00:00' ? date('m-d-Y H:i', strtotime($data->referral_date_time)) : '' }}" class="form-control datetimepicker" type="text" name="referral_date_time"> -->

                                <input class="form-control datepicker" type="text" value="{{ !empty($data->referral_date_time) ? date('m/d/Y', strtotime($data->referral_date_time)) : '' }}" name="referral_date_time" autocomplete="off">
                                <span class="text-danger error_referral_date_time" style="display:none;">This field is required.</span>
                            </div>
                            <div class="col-md-6">
                                <label for="Referral Hospital Name" class="form-label">Referral Hospital Name <span class="text-danger"><b>*</b></span></label>
                                <input value="{{ isset($data) ? $data->referral_hospital_name : '' }}" class="form-control" type="text" name="referral_hospital_name" placeholder="Referral Hospital Name">
                                <span class="text-danger error_referral_hospital_name" style="display:none;">This field is required.</span>
                            </div>
                        </div>

                        <!-- DEATH DISCHARGE -->
                        <div style="display: none" class="g-3 row death_discharge_fields mt-0">
                            <div class="col-md-3">
                                <label for="Death Date and Time" class="form-label">Death Date and Time <span class="text-danger"><b>*</b></span></label>
                                <!-- <input class="form-control datetimepicker" value="{{ !empty($data->death_date_time) && $data->death_date_time != '0000-00-00 00:00:00' ? date('m-d-Y H:i', strtotime($data->death_date_time)) : '' }}" type="text" name="death_date_time"> -->

                                <input class="form-control datepicker" type="text" value="{{ !empty($data->death_date_time) ? date('m/d/Y', strtotime($data->death_date_time)) : '' }}" name="death_date_time" autocomplete="off">
                                <span class="text-danger error_death_date_time" style="display:none;">This field is required.</span>
                            </div>
                            <div class="col-md-3">
                                <label for="Guardian Name" class="form-label">Guardian Name <span class="text-danger"><b>*</b></span></label>
                                <input class="form-control" value="{{ isset($data) ? $data->family_contact : '' }}" type="text" name="family_contact" placeholder="Guardian Name">
                                <span class="text-danger error_family_contact" style="display:none;">This field is required.</span>
                            </div>
                            <div class="col-md-6">
                                <label for="File Attachment" class="form-label">File Attachment</label>
                                <input class="form-control" type="file" name="file_attachment">
                            </div>
                            @if(isset($data) && !empty($data->file_attachment))
                            <div class="col-6">
                                <img src="{!! isset($data) ? getTempUrl($data->file_attachment) : ''  !!}" height="auto" style="cursor: pointer;max-width: 120px;width: 120px;">
                            </div>
                            @endif
                        </div>

                        <div class="col-md-12">
                            <label for="special_note" class="form-label">Special Note</label>
                            <textarea class="form-textarea ckeditor" name="special_note" placeholder="Special Note">{{ isset($data) ? $data->special_note : '' }}</textarea>
                        </div>

                        <div class="col-md-12">
                            <label for="course_during_hosp" class="form-label">Course During Hospitality</label>
                            <textarea class="form-textarea ckeditor" name="course_during_hosp" placeholder="Course During Hospitality">{{ isset($data) ? $data->course_during_hosp : '' }}</textarea>
                        </div>

                        <div class="col-md-12">
                            <label for="post_operation" class="form-label">Post Operation</label>
                            <textarea class="form-textarea ckeditor" name="post_operation" placeholder="Post Operation">{{ isset($data) ? $data->post_operation : '' }}</textarea>
                        </div>

                        <div class="col-md-12">
                            <label for="condition_of_discharge" class="form-label">Condition of Discharge</label>
                            <textarea class="form-textarea ckeditor" name="condition_of_discharge" placeholder="Condition of Discharge">{{ isset($data) ? $data->condition_of_discharge : '' }}</textarea>
                        </div>
                        <div class="col-md-12">
                            <label for="advise_on_discharge" class="form-label">Advise On Discharge</label>
                            <textarea class="form-textarea ckeditor" name="advise_on_discharge" placeholder="Advise On Discharge">{{ isset($data) ? $data->advise_on_discharge : '' }}</textarea>
                        </div>

                        <!-- REFERRAL DISCHARGE -->
                        <div style="display: none" class="g-3 row referral_discharge_fields">
                            <div class="col-md-12">
                                <label for="Reason For Referral" class="form-label">Reason For Referral</label>
                                <textarea class="form-textarea ckeditor" name="reason_for_referral" placeholder="Referral Hospital Name">{{ isset($data) ? $data->reason_for_referral : '' }}</textarea>
                            </div>
                        </div>
                        @foreach($settings as $key => $field)
                            @if($field->type != 'hidden')
                            <div class="col-md-12 {!! $field->code == 'DEATH' ? 'death_discharge_fields' : ($field->code == 'REFERRAL' ? 'referral_discharge_fields' : '') !!}" >
                                <label for="{!! $field->id !!}" class="form-label">{!! $field->field !!}</label>
                            @endif
                            @php
                                $default_value = $field->value ?? $field->default_value;
                            @endphp
                                
                                @if($field->type == 'text')
                                    <input type="text" class="form-control" maxlength="{!! $field->length != '' ? $field->length : '' !!}" name="details[{!! $field->id !!}]" id="{{ $field->field }}" value="{!! $default_value !!}" {!! $field->is_readonly == 1 ? 'readonly' : '' !!} {!! $field->is_menditory == 1 ? 'required' : '' !!}/>
                                @elseif($field->type == 'textarea')
                                    <textarea class="form-control ckeditor" name="details[{!! $field->id !!}]" id="{{ $field->field }}" {!! $field->is_readonly == 1 ? 'readonly' : '' !!} maxlength="{!! $field->length != '' ? $field->length : '' !!}" {!! $field->is_menditory == 1 ? 'required' : '' !!}>{!! $default_value !!}</textarea>
                                @elseif($field->type == 'radio')
                                    <br>
                                    @php
                                        $options = [];
                                        $options = explode(',', $field->select_options);
                                    @endphp
                                    @foreach($options as $option)
                                        <input type="radio" id="{!! $field->id !!}_{{ $option }}" name="details[{!! $field->id !!}]" value="{{ $option }}" {!! $default_value == $option ? 'selected checked' : '' !!} {!! $field->is_readonly == 1 ? 'readonly' : '' !!} {!! $field->is_menditory == 1 ? 'required' : '' !!}>
                                        <label for="{!! $field->id !!}_{{ $option }}">{{ $option }}</label>
                                        <br>
                                    @endforeach
                                @elseif($field->type == 'checkbox')
                                    <input type="checkbox" class="checkbox_input" id="{{ $field->id }}" {!! $default_value == true || $default_value == 1 || $default_value == 'on' ? 'checked' : '' !!} {!! $field->is_readonly == 1 ? 'readonly' : '' !!}/>
                                    <input type="hidden" name="details[{!! $field->id !!}]" class="checkbox_value" value="{!! $default_value == true || $default_value == 1 || $default_value == 'on' ? '1' : '0' !!}">
                                @elseif($field->type == 'select')
                                    @php
                                        $options = [];
                                        $options = explode(',', $field->select_options);
                                    @endphp
                                    <select class="form-control" name="details[{!! $field->id !!}]" id="{{ $field->field }}" {!! $field->is_readonly == 1 ? 'readonly' : '' !!} {!! $field->is_menditory == 1 ? 'required' : '' !!}>
                                        <option value="">Select</option>
                                        @foreach($options as $option)
                                            <option value="{{ $option }}" {!! $default_value == $option ? 'selected' : '' !!}>{{ $option }}</option>
                                        @endforeach
                                    </select>
                                @elseif($field->type == 'hidden')
                                    <input type="hidden" name="details[{!! $field->id !!}]" value="{!! $default_value !!}" {!! $field->is_readonly == 1 ? 'readonly' : '' !!}>
                                @elseif($field->type == 'date')
                                    <input type="date" class="form-control" name="details[{!! $field->id !!}]" id="{{ $field->field }}" value="{!! $default_value !!}" {!! $field->is_readonly == 1 ? 'readonly' : '' !!} {!! $field->is_menditory == 1 ? 'required' : '' !!}>
                                @endif

                            @if($field->type != 'hidden')
                            </div>
                            @endif
                        @endforeach
                        <div class="g-3 row col-md-12 mt-0">
                            <div class="col-md-6">
                                <label for="explained_by" class="form-label">Explained By</label>
                                <input type="text" name="explained_by" class="form-control" value="{{ isset($data) ? $data->explained_by : '' }}">
                            </div>

                            <div class="col-md-6">
                                <label for="understood_by" class="form-label">Understood By</label>
                                <input type="text" name="understood_by" class="form-control" value="{{ isset($data) ? $data->understood_by : '' }}">
                            </div>
                        </div>
                         <div class="col-md-4">
                            <label for="signed_status" class="form-label">Signed Status</label>
                            <select class="form-control" name="signed_status">
                                <option value="0" {!! !empty($data) ? matchSelected('0', $data->signed_status) : '' !!}>Draft</option>
                                <option value="1" {!! !empty($data) ? matchSelected('1', $data->signed_status) : '' !!}>Signed</option>
                            </select>
                        </div>
                         <div class="col-md-4">
                            <label for="Next Follow Up Date" class="form-label">Signed By Dr.</label>
                            <div class="input-group autocomplete">
                                <input type="text" name="" id="doctor_id" class="doctor-select form-control" placeholder="Search Doctor" autocomplete="off" value="@if(!empty($signed_by->name)){!! $signed_by->account_titles !!} {!! $signed_by->name !!} - ({!! $signed_by->code !!}), {!! $signed_by->gender !!}@endif" {{isset($opdBooking->getDoctorAccount->id)?'readonly':''}}>
                                <ul class="searchResult"></ul>
                                <input type="hidden" name="doctor_id" value="{{$signed_by->id??''}}">
                            </div>
                        </div>

                         <div class="col-md-4">
                            <label for="signed_at" class="form-label">Signed Date</label>
                            <input class="form-control datepicker" type="text" id="signed_at" name="signed_at" autocomplete="off" value="{{ isset($data) ? $data->signed_at : '' }}">
                        </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 Discharged</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");

    $(document).ready(function() {
            flatpickr('.datetimepicker', {
                enableTime: true,
                dateFormat: "Y-m-d H:i",
                defaultDate: "now",
                clickOpens: true
            });

        dischargeTypes();

        function dischargeTypes() {
            var selectedOption = $('.discharge_type_code').find('option:selected');
            var discharge_type_code = selectedOption.data('code');
            var referral_discharge_fields = $('.referral_discharge_fields');
            var death_discharge_fields = $('.death_discharge_fields');

            if (discharge_type_code == 'NORMAL') {
                referral_discharge_fields.hide();
                death_discharge_fields.hide();
                referral_discharge_fields.find('input').val('');
                death_discharge_fields.find('input').val('');
            } else if (discharge_type_code == 'REFERRAL') {
                referral_discharge_fields.show();
                death_discharge_fields.hide();
                death_discharge_fields.find('input').val('');
            } else if (discharge_type_code == 'DEATH') {
                death_discharge_fields.show();
                referral_discharge_fields.hide();
                referral_discharge_fields.find('input').val('');
            }
        }

        $('.discharge_type_code').on('change', dischargeTypes);


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

    });

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

        if ($('.discharge_type_code option:selected').data('code') == 'REFERRAL') {
            $('.error_discharge_datetime').hide();
            $('.error_referral_date_time').hide();
            $('.error_referral_hospital_name').hide();
            $('.error_discharge_type_code').hide();
            var error = 0;

            console.log('tesr');
            if ($('input[name="discharge_datetime"]').val() == '') {
                $('.error_discharge_datetime').show();
                error = 1;
            }
            if ($('input[name="referral_date_time"]').val() == '') {
                $('.error_referral_date_time').show();
                error = 1;
            }
            if ($('input[name="referral_hospital_name"]').val() == '') {
                $('.error_referral_hospital_name').show();
                error = 1;
            }
            if ($('.discharge_type_code').val() == null) {
                $('.error_discharge_type_code').show();
                error = 1;
            }
            if (error == 0) {
                $('.ipd-patient-discharged').submit();
            }
        } else if ($('.discharge_type_code option:selected').data('code') == 'DEATH') {
            $('.error_discharge_datetime').hide();
            $('.error_death_date_time').hide();
            $('.error_family_contact').hide();
            $('.error_discharge_type_code').hide();
            var error = 0;
            if ($('input[name="discharge_datetime"]').val() == '') {
                $('.error_discharge_datetime').show();
                error = 1;
            }
            if ($('input[name="death_date_time"]').val() == '') {
                $('.error_death_date_time').show();
                error = 1;
            }
            if ($('input[name="family_contact"]').val().trim() == '') {
                $('.error_family_contact').show();
                error = 1;
            }
            if ($('.discharge_type_code').val() == null) {
                $('.error_discharge_type_code').show();
                error = 1;
            }
            if (error == 0) {
                $('.ipd-patient-discharged').submit();
            }
        } else {
            $('.error_discharge_datetime').hide();
            $('.error_discharge_type_code').hide();
            var error = 0;

            if ($('input[name="discharge_datetime"]').val() == '') {
                $('.error_discharge_datetime').show();
                error = 1;
            }
            if ($('.discharge_type_code').val() == null) {
                $('.error_discharge_type_code').show();
                error = 1;
            }

            if (error == 0) {
                $('.ipd-patient-discharged').submit();
            }
        }

        error = 1;
    });

        $('.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);
        };
    $(document).on('change','#num ,#value ,#discharge_datetime', function() {

    var first = parseInt($('#num').val());
    var second =($('#value').val());
    var date = new Date($('#discharge_datetime').val());
    

    if($('#value').val() == 'Days'){
         date.setDate(date.getDate() + first);

          $("#next_follow_up_date").val($.datepicker.formatDate("mm/dd/yy", date) );
       
    }

    else if($('#value').val() == 'Month'){
       date.setMonth(date.getMonth() + first);
          $("#next_follow_up_date").val($.datepicker.formatDate("mm/dd/yy", date) );

    }
    else if($('#value').val() == 'Year'){
         date.setFullYear(date.getFullYear() + first);
          $("#next_follow_up_date").val($.datepicker.formatDate("mm/dd/yy", date) );
    }

   
});

</script>
@endsection
