@php
    $parsedDetailJson = new stdClass();
    if($note->detail_json) {
        try {
            $parsedDetailJson = json_decode($note->detail_json);
        }
        catch (Exception $e) {}
    }
@endphp

<style>.nrc-badge.bgyellow { background-color: lightyellow; }</style>
<style>.nrc-badge.bggreen { background-color: #caffca; }</style>
<style>.nrc-badge.bgblue { background-color: #d0f2fd; }</style>
<style>.nrc-badge.claim-closed { background-color: lightgray; }</style>

<div class="popup-content-container pt-2" id="note-resolve-{{$note->uid}}">

    <div class="d-flex align-items-center mb-2 mx-3">

        <div class="rounded py-1 px-2 font-weight-bold mr-2 {{ $note->visit_number > 2 ? 'nrc-badge bgyellow': ($note->visit_number == 1 ? 'nrc-badge bggreen': ($note->visit_number == 2 ? 'nrc-badge bgblue':'')) }}">Visit #{{$note->visit_number}}</div>

        <div moe>
            <a href="" start show class="">Memo to Shawn: </a> <b>{{ @$parsedDetailJson->memo_to_shawn }}</b> &nbsp;

            <form url="/api/note/upsertDetailJsonKeyVal" class="mcp-theme-1">
                <input type="hidden" name="uid" value="{{$note->uid}}" class="form-control input-sm" />
                <input type="hidden" name="key" value="memo_to_shawn" class="form-control input-sm" />
                <div class="form-group">
                    <textarea name="val" class="form-control" >{{ @$parsedDetailJson->memo_to_shawn }}</textarea>
                </div>
                <div class="form-group text-nowrap mb-0">
                    <button class="btn btn-sm btn-primary" submit>Submit</button>
                    <button class="btn btn-sm btn-default border" close>Close</button>
                </div>
            </form>
        </div>

        @if(@$parsedDetailJson->farah_decision)
            <span class="mr-2">Farah:</span>
            <span class="mr-3">
                @if(@$parsedDetailJson->farah_decision == 'green')
                    <span class="text-success font-weight-bold"><i class="fa fa-check"></i> Yes</span>
                @elseif(@$parsedDetailJson->farah_decision == 'red')
                    <span class="text-warning-dark font-weight-bold"><i class="fa fa-exclamation-triangle"></i> No</span>
                @else
                    -
                @endif
            </span>
        @endif

        @if(@$parsedDetailJson->shawn_decision)
            <span class="mr-2">Shawn:</span>
            <span class="mr-3">
                @if(@$parsedDetailJson->shawn_decision == 'green')
                    <span class="text-success font-weight-bold"><i class="fa fa-check"></i> Green</span>
                @elseif(@$parsedDetailJson->shawn_decision == 'red')
                    <span class="text-danger font-weight-bold"><i class="fa fa-exclamation-triangle"></i> Rejected</span>
                @else
                    -
                @endif
            </span>
        @endif

        @if(@$parsedDetailJson->kyle_billed)
            <span class="mr-2">Kyle:</span>
            <span class="mr-3">
                @if(@$parsedDetailJson->kyle_billed == 'yes')
                    <span class="text-success font-weight-bold"><i class="fa fa-check"></i> Billed</span>
                @else
                    -
                @endif
            </span>
        @endif

        @if(@$parsedDetailJson->kyle_billed !== 'yes')
            <span class="mr-2">Mark as:</span>
            <div moe>
                <form url="/api/note/upsertDetailJsonKeyVal" show>
                    <input type="hidden" name="uid" value="{{$note->uid}}">
                    <input type="hidden" name="key" value="farah_decision">
                    <input type="hidden" name="val" value="green">
                    <button submit class="mr-2 btn btn-sm font-weight-bold btn-success">Farah Green</button>
                </form>
            </div>
            <div moe>
                <form url="/api/note/upsertDetailJsonKeyVal" show>
                    <input type="hidden" name="uid" value="{{$note->uid}}">
                    <input type="hidden" name="key" value="farah_decision">
                    <input type="hidden" name="val" value="red">
                    <button submit class="mr-2 btn btn-sm font-weight-bold btn-warning">Shawn Review</button>
                </form>
            </div>
            @if(@$parsedDetailJson->farah_decision)
                @if(@$parsedDetailJson->farah_decision === 'red')
                    <div moe>
                        <form url="/api/note/upsertDetailJsonKeyVal" show>
                            <input type="hidden" name="uid" value="{{$note->uid}}">
                            <input type="hidden" name="key" value="shawn_decision">
                            <input type="hidden" name="val" value="green">
                            <button submit class="mr-2 btn btn-sm font-weight-bold btn-success">Shawn Green</button>
                        </form>
                    </div>
                    <div moe>
                        <form url="/api/note/upsertDetailJsonKeyVal" show>
                            <input type="hidden" name="uid" value="{{$note->uid}}">
                            <input type="hidden" name="key" value="shawn_decision">
                            <input type="hidden" name="val" value="red">
                            <button submit class="mr-2 btn btn-sm font-weight-bold btn-danger">Shawn Reject</button>
                        </form>
                    </div>
                @endif
                @if(@$parsedDetailJson->farah_decision == 'green' || @$parsedDetailJson->shawn_decision == 'green')
                    <div moe>
                        <form url="/api/note/upsertDetailJsonKeyVal" show>
                            <input type="hidden" name="uid" value="{{$note->uid}}">
                            <input type="hidden" name="key" value="kyle_billed">
                            <input type="hidden" name="val" value="yes">
                            <button submit class="mr-2 btn btn-sm font-weight-bold btn-primary">Kyle Billed</button>
                        </form>
                    </div>
                @endif
            @endif
        @endif
        @if(!$note->is_claim_closed)
            <div moe>
                <form show url="/api/note/processNoteShortcut">
                    <input type="hidden" name="uid" value="{{$note->uid}}">
                    <button submit class="mr-2 btn btn-sm font-weight-bold btn-primary">Submit Claim</button>
                </form>
            </div>
        @else
            <h6>CLAIM CLOSED</h6>
        @endif
        <button type="button" class="ml-auto btn btn-sm font-weight-bold btn-info btn-prev-row"><i class="fa fa-chevron-left"></i> Prev</button>
        <button type="button" class="ml-2 btn btn-sm font-weight-bold btn-info btn-next-row">Next <i class="fa fa-chevron-right"></i></button>
    </div>

    <div class="mx-3 border">
        <div id="note-single-header" class="d-flex border-bottom align-items-start note_template_{{$note->visitTemplate ? $note->visitTemplate->internal_name : ''}}">

            <div class="p-2 d-inline-flex align-items-start w-100">
                <div class="d-inline-flex mr-3 align-items-baseline">
                    <div class="font-weight-bold font-size-14">{{$patient->displayName()}}</div>
                </div>
                <div class="mr-3">
                    <?php
                    $coverage = $patient->getPrimaryCoverage();
                    $coverageStatus = $patient->getPrimaryCoverageStatus();
                    ?>
                    @if(!$patient->getPrimaryCoverage() || $patient->getPrimaryCoverageStatus() !== 'YES')
                        <div class="max-width-300px">
                            @include('app.patient.coverage-status')
                        </div>
                    @else
                        @include('app.patient.coverage_column_renderer', ['patient'=>$patient, 'truncateName' => true])
                    @endif
                </div>
                <div class="d-inline-flex mr-3 align-items-baseline">
                    <div class="mr-1 text-secondary">DOB:</div>
                    <div>{{$patient->dob}}</div>
                </div>
                <div class="d-inline-flex mr-3 align-items-baseline">
                    <div class="mr-1 text-secondary">Visit Date:</div>
                    <div>{{friendly_date($note->effective_dateest)}}</div>
                </div>
                <div class="d-inline-flex align-items-baseline">
                    <div class="mr-1 text-secondary">Signed By:</div>
                    <div class="mr-2">{{$note->hcpPro->displayName()}}</div>
                    <div class="mr-2">on</div>
                    <div class="mr-2 text-info">{{friendlier_date_time($note->signed_by_hcp_at)}}</div>
                </div>
                <a href="#" native class="ml-2" onclick="$('[data-non-segment-section=Claims]')[0].scrollIntoView({behavior: 'smooth', block: 'end'}); return false;">Go to end</a>
            </div>

            @if($patient->sticky_note)
                <div class="flex-grow-1 border-left p-2 d-inline-flex align-items-baseline bg-aliceblue">
                    <span class="">{{$patient->sticky_note}}</span>
                </div>
            @endif


        </div>

        <div class="card mb-0 {{ $note->is_cancelled ? 'cancelled-item' : '' }} border-0 rounded-0">

            <div class="card-body d-flex align-items-start p-0">
                <div class="flex-grow-1 overflow-auto resolve-segments" style="max-height: calc(100vh - 270px);">
                    <div class="note_template_{{$note->visitTemplate ? $note->visitTemplate->internal_name : ''}}">
                        @include('app.patient.note.note-segment-list-resolve')
                        <div class="border-top mt-3 pt-3 px-3" id="care-plan-details-{{$note->uid}}" moe-refresh-container>
                            @include('app.patient.note.partials.care-plan-details')
                        </div>
                        <div class="border-top mt-3">
                            @include('app.patient.note.partials.cpp-bills-claims-container')
                        </div>
                    </div>
                </div>
                <div class="overflow-auto min-width-250px width-250px" style="max-height: calc(100vh - 270px);">
                    <div class="p-2 border-bottom nrc-icds">
                        <div class="d-flex align-items-baseline mb-1">
                            <div class="font-weight-bold mr-2">Claim ICDs</div>
                            <?php
                            $commonICDs = [
                                [
                                    "code" => "Z71.9",
                                    "desc" => "Counseling, unspecified"
                                ],
                                [
                                    "code" => "I10",
                                    "desc" => "Essential (primary) hypertension"
                                ]
                            ]
                            ?>
                            @foreach($commonICDs as $commonICD)
                                <div class="d-inline position-relative on-hover-show ml-2">
                                        <span class="text-primary c-pointer text-sm">
                                            {{$commonICD['code']}}
                                        </span>
                                    <div menu right class="bg-white border on-hover-content">
                                        @for($i = 1; $i <= 4; $i++)
                                            <a native target="_blank" href="#"
                                               data-code="{{$commonICD['code']}}"
                                               data-description="{{$commonICD['desc']}}"
                                               data-target="{{$i - 1}}"
                                               class="px-2 py-1 d-block text-nowrap text-sm common-icd-item">
                                                Add to ICD {{$i}}
                                            </a>
                                        @endfor
                                    </div>
                                </div>
                            @endforeach
                            <a native target="_blank" href="#"
                               data-code="Z71.9"
                               data-description="Counseling, unspecified"
                               data-target="0"
                               class="text-primary c-pointer text-sm ml-2 common-icd-item">
                                Z@1
                            </a>
                            <a native target="_blank" href="#"
                               data-code="I10"
                               data-description="Essential (primary) hypertension"
                               data-target="1"
                               class="text-primary c-pointer text-sm ml-2 common-icd-item">
                                I@2
                            </a>
                            <div class="d-inline position-relative on-hover-show ml-auto">
                                    <span class="text-primary c-pointer text-sm">
                                        Clear <i class="fa fa-caret-down"></i>
                                    </span>
                                <div menu class="bg-white border on-hover-content">
                                    @for($i = 1; $i <= 4; $i++)
                                        <a native target="_blank" href="#"
                                           data-code=""
                                           data-description=""
                                           data-target="{{$i - 1}}"
                                           class="px-2 py-1 d-block text-nowrap text-sm common-icd-item">
                                            Clear ICD {{$i}}
                                        </a>
                                    @endfor
                                    <a native target="_blank" href="#"
                                       data-code=""
                                       data-description=""
                                       data-target="{{$i - 1}}"
                                       class="px-2 py-1 d-block text-nowrap text-sm common-icd-item-clear-all">
                                        Clear All
                                    </a>
                                </div>
                            </div>
                        </div>
                        <div moe="">
                            <form show url="/api/note/putReasons" class="mcp-theme-1" hook="onICDUpdate-{{$note->uid}}">
                                <input type="hidden" name="uid" value="{{$note->uid}}">
                                <div>
                                    <table class="table table-sm table-bordered mb-2">
                                        <thead class="bg-light">
                                        <tr>
                                            <th class="border-bottom-0">ICD</th>
                                            <th class="border-bottom-0">Desc.</th>
                                        </tr>
                                        </thead>
                                        <tbody>
                                        <tr>
                                            <td class="p-0">
                                                <input icd-autocomplete-code type="text" class="rounded-0 border-0 shadow-none icd-input width-70px pr-0 min-width-unset"
                                                       name="reasonIcd1" placeholder="ICD 1" value="{{@$note->note_reason_icd1}}" autocomplete="off">
                                            </td>
                                            <td class="p-0">
                                                <input icd-autocomplete-description type="text" class="rounded-0 border-0 shadow-none form-control form-control-sm min-width-unset"
                                                       name="reasonIcd1Description" value="{{@$note->note_reason_icd1description}}"
                                                       title="{{@$note->note_reason_icd1description}}">
                                            </td>
                                        </tr>
                                        <tr>
                                            <td class="p-0">
                                                <input icd-autocomplete-code type="text" class="rounded-0 border-0 shadow-none icd-input width-70px pr-0 min-width-unset"
                                                       name="reasonIcd2" placeholder="ICD 2" value="{{@$note->note_reason_icd2}}" autocomplete="off">
                                            </td>
                                            <td class="p-0">
                                                <input icd-autocomplete-description type="text" class="rounded-0 border-0 shadow-none form-control form-control-sm min-width-unset"
                                                       name="reasonIcd2Description" value="{{@$note->note_reason_icd2description}}"
                                                       title="{{@$note->note_reason_icd2description}}">
                                            </td>
                                        </tr>
                                        <tr>
                                            <td class="p-0">
                                                <input icd-autocomplete-code type="text" class="rounded-0 border-0 shadow-none icd-input width-70px pr-0 min-width-unset"
                                                       name="reasonIcd3" placeholder="ICD 3" value="{{@$note->note_reason_icd3}}" autocomplete="off">
                                            </td>
                                            <td class="p-0">
                                                <input icd-autocomplete-description type="text" class="rounded-0 border-0 shadow-none form-control form-control-sm min-width-unset"
                                                       name="reasonIcd3Description" value="{{@$note->note_reason_icd3description}}"
                                                       title="{{@$note->note_reason_icd3description}}">
                                            </td>
                                        </tr>
                                        <tr>
                                            <td class="p-0">
                                                <input icd-autocomplete-code type="text" class="rounded-0 border-0 shadow-none icd-input width-70px pr-0 min-width-unset"
                                                       name="reasonIcd4" placeholder="ICD 4" value="{{@$note->note_reason_icd4}}" autocomplete="off">
                                            </td>
                                            <td class="p-0">
                                                <input icd-autocomplete-description type="text" class="rounded-0 border-0 shadow-none form-control form-control-sm min-width-unset"
                                                       name="reasonIcd4Description" value="{{@$note->note_reason_icd4description}}"
                                                       title="{{@$note->note_reason_icd4description}}">
                                            </td>
                                        </tr>
                                        </tbody>
                                    </table>
                                </div>
                                <div class="mb-2">
                                    <label class="text-secondary mb-1">Reason Memo:</label>
                                    <input type="text" class="form-control form-control-sm min-width-unset" name="reasonMemo" value="{{@$note->note_reason_memo}}">
                                </div>
                                <div>
                                    <button submit="" class="btn btn-sm btn-primary mr-1">Submit</button>
                                    <button cancel="" class="btn btn-sm btn-default border">Cancel</button>
                                </div>
                            </form>
                        </div>
                    </div>
                    @include('app.patient.note.rhs-sidebar-nrc')
                </div>
            </div>
        </div>
    </div>
</div>
<script>
    (function() {
        function __initRTEs(_collection) {
            _collection.each(function() {

                let noteRTE = $(this);

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

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

                var el = this;
                var existingContent = $(el).html();
                var quill = new Quill(el, {
                    theme: 'snow',
                    modules: {
                        toolbar: false,
                        keyboard: {
                            bindings: {
                                'tab': {
                                    key: 9,
                                    handler: function(range, context) {
                                        return true;
                                    }
                                }
                            }
                        }
                    },
                    /*formats: [
                        'bold',
                        'italic',
                        'link',
                        'size',
                        'strike',
                        'underline',
                        'blockquote',
                        'header',
                        'indent',
                        'list',
                        'align',
                    ]*/
                });

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

                quill.root.innerHTML = existingContent;

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

                $(el).data('quillInstance', quill);

            });
        }
        function init() {
            let parentSegment = $('#note-resolve-{{$note->uid}}');
            // __initRTEs(parentSegment.find('[note-rte]:not(.ql-container)'));
            runMCInitializer('icd-autocomplete');
            parentSegment.find('.btn-apply-override')
                .off('click.apply-override')
                .on('click.apply-override', function() {
                    let html = $.trim($(this).closest('.rhs-edit').find('[contenteditable]').first().html());
                    $.post('/api/segment/proposeSegmentSummarySuggestion', {
                        uid: $(this).attr('data-segment-uid'),
                        proposedSuggestedSummaryHtml: html,
                        autoAccept: true
                    }, _data => {
                        if(!hasResponseError(_data)) {
                            toastr.success('Updated');
                            $(this).closest('.overridable').find('.lhs-read').first().html(html);
                        }
                    }, 'json');
                });

            parentSegment.find('.common-icd-item')
                .off('click.add-common-icd')
                .on('click.add-common-icd', function () {
                    let table = $(this).closest('.nrc-icds').find('table').first(),
                        tr = table.find('tbody>tr:eq(' + $(this).attr('data-target') + ')');
                    tr.find('>td:eq(0) input').first().val($(this).attr('data-code'));
                    tr.find('>td:eq(1) input').first().val($(this).attr('data-description'));
                    $(this).closest('.on-hover-content').find('[menu]').hide();
                    return false;
                });

            parentSegment.find('.common-icd-item-clear-all')
                .off('click.common-icd-item-clear-all')
                .on('click.common-icd-item-clear-all', function () {
                    let table = $(this).closest('.nrc-icds').find('table').first();
                    table.find('td input').val('');
                    $(this).closest('.on-hover-content').find('[menu]').hide();
                    return false;
                });
            parentSegment.find('.dx-data')
                .off('click.quick-add-icd')
                .on('click.quick-add-icd', function () {
                    let code = $.trim($(this).find('.dx-data-code').text()),
                        description = $.trim($(this).find('.dx-data-description').text()),
                        table = $(this).closest('.card-body').find('.nrc-icds').find('table').first(),
                        tr = null;
                    table.find('tbody>tr').each(function() {
                        if($.trim($(this).find('[icd-autocomplete-code]').first().val()) === '') {
                            tr = $(this);
                            return false;
                        }
                    });
                    if(tr) {
                        tr.find('[icd-autocomplete-code]').val(code);
                        tr.find('[icd-autocomplete-description]').val(description);
                    }
                    return false;
                });
            parentSegment.find('.dx-add-all')
                .off('click.quick-add-icd')
                .on('click.quick-add-icd', function () {
                    let table = $(this).closest('.card-body').find('.nrc-icds').find('table').first();
                    table.find('[icd-autocomplete-code], [icd-autocomplete-description]').val('');
                    $(this).closest('.dx-items').find('.dx-data').each(function() {
                        let code = $.trim($(this).find('.dx-data-code').text()),
                            description = $.trim($(this).find('.dx-data-description').text()),
                            tr = null;
                        table.find('tbody>tr').each(function() {
                            if($.trim($(this).find('[icd-autocomplete-code]').first().val()) === '') {
                                tr = $(this);
                                return false;
                            }
                        });
                        if(tr) {
                            tr.find('[icd-autocomplete-code]').val(code);
                            tr.find('[icd-autocomplete-description]').val(description);
                        }
                    });
                    if($(this).is('[save]')) {
                        $(this).closest('.card-body').find('.nrc-icds').find('button[submit]').trigger('click');
                    }
                    return false;
                });
        }
        addMCInitializer('note-resolve-{{$note->uid}}', init, '#note-resolve-{{$note->uid}}');
        addMCHook('onICDUpdate-{{$note->uid}}', function() {
            toastr.success('ICDs updated');
            fastReload(); // needed to ensure that the note rendered picks the new icds and uses them for create-claim
        });
    }).call(window);
</script>