<?php

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

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

$points = Point
    ::where('client_id', $patient->id)
    ->where('category', 'MEDICATION')
    ->where('is_removed', false)
    ->orderBy('created_at')
    ->get();
foreach ($points as $point) {
    if ($point->data) {
        $point->data = json_decode($point->data);
    }
}
$medications = $points;
?>

<div class="mt-3 p-3 border-top" id="medications-reconcile-{{$note->id}}">
    <div class="mb-2 font-weight-bold text-secondary">The following medications will be marked as reconciled</div>
    <table class="table table-sm table-striped table-bordered">
        <thead>
        <tr>
            <th class="text-secondary bg-light border-bottom-0 w-25">Medication</th>
            <th class="text-secondary bg-light border-bottom-0 w-25">Pre-existing Plan</th>
            <th class="text-secondary bg-light border-bottom-0 w-25">Current Subjective
                <a href="#" class="text-sm font-weight-normal ml-3 btn-copy-all">Copy all to new subj.</a>
            </th>
            <th class="text-secondary bg-light border-bottom-0 w-25">New Subjective</th>
        </tr>
        </thead>
        @foreach($medications as $medication)
            <?php
            $default = '';

            // get most recent child plan for this point that was created before this note
            $mostRecentPlanBeforeThisNote = Point::where('parent_point_id', $medication->id)
                ->where('category', 'PLAN')
                ->where('added_in_note_id', '<', $note->id)
                ->orderBy('id', 'DESC')
                ->first();

            // get most recent child review for this point that was created before this note
            $mostRecentReviewBeforeThisNote = Point::where('parent_point_id', $medication->id)
                ->where('category', 'REVIEW')
                ->where('added_in_note_id', '<', $note->id)
                ->orderBy('id', 'DESC')
                ->first();

            // get child review for this point created on this note
            $newReview = Point::where('parent_point_id', $medication->id)
                ->where('category', 'REVIEW')
                ->where('added_in_note_id', $note->id)
                ->orderBy('id', 'DESC')
                ->first();
            if($newReview && $newReview->data) {
                $newReview->data = json_decode($newReview->data);
                $default = $newReview->data->value;
            }
            ?>
            <tr>
                <td class="bg-light font-weight-bold">
                    <span class="" if-active>{{$medication->data->name}}</span>
                    <span class="text-secondary on-hover-opaque d-none" if-historic>{{$medication->data->name}}</span>
                    <div class="d-block font-weight-normal">
                        <div class="d-flex align-items-baseline">
                            <span class="text-secondary mr-1">Active:</span>
                            <span class="text-success font-weight-bold" if-active>Yes</span>
                            <span class="text-warning-mellow font-weight-bold d-none" if-historic>No</span>
                            <div moe class="ml-2" if-active>
                                <a href="#" start show>Mark {{$medication->is_removed ? 'Active' : 'Historic'}}</a>
                                <form url="/api/visitPoint/updateTopLevel" no-auto-focus class="mcp-theme-1">
                                    <p class="mb-2">Mark medication as {{$medication->is_removed ? 'Active' : 'Historic'}}</p>
                                    <input type="hidden" name="uid" value="{{$medication->uid}}">
                                    <input type="hidden" name="noteUid" value="{{$note->uid}}">
                                    <input type="hidden" name="isRemoved" value="{{$medication->is_removed ? '0' : '1'}}">
                                    <div>
                                        <button type="button" class="btn-mark-historic 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>
                            <div moe class="ml-2 d-none" if-historic>
                                <a href="#" start show>Mark as Active</a>
                                <form url="/api/visitPoint/updateTopLevel" no-auto-focus class="mcp-theme-1">
                                    <p class="mb-2">Mark medication as Active</p>
                                    <input type="hidden" name="uid" value="{{$medication->uid}}">
                                    <input type="hidden" name="noteUid" value="{{$note->uid}}">
                                    <input type="hidden" name="isRemoved" value="0">
                                    <div>
                                        <button type="button" class="btn-mark-active 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>
                        </div>
                    </div>
                </td>
                <td class="bg-light">
                    @include('app/patient/wizard-partials/show-plan', ['point' => $medication, 'plan' => $mostRecentPlanBeforeThisNote])
                </td>
                <td class="bg-light">
                    @include('app/patient/wizard-partials/show-review', ['point' => $medication, 'review' => $mostRecentReviewBeforeThisNote])
                </td>
                <td class="p-0 bg-white">
                    <div note-rte slim-rte ignore-changes
                         data-point-uid="{{$medication->uid}}"
                         class="form-group rte-holder mb-0 bg-white border-0 rounded-0"><?= $default ?></div>
                </td>
            </tr>
        @endforeach
    </table>
    <div class="d-flex align-items-center justify-content-center">
        <button class="btn btn-sm btn-primary mr-2 btn-save-reviews">Save</button>
        <button class="btn btn-sm btn-default border mr-2" onclick="closeStagPopup()">Cancel</button>
    </div>
</div>

<script>
    (function() {
        function __initRTEs(_collection) {
            _collection.each(function() {
                let noteRTE = $(this);
                $(this).wrap(
                    $('<div class="rte-holder"/>')
                        .attr('data-shortcuts', '')
                );
                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',
                    ]
                });
                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() {
            $('#medications-reconcile-{{$note->id}} .copy-to-new-subjective')
                .off('click')
                .on('click', function() {
                    let html = $.trim($(this).parent().prev('.inline-html-container').html());
                    let quillInstance = $(this).closest('tr').find('[note-rte][data-point-uid]').first().data('quillInstance');
                    // quillInstance.setContent(html);
                    quillInstance.root.innerHTML = html;
                    return false;
                });

            $('#medications-reconcile-{{$note->id}} .btn-copy-all')
                .off('click')
                .on('click', function() {
                    $('#medications-reconcile-{{$note->id}} .copy-to-new-subjective').each(function() {
                        $(this).trigger('click');
                    });
                    return false;
                });

            $('#medications-reconcile-{{$note->id}} .btn-save-reviews')
                .off('click')
                .on('click', function() {
                    let payload = {
                        noteUid: '{{$note->uid}}',
                        reviews: []
                    }

                    let hasAtLeastOneNonEmptyReview = false;

                    $('#medications-reconcile-{{$note->id}} [data-point-uid]').each(function () {
                        if($.trim($('<div/>').html($(this).find('.ql-editor').html()).text())) {
                            hasAtLeastOneNonEmptyReview = true;
                            payload.reviews.push({
                                parentPointUid: $(this).attr('data-point-uid'),
                                data: JSON.stringify({
                                    isReconciled: true,
                                    value: $(this).find('.ql-editor').html()
                                })
                            });
                        }
                    });

                    if(!hasAtLeastOneNonEmptyReview) {
                        toastr.error('New subjective is empty on all medications!');
                        return false;
                    }

                    showMask();

                    $.ajax({
                        url: '/api/visitPoint/upsertChildReviewMulti',
                        type:"POST",
                        data: JSON.stringify(payload),
                        contentType:"application/json; charset=utf-8",
                        dataType:"json",
                        success: function(_data) {
                            if(!hasResponseError(_data)) {
                                closeStagPopup();
                                refreshAffectedSegmentsByType('medication');
                            }
                        }
                    }).then(() => {
                        hideMask();
                    });

                });

            $('#medications-reconcile-{{$note->id}} .btn-mark-historic')
                .off('click')
                .on('click', function() {
                    showMask();
                    let form = $(this).closest('form'), row = $(this).closest('tr');
                    $.post(form.attr('url'), form.serialize(), _data => {
                        if(!hasResponseError(_data)) {
                            row.find('[if-active], [if-historic]').addClass('d-none');
                            row.find('[if-historic]').removeClass('d-none');
                        }
                    }, 'json').then(() => {
                        $('[moe] form').hide();
                        hideMask();
                    });
                    return false;
                });

            $('#medications-reconcile-{{$note->id}} .btn-mark-active')
                .off('click')
                .on('click', function() {
                    showMask();
                    let form = $(this).closest('form'), row = $(this).closest('tr');
                    $.post(form.attr('url'), form.serialize(), _data => {
                        if(!hasResponseError(_data)) {
                            row.find('[if-active], [if-historic]').addClass('d-none');
                            row.find('[if-active]').removeClass('d-none');
                        }
                    }, 'json').then(() => {
                        $('[moe] form').hide();
                        hideMask();
                    });
                    return false;
                });

            __initRTEs($('#medications-reconcile-{{$note->id}} [note-rte]'))
        }
        addMCInitializer('medications-reconcile-{{$note->id}}', init, '#medications-reconcile-{{$note->id}}')
    }).call(window);
</script>