<?php
/** @var App\Models\Note $note */
/** @var App\Models\Pro $pro */
/** @var App\Models\Section $section */
/** @var $allSections */
?>
@extends ('layouts.patient')

@section('inner-content')

    <?php
    $hasBills = false;
    if($note->bills->count()) {
        foreach ($note->bills as $bill) {
            if(!$bill->is_cancelled) {
                $hasBills = true;
                break;
            }
        }
    }
    ?>

    <div class="pt-2 pb-3 d-flex align-items-start">
        <h6 class="my-0 text-secondary d-flex align-items-start w-100">
            <a href="/patients/view/{{ $patient->uid }}/notes" class="small text-decoration-none mr-3">
                <i class="fa fa-chevron-left"></i>
            </a>
            <div class="mr-auto">
                <span class="text-dark font-weight-bold">Note
                    <span class="text-secondary font-weight-normal">{{ $note->is_cancelled ? '(CANCELLED)' : '' }}</span>
                </span>
            </div>
            @if($patient->has_mcp_done_onboarding_visit !== 'YES')
                <div class="ml-auto">
                    <div moe relative>
                        <a start show class="font-weight-bold">Mark as Onboarding Visit Note</a>
                        <form url="/api/client/updateMcpOnboardingVisitInfo" class="mcp-theme-1" right>
                            <input type="hidden" name="uid" value="{{$patient->uid}}">
                            <input type="hidden" name="mcpOnboardingVisitNoteUid" value="{{$note->uid}}">
                            <input type="hidden" name="hasMcpDoneOnboardingVisit" value="YES">
                            <input type="hidden" name="mcpOnboardingVisitDate" value="{{$note->effective_dateest}}">
                            <p class="min-width-200px">Mark this patient's onboarding as completed using this note?</p>
                            <div>
                                <button submit class="btn btn-sm btn-success mr-1">Yes</button>
                                <button cancel class="btn btn-sm btn-default border">No</button>
                            </div>
                        </form>
                    </div>

                </div>
            @endif
        </h6>
    </div>

    <div class="card mb-0 {{ $note->is_cancelled ? 'cancelled-item' : '' }}">
        <div class="card-header d-flex align-items-start px-3 py-2 border-bottom">
            <div class="pr-2">
                {{$note->title}}
                @if(!$note->is_signed_by_hcp)
                <div moe>
                    <a href="" show start><i class="fa fa-edit"></i></a>
                    <form url="/api/note/putTitle">
                        <input type="hidden" name="uid" value="{{$note->uid}}">
                        <div class="mb-2">
                            <input type="text" name="title" value="{{$note->title}}" class="form-control form-control-sm"
                                   placeholder="Title">
                        </div>
                        <div class="form-group mb-0">
                            <button class="btn btn-primary btn-sm" submit>Submit</button>
                            <button class="btn btn-default border btn-sm" cancel>Cancel</button>
                        </div>
                    </form>
                </div>
                @endif
            </div>
            <div class="px-2 border-left border-right">
                <div class="d-flex">
                    <span class="mr-2">{{friendly_date_time($note->effective_dateest, false, '')}}</span>
                    @if(!$note->is_signed_by_hcp)
                    <span moe class="ml-auto">
                        <a href="" show start><i class="fa fa-calendar"></i></a>
                        <form url="/api/note/putEffectiveDateEST">
                            <input type="hidden" name="uid" value="{{$note->uid}}">
                            <div class="mb-2">
                                <label for="" class="text-secondary text-sm">Effective date EST</label>
                                <input type="date" name="effectiveDateEST" value="{{$note->effective_dateest}}" class="form-control form-control-sm">
                            </div>
                            <div class="mb-0">
                                <button class="btn btn-primary btn-sm" submit>Submit</button>
                                <button class="btn btn-default border btn-sm" cancel>Cancel</button>
                            </div>
                        </form>
                    </span>
                    @endif
                </div>
                <div class="d-flex">
                    <span class="mr-2">{{friendly_time($note->effective_time, '')}}</span>
                    @if(!$note->is_signed_by_hcp)
                    <span moe class="ml-auto">
                        <a href="" show start><i class="fa fa-clock"></i></a>
                        <form url="/api/note/putEffectiveTime">
                            <input type="hidden" name="uid" value="{{$note->uid}}">
                            <div class="mb-2">
                                <label for="" class="text-secondary text-sm">Effective time </label>
                                <input type="time" name="effectiveTime" value="{{ date("H:i", strtotime($note->effective_time)) }}" class="form-control form-control-sm">
                            </div>
                            <div class="mb-0">
                                <button class="btn btn-primary btn-sm" submit>Submit</button>
                                <button class="btn btn-default border btn-sm" cancel>Cancel</button>
                            </div>
                        </form>
                    </span>
                    @endif
                </div>
            </div>

            <div class="px-2">
                <div class="d-flex">
                    <span class="mr-2"><span class="text-secondary">HCP:</span> {{$note->hcpPro->name_display}}</span>
                    @if(!$note->is_signed_by_hcp)
                    <div moe class="ml-auto">
                        <a href="" show start><i class="fa fa-edit"></i></a>
                        <form url="/api/note/putHcp">
                            <input type="hidden" name="uid" value="{{$note->uid}}">
                            <div class="mb-2">
                                <select name="hcpProUid" class="form-control form-control-sm">
                                    <option value="">-- Select HCP Pro --</option>
                                    @foreach ($pros as $iPro)
                                        <option value="{{$iPro->uid}}" {{ $note->hcpPro && $iPro->id === $note->hcpPro->id ? 'selected' : '' }}>{{$iPro->name_display}}</option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="mb-0">
                                <button class="btn btn-primary btn-sm" submit>Submit</button>
                                <button class="btn btn-default border btn-sm" cancel>Cancel</button>
                            </div>
                        </form>
                    </div>
                    @endif
                </div>
            </div>
            <div class="ml-auto d-flex align-items-start">
                <div class="pr-2">
                    <div>
                        @if($note->is_signed_by_hcp)
                            <span class="text-secondary">
                        <i class="fa fa-check"></i>
                        HCP Signed
                    </span>
                        @else
                            <div moe
                                 class="{{ $note->hcp_pro_id !== $pro->id ? 'moe-disabled' : '' }}"
                                 title="{{ $note->hcp_pro_id !== $pro->id ? 'Only the note\'s HCP can sign' : '' }}">
                                <a class="" href="" show start>Sign as HCP</a>
                                <form url="/api/note/signAsHcp">
                                    <input type="hidden" name="uid" value="{{$note->uid}}">
                                    <p>Sign this note as HCP?</p>
                                    <div class="mb-0">
                                        <button class="btn btn-success btn-sm" submit>Sign</button>
                                        <button class="btn btn-default border btn-sm" cancel>Cancel</button>
                                    </div>
                                </form>
                            </div>
                        @endif
                    </div>
                </div>
                <div class="pl-2 border-left">
                    <div class="d-flex justify-content-end">
                        <div moe relatve class="">
                            <a class="" href="" show start>Create Bill</a>
                            <form url="/api/bill/createForNote" right>
                                <input type="hidden" name="noteUid" value="{{$note->uid}}">
                                <div class="mb-2">
                                    <label for="" class="text-secondary text-sm">Effective Date</label>
                                    <input type="date" name="effectiveDate" class="form-control form-control-sm" value="{{date('Y-m-d')}}" required>
                                </div>
                                <div class="mb-2">
                                    <select autofocus class="form-control" name="code">
                                        <option value="">-- Select Code --</option>
                                        <?php $noteRates = $pro->noteRates(); ?>
                                        @if($noteRates && count($noteRates))
                                            @foreach($noteRates as $noteRate)
                                                <option value="{{ $noteRate->code }}">{{ $noteRate->code }}</option>
                                            @endforeach
                                        @endif
                                    </select>
                                </div>
                                <div class="mb-2">
                                    <input type="text" name="reason1" placeholder="Reason 1" class="form-control form-control-sm">
                                </div>
                                <div class="mb-2">
                                    <input type="text" name="reason2" placeholder="Reason 2" class="form-control form-control-sm">
                                </div>
                                <div class="">
                                    <button class="btn btn-primary btn-sm" submit>Submit</button>
                                    <button class="btn btn-default border btn-sm" cancel>Cancel</button>
                                </div>
                            </form>
                        </div>
                    </div>
                    <div class="d-flex justify-content-end">
                        @if(!$note->is_cancelled)
                        <div moe relatve
                             class="{{ $hasBills ? 'moe-disabled' : '' }}"
                             title="{{ $hasBills ? 'Cannot cancel note since it has un-cancelled bills in it' : '' }}">
                            <a class="text-danger" href="" show start>Cancel Note</a>
                            <form url="/api/note/cancel" right>
                                <input type="hidden" name="uid" value="{{$note->uid}}">
                                <p class="small mb-2">Are you sure you want to cancel this note?</p>
                                <div class="mb-2">
                                    <textarea name="memo" id="" cols="30" rows="5" placeholder="Memo" class="memo-textarea form-control form-control-sm"></textarea>
                                </div>
                                <div class="d-flex align-items-center">
                                    <button class="btn btn-sm btn-danger mr-2" submit>Yes</button>
                                    <button class="btn btn-sm btn-default mr-2 border" cancel>No</button>
                                </div>
                            </form>
                        </div>
                        @else
                            <span class="text-secondary font-weight-bold">CANCELLED</span>
                        @endif
                    </div>
                </div>
            </div>
        </div>
        <div class="card-body p-0">
            <div>
                <div class="mb-3">
                    <div>
                        <?php
                        $shortcuts = $pro->shortcuts;
                        $packed = [];
                        foreach ($shortcuts as $shortcut) {
                            $packed[] = $shortcut->shortcut . '|||' . $shortcut->text;
                        }
                        $packed = implode("^^^", $packed);
                        $shortcuts = $packed;
                        ?>
                        @foreach($note->sections as $section)
                        <div class="p-3 border-bottom note-section">
                            <div class="d-flex align-items-start">
                                <a class="font-weight-bold mb-2 d-flex align-items-center c-pointer">
                                    {{$section->sectionTemplate->title}}
                                    <span class="d-none if-not-edit"><i class="fa fa-edit ml-2"></i></span>
                                    <span class="edit-trigger"></span>
                                </a>
                                <?php $sectionInternalName = $section->sectionTemplate->internal_name; ?>
                                @if($sectionInternalName === "exam" || $sectionInternalName === "objective")
                                    @include('app/patient/note/_templates-exam-index')
                                @else
                                    @include('app/patient/note/_templates-index')
                                @endif
                                <?php
                                if(file_exists(storage_path('sections/' . $sectionInternalName . '/actions.php'))) {
                                    include(storage_path('sections/' . $sectionInternalName . '/actions.php'));
                                }
                                ?>
                                <?php
                                if(file_exists(storage_path('sections/' . $sectionInternalName . '/actions.blade.php'))) {
                                    ?> @include('sections/' . $sectionInternalName . '/actions') <?php
                                }
                                ?>
                                <a href="#" class="d-none text-danger if-edit ml-auto remove-section-trigger"
                                   data-uid="{{$section->uid}}"
                                   title="Remove {{$section->sectionTemplate->title}}">
                                    Remove {{$section->sectionTemplate->title}}
                                </a>
                            </div>
                            <div class="d-none if-not-edit  inset-comment">{!! !empty($section->summary_html) ? $section->summary_html : '-' !!}</div>
                            <div class="d-none if-edit">@include('sections/'.$section->sectionTemplate->internal_name.'/form')</div>
                        </div>
                        @endforeach
                    </div>
                </div>

                @if($note->bills->count())
                    <div class="mt-2 px-3">
                        <p class="font-weight-bold mb-2 text-secondary">Bills</p>
                        <table class="table table-sm tabe-striped mb-3 border-left border-right border-bottom">
                            <thead class="bg-light">
                            <tr>
                                <th class="border-bottom-0 w-25 pl-3">Code</th>
                                <th class="border-bottom-0 w-25 pl-2">Reason</th>
                                <th class="border-bottom-0 w-25 pl-2">Amount</th>
                                <th class="border-bottom-0"></th>
                            </tr>
                            </thead>
                            <tbody>
                            @foreach ($note->bills as $bill)
                                <tr>
                                    <td class="pl-3 {{ $bill->is_cancelled ? 'text-secondary' : '' }}">{{$bill->code}}</td>
                                    <td class="pl-2">
                                        {{ $bill->reason1 }}
                                        <div class="text-secondary small">{{ $bill->reason2 }}</div>
                                    </td>
                                    <td class="pl-2">
                                        @if($bill->has_hcp_been_paid)
                                            <span class="text-dark">Received:</span><span class="font-weight-bold text-success ml-2">${{ $bill->hcp_payment_amount }}</span>
                                        @else
                                            <span class="text-dark">Expected:</span><span class="font-weight-bold text-dark ml-2">{{ $bill->hcp_expected_payment_amount ? '$' . $bill->hcp_expected_payment_amount : '-' }}</span>
                                        @endif
                                    </td>
                                    <td>
                                        <div class="">
                                            @if(!$bill->is_cancelled)
                                                @if($bill->is_signed_by_hcp)
                                                    <div class="d-block text-secondary">
                                                        <i class="fa fa-check"></i>
                                                        HCP Signed
                                                    </div>
                                                @else
                                                    <div moe
                                                         class="d-block {{ $bill->hcp_pro_id !== $pro->id ? 'moe-disabled' : '' }}"
                                                         title="{{ $bill->hcp_pro_id !== $pro->id ? 'Only the bill\'s HCP can sign' : '' }}">
                                                        <a class="" href="" show start>Sign as HCP</a>
                                                        <form url="/api/bill/signAsHcp">
                                                            <input type="hidden" name="uid" value="{{$bill->uid}}">
                                                            <p>Sign this bill as HCP?</p>
                                                            <div class="mb-0">
                                                                <button class="btn btn-success btn-sm" submit>Sign</button>
                                                                <button class="btn btn-default border btn-sm" cancel>Cancel</button>
                                                            </div>
                                                        </form>
                                                    </div>
                                                @endif
                                            @endif
                                            @if($bill->is_cancelled)
                                                <div class="d-block text-secondary">
                                                    Cancelled
                                                </div>
                                            @else
                                                <div class="d-block" moe>
                                                    <a class="text-danger" href="" show start>Cancel</a>
                                                    <form url="/api/bill/markCancelled">
                                                        <input type="hidden" name="uid" value="{{$bill->uid}}">
                                                        <p>Cancel this bill?</p>
                                                        <div class="mb-0">
                                                            <button class="btn btn-danger btn-sm" submit>Yes</button>
                                                            <button class="btn btn-default border btn-sm" cancel>No</button>
                                                        </div>
                                                    </form>
                                                </div>
                                            @endif
                                        </div>
                                    </td>
                                </tr>
                            @endforeach
                            </tbody>
                        </table>
                    </div>
                @else
                    <div class="my-3 px-3 d-flex">
                        <p class="font-weight-bold mb-0 text-secondary">No bills in this note</p>
                        <span class="mx-2 text-secondary">|</span>
                        <span moe class="">
                            <a class="" href="" show start>Create Bill</a>
                            <form url="/api/bill/createForNote">
                                <input type="hidden" name="noteUid" value="{{$note->uid}}">
                                <div class="mb-2">
                                    <label for="" class="text-secondary text-sm">Effective Date</label>
                                    <input type="date" name="effectiveDate" class="form-control form-control-sm" value="{{date('Y-m-d')}}" required>
                                </div>
                                <div class="mb-2">
                                    <select autofocus class="form-control" name="code">
                                        <option value="">-- Select Code --</option>
                                        <?php $noteRates = $pro->noteRates(); ?>
                                        @if($noteRates && count($noteRates))
                                            @foreach($noteRates as $noteRate)
                                                <option value="{{ $noteRate->code }}">{{ $noteRate->code }}</option>
                                            @endforeach
                                        @endif
                                    </select>
                                </div>
                                <div class="mb-2">
                                    <input type="text" name="reason1" placeholder="Reason 1" class="form-control form-control-sm">
                                </div>
                                <div class="mb-2">
                                    <input type="text" name="reason2" placeholder="Reason 2" class="form-control form-control-sm">
                                </div>
                                <div class="">
                                    <button class="btn btn-primary btn-sm" submit>Submit</button>
                                    <button class="btn btn-default border btn-sm" cancel>Cancel</button>
                                </div>
                            </form>
                        </span>
                    </div>
                @endif
            </div>
        </div>
    </div>
    <div class="note-templates-underlay"></div>
    <script>
        (function() {
            function init() {
                $('textarea[rte]').each(function() {

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

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

                    var ti = $('<input type="hidden" />')
                        .val(this.value)
                        .attr('name', this.name)
                        .insertBefore(this);
                    var ce = $('<div data-editor-id="' + editorID + '" data-field="' + this.name + '"/>')
                        .html(this.value)
                        .insertBefore(this);
                    $(this).remove();

                    var qe = new Quill('[data-editor-id="' + editorID + '"]', {
                        theme: 'snow',
                        modules: {
                            keyboard: {
                                bindings: {
                                    handleEnter: {
                                        key: 13,
                                        handler: function() {
                                            if(!$('.stag-shortcuts:visible').length) return true;
                                        }
                                    }
                                }
                            }
                        }
                    });
                    var toolbar = $(qe.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);

                    qe.on('text-change', function() {
                        ti.val(qe.root.innerHTML);
                    });

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

                });

                $('.edit-trigger')
                    .off('click.edit-trigger')
                    .on('click.edit-trigger', function() {
                        let editParent = $(this).closest('.note-section');
                        editParent.toggleClass('edit');
                        if(editParent.is('.edit')) {
                            editParent.siblings('.edit').removeClass('edit');
                            if(editParent.find('[contenteditable]').length) {
                                editParent.find('[contenteditable]').first().focus();
                            }
                            else {
                                editParent.find('textarea:visible').first().focus();
                            }
                        }
                        return false;
                    });

                $('.note-templates-trigger')
                    .off('click.note-templates-trigger')
                    .on('click.note-templates-trigger', function() {
                        $('.note-templates-underlay').show();
                        let container = $(this).closest('.note-section').find('.note-template-container');
                        container.find('.note-template-children').hide();
                        container.find('.note-template-item.selected').removeClass('selected');
                        container.find('.note-template-item[prefix]').removeAttr('prefix');
                        container.find('input[type="checkbox"]').prop('checked', false);
                        container.find('.note-template-output-text').empty();
                        container.show();
                        loadTemplateSet(container.find('.note-template-set-chooser'));
                        loadExamTemplateSet(container.find('.note-exam-template-set-chooser'),
                            container.find('.note-exam-exam-chooser').val(),
                            container.find('.note-exam-template-set-chooser').val());
                        return false;
                    });

                $(document)
                    .off('click.note-templates-underlay', '.note-templates-underlay, .note-template-close-trigger')
                    .on('click.note-templates-underlay', '.note-templates-underlay, .note-template-close-trigger', function() {
                        $('.note-templates-underlay').hide();
                         $('.note-template-container').hide();
                    });

                $(document)
                    .off('click.note-template-label', '.note-template-item .label')
                    .on('click.note-template-label', '.note-template-item .label', function() {
                        let item = $(this).closest('.note-template-item');
                        let isChecked = $(this).find('>input[type="checkbox"]').prop('checked');
                        let hasChildren = !!item.find('>.note-template-children').length,
                            childrenShown = item.find('>.note-template-children:visible').length;

                        if(isChecked && hasChildren && !childrenShown) { // just show
                            $('.note-template-children').hide();
                            $(this).parents('.note-template-children').show();
                            item.find('>.note-template-children').show()
                                .find('>textarea,>input[type="number"],>input[type="date"]').first().focus();
                            return false;
                        }

                        $(this).find('>input[type="checkbox"]').prop('checked', !isChecked);
                        isChecked = !isChecked;
                        if(isChecked) {
                            item.addClass('selected');
                        }
                        else {
                            item.removeClass('selected');
                        }
                        $('.note-template-children').hide();
                        $(this).parents('.note-template-children').show();
                        if(isChecked) {
                            item.find('>.note-template-children')
                                .show()
                                .find('>textarea,>input[type="number"],>input[type="date"]')
                                .first().focus();
                        }

                        generateTemplateOutput();

                        return false;
                    });

                $(document)
                    .off('mousedown.note-templates-apply', '.note-template-apply-trigger')
                    .on('mousedown.note-templates-apply', '.note-template-apply-trigger', function() {
                        let result = $('.note-template-output-text:visible').first().html();
                        $('.note-templates-underlay').hide();
                        $('.note-template-container').hide();
                        let editor  = $('.ql-editor[contenteditable]:visible').first();
                        result = $.trim(editor.text() !== '' ? editor.html() : '') + result;
                        editor.html(result).focus();
                        return false;
                    });

                $(document)
                    .off('input paste change', '.note-template-item textarea, .note-template-item input[type="number"], .note-template-item input[type="date"]')
                    .on('input paste change', '.note-template-item textarea, .note-template-item input[type="number"], .note-template-item input[type="date"]', function() {
                        generateTemplateOutput();
                    });

                $(document)
                    .off('click.plus-trigger', '.note-template-item .plus-trigger')
                    .on('click.plus-trigger', '.note-template-item .plus-trigger', function() {
                        let item = $(this).closest('.note-template-item');
                        if(item.attr('prefix') === '(+)') {
                            item.removeAttr('prefix');
                            item.find('>.note-template-text>.label>input[type="checkbox"]').prop('checked', false);
                            item.removeClass('selected');
                        }
                        else {
                            item.attr('prefix', '(+)');
                            item.find('>.note-template-text>.label>input[type="checkbox"]').prop('checked', true);
                            item.addClass('selected');
                        }
                        generateTemplateOutput();
                        return false;
                    });

                $(document)
                    .off('click.minus-trigger', '.note-template-item .minus-trigger')
                    .on('click.minus-trigger', '.note-template-item .minus-trigger', function() {
                        let item = $(this).closest('.note-template-item');
                        if(item.attr('prefix') === '(-)') {
                            item.removeAttr('prefix');
                            item.find('>.note-template-text>.label>input[type="checkbox"]').prop('checked', false);
                            item.removeClass('selected');
                        }
                        else {
                            item.attr('prefix', '(-)');
                            item.find('>.note-template-text>.label>input[type="checkbox"]').prop('checked', true);
                            item.addClass('selected');
                        }
                        generateTemplateOutput();
                        return false;
                    });

                $(document)
                    .off('change.note-template-set-chooser', '.note-template-set-chooser')
                    .on('change.note-template-set-chooser', '.note-template-set-chooser', function() {
                        return loadTemplateSet($(this));
                    });

                $(document)
                    .off('change.note-exam-template-set-chooser', '.note-exam-template-set-chooser')
                    .on('change.note-exam-template-set-chooser', '.note-exam-template-set-chooser', function() {
                        $(this).closest('.note-template-container')
                            .find('.note-exam-exam-chooser')
                                .val($(this).find('option:selected').attr('exam'));
                        return loadExamTemplateSet($(this),
                            $(this).closest('.note-template-container').find('.note-exam-exam-chooser').first().val(),
                            $(this).val());
                    });

                $(document)
                    .off('change.note-exam-exam-chooser', '.note-exam-exam-chooser')
                    .on('change.note-exam-exam-chooser', '.note-exam-exam-chooser', function() {
                        return loadExamTemplateSet($(this),
                            $(this).val(),
                            $(this).closest('.note-template-container').find('.note-exam-template-set-chooser').first().val());
                    });

                $('.remove-section-trigger').click(function() {
                    $.post('/api/section/deactivate', {
                        uid: $(this).attr('data-uid'),
                        memo: 'Deactivated from note',
                    }, function(_data) {
                        if(_data) {
                            if(_data.success) {
                                fastReload();
                            }
                            else {
                                toastr.error(_data.message);
                            }
                        }
                        else {
                            toastr.error('Unable to remove section!');
                        }
                    }, 'json');
                    // $(this).closest('.note-section').removeClass('edit');
                    return false;
                });

                $(document)
                    .off('mousedown.enable-edit', '.note-section:not(.edit)')
                    .on('mousedown.enable-edit', '.note-section:not(.edit)', function(e) {
                        e.stopPropagation();
                        e.preventDefault();
                        $(this).find('.edit-trigger').first().click();
                        return false;
                    });

            }

            function loadTemplateSet(_chooser) {
                if(!_chooser.length || !_chooser.val()) return false;
                let container = _chooser.closest('.note-template-container');
                container.find('>.note-template-item').remove();
                container.find('.please-wait').remove();
                container.append('<p class="please-wait my-2 text-secondary text-center">Please wait ...</p>');
                $.get('/note-template-set/' + _chooser.attr('data-section') + '/' + _chooser.val(), function(_html) {
                    container.find('.please-wait').remove();
                    container.append(_html);
                });
                return false;
            }

            function loadExamTemplateSet(_chooser, _exam, _templateSet) {
                if(!_chooser.length || !_chooser.val()) return false;
                let container = _chooser.closest('.note-template-container');
                container.find('>.note-template-item').remove();
                container.find('.please-wait').remove();
                container.append('<p class="please-wait my-2 text-secondary text-center">Please wait ...</p>');
                $.get('/note-template-set/exam/' + _exam + '/' + _templateSet, function(_html) {
                    container.find('.please-wait').remove();
                    container.append(_html);
                });
                return false;
            }

            function generateOutputForNode(_node) {
                let template = (_node.attr('prefix') ? _node.attr('prefix') : '') + _node.attr('template'),
                    value = template;
                if(value.indexOf('{text}') !== -1) {
                    value = value.replace('{text}',
                        _node
                            .find('>.note-template-children')
                                .find('>textarea,>input[type="number"],>input[type="date"]').first().val());
                }
                else if(value.indexOf('{children}') !== -1) {
                    let values = [];
                    _node.find('>.note-template-children>.note-template-item.selected').each(function() {
                        values.push(generateOutputForNode($(this)));
                    });
                    let combined = '';
                    for (let i = 0; i < values.length; i++) {
                        combined += values[i];
                        if(values.length > 1 && i <= values.length - 2) {
                            if(i === values.length - 2) {
                                combined += ' and ';
                            }
                            else {
                                combined += ', ';
                            }
                        }
                    }
                    value = value.replace('{children}', combined);
                }
                return value;
            }

            function generateTemplateOutput() {
                let container = $('.note-template-container:visible').first();
                if(!container.length) return '';
                let lines = [];
                container.find('>.note-template-item.selected').each(function() {
                    lines.push('<p class="note-template-output-line">' + generateOutputForNode($(this)) + '</p>');
                });
                $('.note-template-output-text:visible').first().html(lines.join(''));
            }

            addMCInitializer('note-single', init);
        })();
    </script>
@endsection

@section('left-nav-content')
    <div class="left-nav-content" id="note-sections-app">
        <div class="note-widget-title px-2 py-1">Note Sections</div>
        <input type="search" class="d-block w-100 border-0 outline-0 px-2 py-1"
               v-model="q" placeholder="Filter">
        <div class="border-top py-1">
            <div v-for="section in sections"
                 v-show="section.title.toLowerCase().indexOf(q.toLowerCase()) !== -1">
                <div class="d-flex pr-1 align-items-center note-widget-item c-pointer"
                     :title="section.title + ' - Click to remove'"
                     v-if="section.used"
                     v-on:click.once="remove(section.section_uid)">
                    <span class="mx-2">
                        <a class="font-12 text-secondary" href="#">
                            <i class="fa fa-minus-circle"></i>
                        </a>
                    </span>
                    <span class="font-smaller text-ellipsis">
                        @{{section.title}}
                    </span>
                </div>
                <div class="d-flex pr-1 align-items-center note-widget-item c-pointer"
                     :title="section.title + ' - Click to add'"
                     v-if="!section.used"
                     v-on:click.once="add(section.uid, section.internal_name)">
                    <span class="mx-2">
                        <a class="font-12" href="#">
                            <i class="fa fa-plus-circle"></i>
                        </a>
                    </span>
                    <span class="font-smaller text-ellipsis">
                        @{{section.title}}
                    </span>
                </div>
            </div>
        </div>
    </div>
    <script>
        (function() {
            function initSectionsWidget() {
                var allSections = <?= json_encode($allSections) ?>;
                new Vue({
                    el: '#note-sections-app',
                    delimiters: ['@{{', '}}'],
                    data: {
                        q: '',
                        sections: allSections
                    },
                    methods: {
                        add: function(_uid, _section) {
                            $.get('/get-default-section-data/' + _section + '/{{$patient->uid}}' , function(_data) {
                                $.post('/api/section/create', {
                                    noteUid: '{{$note->uid}}',
                                    summaryHtml: _data.summary,
                                    contentData: JSON.stringify({value: _data.value}),
                                    sectionTemplateUid: _uid,
                                }, function(_data) {
                                    if(_data) {
                                        if(_data.success) {
                                            fastReload();
                                        }
                                        else {
                                            toastr.error(_data.message);
                                        }
                                    }
                                    else {
                                        toastr.error('Unable to add section!');
                                    }
                                }, 'json');
                            }, 'json');
                        },
                        remove: function(_uid) {
                            $.post('/api/section/deactivate', {
                                uid: _uid,
                                memo: 'Deactivated from note',
                            }, function(_data) {
                                if(_data) {
                                    if(_data.success) {
                                        fastReload();
                                    }
                                    else {
                                        toastr.error(_data.message);
                                    }
                                }
                                else {
                                    toastr.error('Unable to remove section!');
                                }
                            }, 'json');
                        }
                    }
                });

                $('div[embed]').each(function() {
                    $(this).load($(this).attr('embed'));
                });
            }
            addMCInitializer('sections-widget', initSectionsWidget);
        })();
    </script>
@endsection
