<?php

use App\Models\Point;
use App\Models\Client;
use App\Models\Note;
use App\Models\Segment;

/** @var Client $patient */
/** @var Note $note */
/** @var $summaryView */

if(!@$goals || !@$counts) {
    list($goals, $counts) = Point::getPointsOfCategoryExtended($patient, 'GOAL', $note, !!@$summaryView);
}
?>

<div @if(!@$summaryView) class="mt-3 p-3 border-top" id="goals-center-{{$note->id}}" @else class="mt-2 pr-2" @endif>
    <div class="point-table-container">

        <table class="table table-sm table-bordered bg-white mb-2 point-table read">
            <thead>
            <tr class="">
                @if($patient->core_note_id !== $note->id)
                    <th class="border-bottom-0 text-secondary text-center width-35px text-nowrap pr-1">Rel.</th>
                @endif
                <th class="border-bottom-0 text-secondary">Goal</th>
                <th class="border-bottom-0 text-secondary w-30">Subjective</th>
                <th class="border-bottom-0 text-secondary w-30">Plan</th>
                @if(!@$summaryView) <th class="border-bottom-0 text-secondary width-30px"></th> @endif
            </tr>
            </thead>
            <?php $prevRowState = -1; ?>
            <?php
            $segment = $note->coreSegment; // getSegmentByInternalName('intake_allergies');
            // if(!$segment) $segment = $note->getSegmentByInternalName('allergies');
            // if(!$segment) $segment = $note->coreSegment;
            ?>
            <?php foreach($goals as $goal): ?>
            <?php $point = $goal; ?>
            @if($prevRowState !== $goal->state)
                @include('app.patient.wizard-partials.state-row', ['point' => $goal])
            @endif
            <?php $prevRowState = $goal->state; ?>
            <?php $rel = $goal->note_point_uid; ?>
            <tr class="{{$rel ? 'relevant-to-visit' : ''}} point-row"
                data-uid="{{$goal->uid}}"
                data-name-base64="{{!!@($goal->data->goal) ? base64_encode($goal->data->goal) : ''}}"
                data-is-removed="{{$goal->is_removed ? 1 : 0}}"
                data-is-removed-due-to-entry-error="{{$goal->is_removed_due_to_entry_error ? 1 : 0}}">
                @if($patient->core_note_id !== $note->id)
                    @include('app.patient.wizard-partials.relevance-column-optimized', ['point' => $point])
                @endif
                <td>
                    <div class="d-flex align-items-start">
                        @include('app.patient.wizard-partials.state-icon', ['point' => $goal])
                        <div>
                            @if(!@$summaryView)
                            <div moe huge relative>
                                <a start show href="#" title="Edit"><?= !!@($goal->data->goal) ? @($goal->data->goal) : '-' ?></a>
                                <form url="/api/visitPoint/updateTopLevel" no-auto-focus class="mcp-theme-1 frm-edit-goal">
                                    <input type="hidden" name="uid" value="<?= $goal->uid ?>">
                                    <input type="hidden" name="noteUid" value="<?= $note->uid ?>">
                                    <p class="mb-2"><b>Update Goal</b></p>

                                    <input type="hidden" name="data" value='{{json_encode($goal->data)}}'>

                                    @if($goal->added_in_note_id !== $note->id)

                                        <div class="mb-2 bg-light p-2 border">
                                            <p class="mb-1 font-weight-bold">
                                                {{ @$goal->data->goal }}
                                            </p>
                                            @if($patient->core_note_id !== $note->id)
                                                <div class="text-secondary">This goal was added outside of this visit.
                                                    <a href="#" class="update-core-data ml-2">
                                                        <i class="fa fa-edit on-hover-opaque"></i>
                                                        Update
                                                    </a>
                                                </div>
                                            @endif
                                        </div>

                                    @endif

                                    <div class="mb-2 {{$goal->added_in_note_id === $note->id ? '' : 'd-none'}}" if-core-data-edit-confirmed>

                                        <div class="mb-2">
                                            <label class="text-sm mb-1 font-weight-bold">Goal</label>
                                            <input type="text" class="form-control form-control-sm min-width-unset"
                                                   data-name="goal"
                                                   value="{{@$goal->data->goal}}">
                                        </div>

                                    </div>

                                    @include('app.patient.wizard-partials.common-fields-optimized', ['label' => 'goal', 'point' => $goal])

                                    <div class="mt-3 pt-2 d-flex align-items-center border-top">
                                        <button type="submit" class="btn-save-goal btn btn-sm btn-primary mr-2">Save</button>
                                        <button cancel class="btn btn-sm bg-light btn-default border">Cancel</button>
                                    </div>
                                </form>
                            </div>
                            @else
                                <?= !!@($goal->data->goal) ? @($goal->data->goal) : '-' ?>
                            @endif

                            @include('app.patient.wizard-partials.state-badge', ['point' => $goal, 'addedVerb' => 'Prescribed'])
                        </div>
                    </div>
                </td>
                <td>
                    <div if-read-mode>
                        <div class="d-flex align-items-start position-relative">
                            <div class="flex-grow-1">
                                <?php
                                $point = $goal;
                                include resource_path('views/app/patient/segment-templates/_child_review/last-review-optimized.php');
                                ?>
                            </div>
                            @if(!@$summaryView)
                            <div class="d-inline-flex ml-1">
                                <a class="px-1 view-review-log"
                                   native target="_blank"
                                   open-in-stag-popup
                                   popup-style="stag-popup-md"
                                   title="Subjective log<?= !!@($goal->data->goal) ? ' for ' . @($goal->data->goal) : '' ?>"
                                   href="/point/review-log/<?= $goal->uid ?>?popupmode=1">
                                    <i class="fa fa-history"></i>
                                </a>
                                <?php
                                if($segment) {
                                    include resource_path('views/app/patient/segment-templates/_child_review/edit-review-optimized.php');
                                }
                                ?>
                            </div>
                            @endif
                        </div>
                    </div>
                    <div if-edit-mode>
                        <?php
                        if($segment) {
                            include resource_path('views/app/patient/segment-templates/_child_review/edit-review-in-place-optimized.php');
                        }
                        ?>
                    </div>
                </td>
                <td>
                    <div if-read-mode>
                        <div class="d-flex align-items-start position-relative">
                            <div class="flex-grow-1">
                                <?php
                                include resource_path('views/app/patient/segment-templates/_child_plan/last-plan-optimized.php');
                                ?>
                            </div>
                            @if(!@$summaryView)
                            <div class="d-inline-flex ml-1">
                                <a class="px-1 view-review-log"
                                   native target="_blank"
                                   open-in-stag-popup
                                   popup-style="stag-popup-md"
                                   title="Plan log<?= !!@($goal->data->goal) ? ' for ' . @($goal->data->goal) : '' ?>"
                                   href="/point/plan-log/<?= $goal->uid ?>?popupmode=1">
                                    <i class="fa fa-history"></i>
                                </a>
                                <?php
                                if($segment) {
                                    include resource_path('views/app/patient/segment-templates/_child_plan/edit-plan-optimized.php');
                                }
                                ?>
                            </div>
                            @endif
                        </div>
                    </div>
                    <div if-edit-mode>
                        <?php
                        if($segment) {
                            include resource_path('views/app/patient/segment-templates/_child_plan/edit-plan-in-place-optimized.php');
                        }
                        ?>
                    </div>
                </td>
                @if(!@$summaryView)
                <td>
                    <div class="position-relative c-pointer stag-tooltip">
                        <i class="fa fa-info-circle"></i>
                        <div class="position-absolute bg-white border rounded p-2 stag-tooltip-content">
                            <div class="text-nowrap small text-left">Started <b><?= !!@($goal->data->start_date) ? friendly_date($goal->data->start_date) : '-' ?></b></div>
                            @if(!!@($goal->data->prescriber))
                                <div class="text-sm text-left text-secondary">By: <?= !!@($goal->data->prescriber) ? @($goal->data->prescriber) : '-' ?></div>
                            @endif
                            <hr class="my-1">
                            <div class="text-nowrap small text-left text-left">Ended <b><?= !!@($goal->removal_effective_date) ? friendly_date($goal->removal_effective_date) : '-' ?></b></div>
                            @if(!!@($goal->data->prescriber))
                                <div class="text-sm text-secondary">By/Memo: <?= !!@($goal->removal_reason_memo) ? @($goal->removal_reason_memo) : '-' ?></div>
                            @endif
                        </div>
                    </div>
                </td>
                @endif
            </tr>
            <?php endforeach; ?>
        </table>

        @if(!@$summaryView)
        <div class="d-flex align-items-center">
            <div class="mt-1 w-100 border p-3 bg-aliceblue border-info rounded">

                <div class="d-flex align-items-baseline mb-3" tab-links="">
                    <a class="tab-link-active" href="#" tab-link="add-single">Add Single</a>
                    <a class="" href="#" tab-link="add-multiple-pre-existing">Add Multiple Pre-existing</a>
                </div>
                <div class="cm-tab" tab-key="add-single">

                <form action="/api/visitPoint/addTopLevel" class="mcp-theme-1 w-100" id="frm-add-goal" novalidate>
                    <input type="hidden" name="noteUid" value="<?= $note->uid ?>">
                    <input type="hidden" name="category" value="GOAL">
                    <input type="hidden" name="data">

                    <input type="hidden" name="isRemovedDueToEntryError" value="0">

                    <p class="mb-2"><b>Add Goal</b></p>

                    <div class="row">
                        <div class="col-9">
                            <div class="row mb-2">
                                <div class="col-12">

                                    <label class="text-sm mb-0 font-weight-bold">Goal</label>
                                    <input type="text"
                                           data-name="goal"
                                           class="form-control form-control-sm"
                                           required>
                                </div>
                            </div>

                            <?php $point = null; ?>
                            @include('app.patient.wizard-partials.common-fields-optimized', ['label' => 'goal'])

                        </div>
                        <div class="col-3 border-left">

                        </div>
                    </div>

                    <div class="d-flex align-items-center">
                        <button type="submit" class="btn btn-sm btn-primary mr-2">Save Goal</button>
                        <button type="button" class="btn btn-sm btn-default border-secondary bg-white border mr-2" onclick="return closeStagPopup()">Close</button>
                    </div>
                </form>

                </div>
                <div class="cm-tab d-none" tab-key="add-multiple-pre-existing">
                    @include('app.patient.wizard-partials.add-multiple-pre-existing', ['label' => 'goal', 'adder' => 'Added By'])
                </div>
            </div>
        </div>
        @endif
    </div>
</div>

@if(!@$summaryView)
<script>
    (function() {
        function init() {
            let parentSegment = $('#goals-center-{{$note->id}}');

            parentSegment.find('select[data-name="category"]')
                .off('change')
                .on('change', function() {
                    $(this).closest('form').find('.help-text').addClass('d-none');
                    $(this).closest('form').find('.help-text[data-category="' + this.value + '"]').removeClass('d-none');
                })
                .trigger('change');

            @include('app.patient.wizard-partials.common-script', ['label' => 'goal', 'segment_part' => 'goals', 'nameKey' => 'goal'])

            initSegmentMoes($('#goals-center-{{$note->id}}'));
            __initRTEs(parentSegment.find('[note-rte]:not(.ql-container)'));

            let mode = 'read';

            // custom buttons on title bar
            $('.button-container').remove();
            let buttonContainer = $('<div/>').addClass('button-container ml-4 mr-auto');
            let titleElem = $('#goals-center-{{$note->id}}').closest('.stag-popup').find('.stag-popup-title>span');
            titleElem.next().removeClass('ml-auto');
            titleElem.parent().addClass('align-items-center');

            // add button for "Edit Mode"
            $('.btn-toggle-edit-mode').remove();
            let button = $('<a href="#" native target="_blank" data-mode="read" ' +
                'class="btn-toggle-edit-mode btn btn-sm mr-2 btn-info text-white font-weight-bold shadow-none">Switch to Edit Mode</a>')
                .appendTo(buttonContainer);

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

            button
                .off('click.toggle-edit')
                .on('click.toggle-edit', function () {
                    if (mode === 'read') {
                        mode = 'edit';
                        $(this).text('Back to Read Mode');
                        $('#goals-center-{{$note->id}} .point-table').removeClass('read').addClass('edit');
                    } else {
                        let url = $(this).closest('.stag-popup').attr('stag-popup-key');
                        if(url.indexOf('forceReadMode') === -1) url += '&forceReadMode=1';
                        refreshDynamicStagPopup(url);
                    }
                    return false;
                });

            buttonContainer.insertAfter(titleElem);

        }
        addMCInitializer('goals-center-{{$note->id}}', init, '#goals-center-{{$note->id}}');
    }).call(window);
</script>
@endif
