<?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(!@$careTeamMembers || !@$counts) {
    list($careTeamMembers, $counts) = Point::getPointsOfCategoryExtended($patient, 'CARE_TEAM_MEMBER', $note, !!@$summaryView);
}
?>

<div @if(!@$summaryView) class="mt-3 p-3 border-top" id="careteam-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">Name/Details</th>
                <th class="border-bottom-0 text-secondary w-30">Subjective</th>
                <th class="border-bottom-0 text-secondary w-30">Plan</th>
                <th class="border-bottom-0 text-secondary">Contact</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($careTeamMembers as $careTeamMember): ?>
            <?php $point = $careTeamMember; ?>
            @if($prevRowState !== $careTeamMember->state)
                @include('app.patient.wizard-partials.state-row', ['point' => $careTeamMember])
            @endif
            <?php $prevRowState = $careTeamMember->state; ?>
            <?php $rel = $careTeamMember->note_point_uid; ?>
            <tr class="{{$rel ? 'relevant-to-visit' : ''}} point-row"
                data-uid="{{$careTeamMember->uid}}"
                data-name-base64="{{!!@($careTeamMember->data->name) ? base64_encode($careTeamMember->data->name) : ''}}"
                data-is-removed="{{$careTeamMember->is_removed ? 1 : 0}}"
                data-is-removed-due-to-entry-error="{{$careTeamMember->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' => $careTeamMember])
                        <div>
                            @if(!@$summaryView)
                                <div>
                                    <div moe huge relative>
                                        <a start show href="#" title="Edit">
                                            <?= !!@($careTeamMember->data->name) ? @($careTeamMember->data->name) : '-' ?>
                                            <?= !!@($careTeamMember->data->specialty) ? ' / ' . @($careTeamMember->data->specialty) : '' ?>
                                            <?= !!@($careTeamMember->data->organization) ? ' / ' . @($careTeamMember->data->organization) : '' ?>
                                        </a>
                                        <form url="/api/visitPoint/updateTopLevel" no-auto-focus class="mcp-theme-1 frm-edit-care-team-member">
                                            <input type="hidden" name="uid" value="<?= $careTeamMember->uid ?>">
                                            <input type="hidden" name="noteUid" value="<?= $note->uid ?>">
                                            <p class="mb-2"><b>Update Care Team Member</b></p>

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

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

                                                <div class="mb-2 bg-light p-2 border">
                                                    <p class="mb-1 font-weight-bold">
                                                        {{ @$careTeamMember->data->name }}
                                                        {{ @$careTeamMember->data->specialty }}
                                                        {{ @$careTeamMember->data->organization }}
                                                    </p>
                                                    @if($patient->core_note_id !== $note->id)
                                                        <div class="text-secondary">This care team member 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 {{$careTeamMember->added_in_note_id === $note->id ? '' : 'd-none'}}" if-core-data-edit-confirmed>

                                                <div class="row mb-2">
                                                    <div class="col-6 pr-0">
                                                        <label class="text-sm mb-1 font-weight-bold">Name</label>
                                                        <input type="text" class="form-control form-control-sm min-width-unset"
                                                               data-name="name"
                                                               value="{{@$careTeamMember->data->name}}">
                                                    </div>
                                                    <div class="col-6">
                                                        <label class="text-sm mb-1 font-weight-bold">Specialty</label>
                                                        <input type="text" class="form-control form-control-sm min-width-unset"
                                                               data-name="specialty"
                                                               data-option-list="specialty"
                                                               value="{{@$careTeamMember->data->specialty}}">
                                                        <div class="data-option-list">
                                                            <div>Allergy and immunology</div>
                                                            <div>Anesthesiology</div>
                                                            <div>Dermatology</div>
                                                            <div>Diagnostic radiology</div>
                                                            <div>Emergency medicine</div>
                                                            <div>Family medicine</div>
                                                            <div>Internal medicine</div>
                                                            <div>Medical genetics</div>
                                                            <div>Neurology</div>
                                                            <div>Nuclear medicine</div>
                                                            <div>Obstetrics and gynecology</div>
                                                            <div>Ophthalmology</div>
                                                            <div>Pathology</div>
                                                            <div>Pediatrics</div>
                                                            <div>Physical medicine and rehabilitation</div>
                                                            <div>Preventive medicine</div>
                                                            <div>Psychiatry</div>
                                                            <div>Radiation oncology</div>
                                                            <div>Surgery</div>
                                                            <div>Urology</div>
                                                        </div>
                                                    </div>
                                                </div>

                                                <div class="row mb-2">
                                                    <div class="col-6 pr-0">
                                                        <label class="text-sm mb-1 font-weight-bold">Organization</label>
                                                        <input type="text" class="form-control form-control-sm min-width-unset"
                                                               data-name="organization"
                                                               value="{{@$careTeamMember->data->organization}}">
                                                    </div>
                                                    <div class="col-3 pr-0">
                                                        <label class="text-sm mb-1 font-weight-bold">Phone</label>
                                                        <input type="text" class="form-control form-control-sm min-width-unset"
                                                               data-name="phone"
                                                               value="{{@$careTeamMember->data->phone}}">
                                                    </div>
                                                    <div class="col-3">
                                                        <label class="text-sm mb-1 font-weight-bold">Fax</label>
                                                        <input type="text" class="form-control form-control-sm min-width-unset"
                                                               data-name="fax"
                                                               value="{{@$careTeamMember->data->fax}}">
                                                    </div>
                                                </div>

                                            </div>

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

                                            <div class="mt-3 pt-2 d-flex align-items-center border-top">
                                                <button type="submit" class="btn-save-care-team-member 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>
                            @else
                                <?= !!@($careTeamMember->data->name) ? @($careTeamMember->data->name) : '-' ?>
                                <?= !!@($careTeamMember->data->specialty) ? '<br>' . @($careTeamMember->data->specialty) : '' ?>
                                <?= !!@($careTeamMember->data->organization) ? '<br>' . @($careTeamMember->data->organization) : '' ?>
                            @endif
                            @include('app.patient.wizard-partials.state-badge', ['point' => $careTeamMember])
                        </div>
                    </div>
                </td>
                <td>
                    <div if-read-mode>
                        <div class="d-flex align-items-start position-relative">
                            <div class="flex-grow-1">
                                <?php
                                $point = $careTeamMember;
                                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<?= !!@($careTeamMember->data->name) ? ' for ' . @($careTeamMember->data->name) : '' ?>"
                                   href="/point/review-log/<?= $careTeamMember->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<?= !!@($careTeamMember->data->name) ? ' for ' . @($careTeamMember->data->name) : '' ?>"
                                   href="/point/plan-log/<?= $careTeamMember->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>
                <td>
                    <?= '<span class="text-secondary">Ph: </span>' . (!!@($careTeamMember->data->phone) ? @($careTeamMember->data->phone) : '-') ?><br>
                    <?= '<span class="text-secondary">Fax: </span>' . (!!@($careTeamMember->data->fax) ? @($careTeamMember->data->fax) : '-') ?>
                </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><?= !!@($careTeamMember->data->start_date) ? friendly_date($careTeamMember->data->start_date) : '-' ?></b></div>
                            @if(!!@($careTeamMember->data->prescriber))
                                <div class="text-sm text-left text-secondary">By: <?= !!@($careTeamMember->data->prescriber) ? @($careTeamMember->data->prescriber) : '-' ?></div>
                            @endif
                            <hr class="my-1">
                            <div class="text-nowrap small text-left text-left">Ended <b><?= !!@($careTeamMember->removal_effective_date) ? friendly_date($careTeamMember->removal_effective_date) : '-' ?></b></div>
                            @if(!!@($careTeamMember->data->prescriber))
                                <div class="text-sm text-secondary">By/Memo: <?= !!@($careTeamMember->removal_reason_memo) ? @($careTeamMember->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-care-team-member" novalidate>
                    <input type="hidden" name="noteUid" value="<?= $note->uid ?>">
                    <input type="hidden" name="category" value="CARE_TEAM_MEMBER">
                    <input type="hidden" name="data">

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

                    <p class="mb-2"><b>Add Care Team Member</b></p>

                    <div class="row">
                        <div class="col-8">

                            <div class="row mb-2">
                                <div class="col-6 pr-0">
                                    <label class="text-sm mb-1 font-weight-bold">Name</label>
                                    <input type="text" class="form-control form-control-sm min-width-unset"
                                           data-name="name">
                                </div>
                                <div class="col-6">
                                    <label class="text-sm mb-1 font-weight-bold">Specialty</label>
                                    <input type="text" class="form-control form-control-sm min-width-unset"
                                           stag-suggest
                                           data-name="specialty">
                                    <div class="data-option-list">
                                        <div>Allergy and immunology</div>
                                        <div>Anesthesiology</div>
                                        <div>Dermatology</div>
                                        <div>Diagnostic radiology</div>
                                        <div>Emergency medicine</div>
                                        <div>Family medicine</div>
                                        <div>Internal medicine</div>
                                        <div>Medical genetics</div>
                                        <div>Neurology</div>
                                        <div>Nuclear medicine</div>
                                        <div>Obstetrics and gynecology</div>
                                        <div>Ophthalmology</div>
                                        <div>Pathology</div>
                                        <div>Pediatrics</div>
                                        <div>Physical medicine and rehabilitation</div>
                                        <div>Preventive medicine</div>
                                        <div>Psychiatry</div>
                                        <div>Radiation oncology</div>
                                        <div>Surgery</div>
                                        <div>Urology</div>
                                    </div>
                                </div>
                            </div>

                            <div class="row mb-2">
                                <div class="col-6 pr-0">
                                    <label class="text-sm mb-1 font-weight-bold">Organization</label>
                                    <input type="text" class="form-control form-control-sm min-width-unset"
                                           data-name="organization">
                                </div>
                                <div class="col-3 pr-0">
                                    <label class="text-sm mb-1 font-weight-bold">Phone</label>
                                    <input type="text" class="form-control form-control-sm min-width-unset"
                                           data-name="phone">
                                </div>
                                <div class="col-3">
                                    <label class="text-sm mb-1 font-weight-bold">Fax</label>
                                    <input type="text" class="form-control form-control-sm min-width-unset"
                                           data-name="fax">
                                </div>
                            </div>

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

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

                        </div>
                    </div>

                    <div class="d-flex align-items-center">
                        <button type="submit" class="btn btn-sm btn-primary mr-2 my-1">Save Care Team Member</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' => 'care team member', 'category' => 'CARE_TEAM_MEMBER', 'adder' => 'Added By'])
                </div>
            </div>
        </div>
        @endif
    </div>
</div>

@if(!@$summaryView)
<script>
    (function() {
        function init() {
            let parentSegment = $('#careteam-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' => 'care-team-member', 'segment_part' => 'care_team'])

            initSegmentMoes($('#careteam-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 = $('#careteam-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');
                        $('#careteam-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('careteam-center-{{$note->id}}', init, '#careteam-center-{{$note->id}}');
    }).call(window);
</script>
@endif
