<?php

use App\Models\Point;

$category = 'OBJECTIVE_SYSTEM';
$endPoint = 'upsertNoteSingleton';

$point = Point::where('added_in_note_id', $note->id)->where('category', $category)->orderBy('id', 'DESC')->first();
$contentData = [
    "reviewed_relevant_labs" => null,
    "lab_findings" => null,
    "reviewed_relevant_rpm_data" => null,
    "rpm_findings" => null,
    "rpm_data_unavailable" => null
];
if (!!@$point->data) {
    $contentData = json_decode($point->data, true);
}
?>
<div visit-moe close-on-save close-on-cancel class="d-block px-2 py-1">
    <form show url="/api/visitPoint/<?= $endPoint ?>" class="mcp-theme-1">
        <input type="hidden" name="segmentUid" value="<?= $segment->uid ?>">
        <input type="hidden" name="category" value="<?= $category ?>">
        <input type="hidden" name="data" value="{{json_encode($contentData)}}">

        <label class="d-flex align-items-center mb-2">
            <input type="checkbox" data-name="reviewed_relevant_labs" {{@$contentData["reviewed_relevant_labs"] ? 'checked' : ''}} class="mr-2">
            <span>Reviewed relevant labs.</span>
        </label>

        <div class="mb-2 align-items-baseline {{ @$contentData["reviewed_relevant_labs"] ? 'd-flex' : 'd-none' }}" if-reviewed-labs>
            <span class="text-dark mr-2 text-nowrap">Lab Findings:</span>
            <input type="text" class="form-control form-control-sm flex-grow-1" data-name="lab_findings" value="{{@$contentData["lab_findings"]}}">
        </div>

        <label class="d-flex align-items-center mb-2">
            <input type="checkbox" data-name="reviewed_relevant_rpm_data" {{@$contentData["reviewed_relevant_rpm_data"] ? 'checked' : ''}} class="mr-2">
            <span>Reviewed relevant remote measurements.</span>
            <?php
            // resolve care month from the effective date of this note
            $cmStartDate = date('Y-m-01', strtotime($note->effective_dateest));
            $careMonth = \App\Models\CareMonth::where('client_id', $note->client->id)->where('start_date', $cmStartDate)->first();
            ?>
            @if($careMonth && $careMonth->is_client_enrolled_in_rm)
                <a href="/patients/view/{{ $note->client->uid }}/care-months/view/{{$careMonth->uid}}"
                   class="text-nowrap ml-3"
                   native target="_blank"
                   open-in-stag-popup
                   popup-style="tall overflow-visible"
                   mc-initer="care-month-dashboard-{{$note->client->uid}}"
                   title="Current Care Month RPM Data"
                >Current Care Month RPM Data</a>
            @endif
        </label>

        <div class="mb-2 align-items-baseline {{ @$contentData["reviewed_relevant_rpm_data"] ? 'd-flex' : 'd-none' }}" if-reviewed-rpm>
            <span class="text-dark mr-2 text-nowrap">RPM Findings:</span>
            <input type="text" class="form-control form-control-sm flex-grow-1" data-name="rpm_findings" value="{{@$contentData["rpm_findings"]}}">
        </div>

        <label class="d-flex align-items-center mb-2">
            <input type="checkbox" data-name="rpm_data_unavailable" {{@$contentData["rpm_data_unavailable"] ? 'checked' : ''}} class="mr-2">
            <span>Remote monitoring data not available.</span>
        </label>

        @if($careMonth && $careMonth->is_client_enrolled_in_rm)
            <div class="w-75">
                @include('app.patient.care-month._vitals_graph_unified', ['suffix' => $segment->uid])
            </div>
        @endif

        <div class="pt-2">
            <button submit class="btn btn-sm btn-primary mr-2"><i class="fa fa-save"></i></button>
            <div class="d-inline-flex align-self-stretch align-items-center">
                <span class="autosave-indicator saving text-sm text-secondary">Saving changes &hellip;</span>
                <span class="autosave-indicator saved text-sm text-secondary">
                    <i class="fa fa-check"></i>
                    Saved
                </span>
            </div>
        </div>
    </form>
</div>

@if($careMonth && $careMonth->is_client_enrolled_in_rm)
    <div class="p-2">
        <div class="d-flex align-items-center">
            <h6 class="my-0 text-secondary font-weight-bold text-dark lh-24px"><span class="text-secondary">RPM time billed:</span> {{time_in_hrminsec($careMonth->rm_total_time_in_seconds_by_mcp)}}</h6>
            <?php
            $rmBills = $careMonth->getBillsOfType('RM');
            $activeRMBill = false;
            foreach ($rmBills as $rmBill) {
                if(!$rmBill->is_cancelled && $careMonth->rm_bill_id === $rmBill->id) {
                    $activeRMBill = $rmBill;
                    break;
                }
            }
            ?>
            <span class="mx-2 text-secondary">|</span>
            @include('app.practice-management.care_month_add_entry_form', [
                'right' => false,
                'hook' => 'updateRMSegment',
                'defaultDate' => $note->effective_dateest,
                'defaultSeconds' => 120,
                'defaultInteracted' => true,
                'defaultComment' => 'I have discussed remote monitoring data to date and encouraged patient to regularly measure and follow the care plan.'
                ])
        </div>
{{--        <table class="table table-striped table-sm table-bordered mt-2 mb-0 table-hover">--}}
{{--            <thead>--}}
{{--            <tr>--}}
{{--                <th class="px-2 text-secondary border-bottom-0">Effective Date</th>--}}
{{--                <th class="px-2 text-secondary border-bottom-0">Time</th>--}}
{{--                <th class="px-2 text-secondary border-bottom-0">Created</th>--}}
{{--                <th class="px-2 text-secondary border-bottom-0">Communicated</th>--}}
{{--                <th class="px-2 text-secondary border-bottom-0 w-50">Comments</th>--}}
{{--                <th class="px-2 text-secondary border-bottom-0 delete-column">&nbsp;</th>--}}
{{--            </tr>--}}
{{--            </thead>--}}
{{--            <tbody>--}}
{{--            @foreach($careMonth->entries as $entry)--}}
{{--                @if(!$entry->is_removed && $entry->cm_or_rm === "RM")--}}
{{--                    <tr>--}}
{{--                        <td class="px-2">--}}
{{--                            <div class="font-weight-bold">{{friendly_date_time($entry->effective_date, false)}}</div>--}}
{{--                        </td>--}}
{{--                        <td class="px-2">--}}
{{--                            {{time_in_hrminsec($entry->time_in_seconds)}}--}}
{{--                        </td>--}}
{{--                        <td class="px-2">--}}
{{--                            {{friendly_date_time($entry->created_at)}}--}}
{{--                        </td>--}}
{{--                        <td class="px-2">--}}
{{--                            {{$entry->did_pro_interact_with_client_about_rm ? 'Yes' : 'No'}}--}}
{{--                        </td>--}}
{{--                        <td class="px-2">--}}
{{--                            <div class="text-secondary in-table-markup">{!! $entry->content_text !!}</div>--}}
{{--                            <!--                                        <div class="text-secondary text-sm">{{$entry->content_detail}}</div>-->--}}
{{--                        </td>--}}
{{--                        <td class="px-2">--}}
{{--                            @if(!$activeRMBill)--}}
{{--                                @include('app.practice-management.care_month_add_entry_form', ['right' => true, 'entry' => $entry])--}}
{{--                                <div moe relative>--}}
{{--                                    <a start show class="text-danger">Delete</a>--}}
{{--                                    <form url="/api/careMonthEntry/remove" right class="text-left">--}}
{{--                                        <input type="hidden" name="uid" value="{{ $entry->uid }}">--}}
{{--                                        <p class="small">Are you sure you want to delete this RM entry?</p>--}}
{{--                                        <div class="d-flex align-items-center">--}}
{{--                                            <button class="btn btn-sm btn-danger mr-2" submit>Delete</button>--}}
{{--                                            <button class="btn btn-sm btn-default mr-2 border" cancel>Cancel</button>--}}
{{--                                        </div>--}}
{{--                                    </form>--}}
{{--                                </div>--}}
{{--                            @else--}}
{{--                                <span class="text-sm text-secondary">Can't modify since a bill exists</span>--}}
{{--                            @endif--}}
{{--                        </td>--}}
{{--                    </tr>--}}
{{--                @endif--}}
{{--            @endforeach--}}
{{--            </tbody>--}}
{{--        </table>--}}
    </div>
@endif

<script>
    (function() {
        window.segmentInitializers.<?= !!@$segment ? $segment->segmentTemplate->internal_name : $segmentInternalName ?> = function () {
            let parentSegment = $('[data-segment-template-name="<?= $segment->segmentTemplate->internal_name ?>"] ');
            parentSegment.find('[data-name="reviewed_relevant_labs"]')
                .off('change')
                .on('change', function() {
                    if(this.checked) {
                        parentSegment.find('[if-reviewed-labs]').removeClass('d-none').addClass('d-flex');
                    }
                    else {
                        parentSegment.find('[if-reviewed-labs]').removeClass('d-flex').addClass('d-none');
                    }
                });
            parentSegment.find('[data-name="reviewed_relevant_rpm_data"]')
                .off('change')
                .on('change', function() {
                    if(this.checked) {
                        parentSegment.find('[data-name="rpm_data_unavailable"]').prop('checked', false);
                        parentSegment.find('[if-reviewed-rpm]').removeClass('d-none').addClass('d-flex');
                    }
                    else {
                        parentSegment.find('[if-reviewed-rpm]').removeClass('d-flex').addClass('d-none');
                    }
                });
            parentSegment.find('[data-name="rpm_data_unavailable"]')
                .off('change')
                .on('change', function() {
                    if(this.checked) {
                        parentSegment.find('[data-name="reviewed_relevant_rpm_data"]').prop('checked', false);
                        parentSegment.find('[if-reviewed-rpm]').removeClass('d-flex').addClass('d-none');
                    }
                });

            @if($careMonth && $careMonth->is_client_enrolled_in_rm)
            runMCInitializer('vitalsGraphUnified_{{$careMonth->id}}{{$segment->uid}}');
            addMCHook('updateRMSegment', function() {
                refreshSegment('<?= $segment->segmentTemplate->internal_name ?>');
                return false;
            });
            initMoes();
            initProSuggest();
            parentSegment.find('[cm-rte]').each(function() {

                $(this).wrap(
                    $('<div class="border-left border-right rte-holder"/>')
                        .attr('data-shortcuts', '')
                );

                // give a unique id to this editor instance
                var editorID = Math.ceil(Math.random() * 99999), fieldName = $(this).attr('data-name');

                var el = this;
                var existingContent = $(el).attr('data-content') ? $(el).attr('data-content') : $(el).html();
                var quill = new Quill(el, {
                    theme: 'snow',
                    modules: stagQuillConfig
                });

                var toolbar = $(quill.container).prev('.ql-toolbar');

                // add button for new shortcut
                var newSCButton = $('<button class="btn bg-white btn-sm btn-default text-primary w-auto px-2 border py-0 ' +
                    'text-sm add-shortcut" data-editor-id="' + editorID + '">+ Shortcut</button>');
                toolbar.append(newSCButton);

                quill.root.innerHTML = existingContent;

                $('<input type="hidden" name="' + fieldName + '">').val(existingContent).insertAfter(el);

                quill.on('text-change', function(delta, oldDelta, source) {
                    $(el).next('[name="' + fieldName + '"]').val(quill.root.innerHTML);
                });

                $(quill.container)
                    .find('.ql-editor[contenteditable]')
                    .attr('data-field', fieldName)
                    .attr('data-editor-id', editorID)
                    .attr('with-shortcuts', 1);

            });
            @endif
        };
    }).call(window);
</script>