<?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 */

$selfMonitoring = Point::getOnlyPointOfCategory($patient, 'SELF_MONITORING');
$foodTriggers = Point::getOnlyPointOfCategory($patient, 'FOOD_TRIGGERS');
$cravings = Point::getOnlyPointOfCategory($patient, 'CRAVINGS');
$sleepHabits = Point::getOnlyPointOfCategory($patient, 'SLEEP_HABITS');

$points = [
    ["category" => 'SELF_MONITORING', "name" => 'Self Monitoring', "point" => $selfMonitoring],
    ["category" => 'FOOD_TRIGGERS', "name" => 'Food Triggers', "point" => $foodTriggers],
    ["category" => 'CRAVINGS', "name" => 'Cravings', "point" => $cravings],
    ["category" => 'SLEEP_HABITS', "name" => 'Sleep Habits', "point" => $sleepHabits],
];
?>

<div @if(!@$summaryView) class="mt-3 p-3 border-top" id="behavior-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">

            @foreach($points as $p)
                <?php $point = $p['point']; ?>
                <?php $rel = $point ? $point->relevanceToNote($note) : false; ?>
                <tr class="{{$rel ? 'relevant-to-visit' : ''}} point-row" data-uid="{{$point ? $point->uid : ''}}">
                    @if($point && $patient->core_note_id !== $note->id)
                        @include('app.patient.wizard-partials.relevance-column', ['point' => $point])
                    @endif
                    <td>
                        <div class="d-flex align-items-center">
                            <b class="mr-2">{{$p['name']}}</b>
                            @if(!@$summaryView)
                            @if($p['category'] === 'CRAVINGS')
                                <img src="/img/behavior-rx/cravings.png" class="icon-nutrition-rx-row" alt="">
                            @elseif($p['category'] === 'SLEEP_HABITS')
                                <img src="/img/behavior-rx/sleep.png" class="icon-nutrition-rx-row" alt="">
                            @endif
                            @endif
                        </div>
                    </td>
                    <td class="w-40">
                        <div if-read-mode>
                            @if($point)
                                <?php
                                include resource_path('views/app/patient/segment-templates/_child_review/behavior/' . $p['category'] . '/last-review.php');
                                ?>
                            @else
                                -
                            @endif
                        </div>
                        <div if-edit-mode>
                            <?php
                            $segment = $note->getSegmentByInternalName('intake_behavior');
                            if(!$segment) $segment = $note->getSegmentByInternalName('behavior');
                            if(!$segment) $segment = $note->coreSegment;
                            if($segment) {
                                $currentValue = '';
                                $previousValue = '';
                                $previousChildReview = null;
                                if (@$point) {
                                    if ($point->lastChildReview && $point->last_child_review_point_scoped_note_id === $note->id) {
                                        $currentValue = json_decode($point->lastChildReview->data);
                                        $previousChildReview = \App\Models\Point::where('id', '<', $point->lastChildReview->id)
                                            ->where('category', 'REVIEW')
                                            ->where('parent_point_id', $point->id)
                                            ->orderBy('id', 'DESC')
                                            ->first();
                                        if($previousChildReview && $previousChildReview->data) {
                                            $previousValue = json_decode($previousChildReview->data);
                                        }
                                    }
                                    else {
                                        $previousChildReview = \App\Models\Point::where('parent_point_id', $point->id)
                                            ->where('category', 'REVIEW')
                                            ->orderBy('id', 'DESC')
                                            ->first();
                                        if($previousChildReview && $previousChildReview->data) {
                                            $previousValue = json_decode($previousChildReview->data);
                                        }
                                    }
                                }
                                ?>
                                <div visit-moe relative class="d-block">
                                    <form show url="/api/visitPoint/<?= $point ? 'upsertChildReview' : 'addTopLevel' ?>"
                                          class="mcp-theme-1 frm-review-plan-lifestyle frm-review-plan-behavior" right>

                                        @if($point)
                                            <input type="hidden" name="uid" value="<?= $point->uid ?>">
                                            <input type="hidden" name="segmentUid" value="<?= $segment->uid ?>">
                                            <input type="hidden" name="data">
                                        @else
                                            <input type="hidden" name="noteUid" value="<?= $note->uid ?>">
                                            <input type="hidden" name="category" value="<?= $p['category'] ?>">
                                            <input type="hidden" name="additionReasonCategory" value="ON_INTAKE">
                                            <input type="hidden" name="childReviewData">
                                        @endif

                                        @if($previousValue)
                                            <div class="mb-2">
                                                <div class="d-flex align-items-baseline mb-1">
                                                    <span class="text-sm text-secondary">Previous Subjective / <?= friendlier_date($previousChildReview->created_at) ?>)</span>
                                                </div>
                                                <div class="p-2 bg-light border inline-html-container">
                                                    <?php $review = $previousValue; ?>
                                                    <?php include(resource_path('views/app/patient/segment-templates/_child_review/behavior/' . $p['category'] . '/view-review.php')); ?>
                                                </div>
                                            </div>
                                        @endif
                                        <?php include resource_path('views/app/patient/segment-templates/_child_review/behavior/' . $p['category'] . '/edit-review.php'); ?>
                                    </form>
                                </div>
                                @if(!empty($currentValue))
                                    <?php include(resource_path('views/app/patient/segment-templates/_child_review/delete-review.php')); ?>
                                @endif
                                <?php
                            }
                            ?>
                        </div>
                    </td>
                    <td class="w-40">
                        <div if-read-mode>
                            @if($point)
                                <?php include resource_path('views/app/patient/segment-templates/_child_plan/behavior/' . $p['category'] . '/last-plan.php'); ?>
                            @else
                                -
                            @endif
                        </div>
                        <div if-edit-mode>
                            <?php
                            $segment = $note->getSegmentByInternalName('plan_behavior');
                            if(!$segment) $segment = $note->getSegmentByInternalName('behavior');
                            if(!$segment) $segment = $note->coreSegment;
                            if($segment) {
                                $currentValue = '';
                                $previousValue = '';
                                $previousChildPlan = null;
                                if (@$point) {
                                    if ($point->lastChildPlan && $point->last_child_plan_point_scoped_note_id === $note->id) {
                                        $currentValue = json_decode($point->lastChildPlan->data);
                                        $previousChildPlan = \App\Models\Point::where('id', '<', $point->lastChildPlan->id)
                                            ->where('category', 'PLAN')
                                            ->where('parent_point_id', $point->id)
                                            ->orderBy('id', 'DESC')
                                            ->first();
                                        if($previousChildPlan && $previousChildPlan->data) {
                                            $previousValue = json_decode($previousChildPlan->data);
                                        }
                                    }
                                    else {
                                        $previousChildPlan = \App\Models\Point::where('parent_point_id', $point->id)
                                            ->where('category', 'PLAN')
                                            ->orderBy('id', 'DESC')
                                            ->first();
                                        if($previousChildPlan && $previousChildPlan->data) {
                                            $previousValue = json_decode($previousChildPlan->data);
                                        }
                                    }
                                }
                                ?>
                                <div visit-moe relative class="d-block">
                                    <form show url="/api/visitPoint/<?= $point ? 'upsertChildPlan' : 'addTopLevel' ?>"
                                          class="mcp-theme-1 frm-review-plan-lifestyle frm-review-plan-behavior" right>
                                        @if($point)
                                            <input type="hidden" name="uid" value="<?= $point->uid ?>">
                                            <input type="hidden" name="segmentUid" value="<?= $segment->uid ?>">
                                            <input type="hidden" name="data">
                                        @else
                                            <input type="hidden" name="noteUid" value="<?= $note->uid ?>">
                                            <input type="hidden" name="category" value="<?= $p['category'] ?>">
                                            <input type="hidden" name="additionReasonCategory" value="DURING_VISIT">
                                            <input type="hidden" name="childPlanData">
                                        @endif
                                        @if($previousValue)
                                            <div class="mb-2">
                                                <div class="d-flex align-items-baseline mb-1">
                                                    <span class="text-sm text-secondary">Previous Plan / <?= friendlier_date($previousChildPlan->created_at) ?>)</span>
                                                </div>
                                                <div class="p-2 bg-light border inline-html-container">
                                                    <?php $plan = $previousValue; ?>
                                                    <?php include(resource_path('views/app/patient/segment-templates/_child_plan/behavior/' . $p['category'] . '/view-plan.php')); ?>
                                                </div>
                                            </div>
                                        @endif
                                        <?php include resource_path('views/app/patient/segment-templates/_child_plan/behavior/' . $p['category'] . '/edit-plan.php'); ?>
                                    </form>
                                </div>
                                @if(!empty($currentValue))
                                    <?php include(resource_path('views/app/patient/segment-templates/_child_plan/delete-plan.php')); ?>
                                @endif
                                <?php
                            }
                            ?>
                        </div>
                    </td>
                </tr>
            @endforeach

        </table>

    </div>
</div>
@if(!@$summaryView)
<script>
    (function() {
        function init() {

            $('div[moe] form').hide();

            let mode = 'read';

            let parentSegment = $('#behavior-center-{{$note->id}}');
            @include('app.patient.wizard-partials.common-script', ['label' => 'behavior', 'segment_part' => 'behavior'])
            initSegmentMoes(parentSegment);
            __initRTEs(parentSegment.find('[note-rte]:not(.ql-container)'));

            // custom buttons on title bar
            $('.button-container').remove();
            let buttonContainer = $('<div/>').addClass('button-container ml-4 mr-auto');
            let titleElem = $('#behavior-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);

            buttonContainer.insertAfter(titleElem);

            button
                .off('click.toggle-edit')
                .on('click.toggle-edit', function () {
                    if (mode === 'read') {
                        mode = 'edit';
                        $(this).text('Back to Read Mode');
                        $('#behavior-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;
                });

            // HACK: create empty top-level points if not existing
            let createCalls = [];

            <?php
            $missing = [];
            foreach ($points as $p) {
                if (!$p['point']) {
                    $missing[] = $p['category'];
                }
            }
            if(count($missing)) {
                foreach ($missing as $m) {
                    ?>
                    createCalls.push($.ajax({
                        url: "/api/visitPoint/addTopLevel",
                        type: 'post',
                        data: {
                            noteUid: '{{$note->uid}}',
                            category: '{{$m}}',
                            additionReasonCategory: 'ON_INTAKE'
                        },
                        success: function (jsonSaveResponse) {},
                        error: function (jqXHR, textStatus, errorThrown) {}
                    }));
                    <?php
                }
                ?>
                Promise.all(createCalls).then(() => {
                    refreshDynamicStagPopup();
                });
                <?php
            }
            else {
                if(@$note && !$note->is_signed_by_hcp && !request()->input('forceReadMode')) { // auto-open edit mode
                    ?>
                    button.trigger('click');
                    <?php
                }
            }
            ?>
        }
        addMCInitializer('behavior-center-{{$note->id}}', init, '#behavior-center-{{$note->id}}');
    }).call(window);
</script>
@endif
