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

$highSugarBeverages = Point::getOnlyPointOfCategory($patient, 'HIGH_SUGAR_BEVERAGES');
$waterIntake = Point::getOnlyPointOfCategory($patient, 'WATER_INTAKE');
$fastFood = Point::getOnlyPointOfCategory($patient, 'FAST_FOOD');
$snacks = Point::getOnlyPointOfCategory($patient, 'SNACKS');
$vegetables = Point::getOnlyPointOfCategory($patient, 'VEGETABLES');
$portionSizes = Point::getOnlyPointOfCategory($patient, 'PORTION_SIZES');
$dailyIntakeCarbohydrates = Point::getOnlyPointOfCategory($patient, 'DAILY_INTAKE_CARBOHYDRATES');
$dailyIntakeCalories = Point::getOnlyPointOfCategory($patient, 'DAILY_INTAKE_CALORIES');

$points = [
    ["category" => 'HIGH_SUGAR_BEVERAGES', "name" => 'Beverages', "point" => $highSugarBeverages],
    ["category" => 'WATER_INTAKE', "name" => 'Water Intake', "point" => $waterIntake],
    ["category" => 'FAST_FOOD', "name" => 'Fast Food', "point" => $fastFood],
    ["category" => 'SNACKS', "name" => 'Snacks', "point" => $snacks],
    ["category" => 'VEGETABLES', "name" => 'Vegetables', "point" => $vegetables],
    ["category" => 'PORTION_SIZES', "name" => 'Portion Sizes', "point" => $portionSizes],
    ["category" => 'DAILY_INTAKE_CARBOHYDRATES', "name" => 'Daily Intake Carbohydrates', "point" => $dailyIntakeCarbohydrates],
    ["category" => 'DAILY_INTAKE_CALORIES', "name" => 'Daily Intake Calories', "point" => $dailyIntakeCalories],
];
?>

<div @if(!@$summaryView) class="mt-3 p-3 border-top" id="nutrition-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'] === 'HIGH_SUGAR_BEVERAGES')
                                <img src="/img/nutrition-rx/hsb.png" class="icon-nutrition-rx-row" alt="">
                            @elseif($p['category'] === 'WATER_INTAKE')
                                <img src="/img/nutrition-rx/wi.png" class="icon-nutrition-rx-row" alt="">
                            @elseif($p['category'] === 'VEGETABLES')
                                <img src="/img/nutrition-rx/vc.png" class="icon-nutrition-rx-row" alt="">
                            @elseif($p['category'] === 'DAILY_INTAKE_CARBOHYDRATES' || $p['category'] === 'DAILY_INTAKE_CALORIES')
                                <img src="/img/nutrition-rx/ig.png" class="icon-nutrition-rx-row" alt="">
                            @endif
                            @endif
                        </div>
                        @if(!@$summaryView)
                        <div class="text-sm mt-1">
                            @if($p['category'] === 'HIGH_SUGAR_BEVERAGES')
                                E.g. soda, sweet tea, coffee, juice, etc.
                            @elseif($p['category'] === 'WATER_INTAKE')
                                Ounces per day
                            @elseif($p['category'] === 'FAST_FOOD')
                                Meals per week
                            @elseif($p['category'] === 'PORTION_SIZES')
                                Servings per meal
                            @elseif($p['category'] === 'DAILY_INTAKE_CARBOHYDRATES' || $p['category'] === 'DAILY_INTAKE_CALORIES')

                            @endif
                        </div>
                        @endif
                    </td>
                    <td class="w-40">
                        <div if-read-mode>
                            @if($point)
                                <?php
                                include resource_path('views/app/patient/segment-templates/_child_review/nutrition/' . $p['category'] . '/last-review.php');
                                ?>
                            @else
                                -
                            @endif
                        </div>
                        <div if-edit-mode>
                            <?php
                            $segment = $note->getSegmentByInternalName('intake_nutrition');
                            if(!$segment) $segment = $note->getSegmentByInternalName('nutrition');
                            if(!$segment) $segment = $note->coreSegment;
                            if($segment) {
                                include resource_path('views/app/patient/segment-templates/_child_review/nutrition/' . $p['category'] . '/edit-review.php');
                            }
                            ?>
                        </div>
                    </td>
                    <td class="w-40">
                        <div if-read-mode>
                            @if($point)
                                <?php
                                include resource_path('views/app/patient/segment-templates/_child_plan/nutrition/' . $p['category'] . '/last-plan.php');
                                ?>
                            @else
                                -
                            @endif
                        </div>
                        <div if-edit-mode>
                            <?php
                            $segment = $note->getSegmentByInternalName('plan_nutrition');
                            if(!$segment) $segment = $note->getSegmentByInternalName('nutrition');
                            if(!$segment) $segment = $note->coreSegment;
                            if($segment) {
                                include resource_path('views/app/patient/segment-templates/_child_plan/nutrition/' . $p['category'] . '/edit-plan.php');
                            }
                            ?>
                        </div>
                    </td>
                </tr>
            @endforeach

        </table>

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

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

            let mode = 'read';

            let parentSegment = $('#nutrition-center-{{$note->id}}');
            @include('app.patient.wizard-partials.common-script', ['label' => 'nutrition', 'segment_part' => 'nutrition'])
            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 = $('#nutrition-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');
                        $('#nutrition-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('nutrition-center-{{$note->id}}', init, '#nutrition-center-{{$note->id}}');
    }).call(window);
</script>
@endif
