<?php

$days = $patient->cmMeasurementsMatrix($careMonth, ($pro->pro_type === 'ADMIN' ? null : $pro));

$performerRole = false;
if ($pro->pro_type === 'ADMIN') {
    $performerRole = 'ADMIN';
} else if ($careMonth->mcp_pro_id === $pro->id) {
    $performerRole = 'MCP';
} else if ($careMonth->rme_pro_id === $pro->id || $careMonth->rmm_pro_id === $pro->id) {
    $performerRole = 'NON-HCP';
}

$unstampedMCP = [];
$unstampedNonHCP = [];
foreach ($days as $k => $day) {
    $unstampedMCP[$k] = [];
    $unstampedNonHCP[$k] = [];
    foreach ($days[$k] as $mIndex => $m) {
        if(!$m->has_been_stamped_by_mcp) {
            $unstampedMCP[$k][] = $m->measurement_uid;
        }
        if(!$m->has_been_stamped_by_non_hcp) {
            $unstampedNonHCP[$k][] = $m->measurement_uid;
        }
    }
}

?>

<div id="cm-matrix-{{$patient->id}}">
@if(!@$onlyMatrix)
<div class="d-flex align-items-baseline mb-3" tab-links>
    <a class="tab-link-active" href="#" tab-link="time-entries">Time Entries</a>
    <a class="" href="#" tab-link="bmi-summary">BMI/Weight Management Settings</a>
    <a class="" href="#" tab-link="bp-summary">BP Management Settings</a>
</div>
@endif
<div class="my-3 cm-tab" tab-key="time-entries">
    @if($careMonth->is_client_enrolled_in_rm)
        <?php
        $myEntries = $careMonth->entriesByPro($pro->id);
        $otherEntries = $careMonth->entriesNotByPro($pro->id);
        ?>
        <div class="d-flex align-items-center">
            <h6 class="my-0 text-secondary font-weight-bold text-dark lh-24px">My Time Entries</h6>
            <span class="mx-2 text-secondary">|</span>
            @include('app.practice-management.care_month_add_entry_form', ['right' => false])
        </div>
        <table class="table table-striped table-sm table-bordered mt-2 mb-0 table-hover">
            <thead>
            <tr>
                <th class="px-2 text-secondary border-bottom-0">Date</th>
                <th class="px-2 text-secondary border-bottom-0">Time</th>
                <th class="px-2 text-secondary border-bottom-0">Inter.</th>
                <th class="px-2 text-secondary border-bottom-0 w-50">Comments</th>
                <th class="px-2 text-secondary border-bottom-0 delete-column">&nbsp;</th>
            </tr>
            </thead>
            <tbody>
            @foreach($myEntries as $entry)
                @if(!$entry->is_removed && $entry->cm_or_rm_or_rtm_msk_or_rtm_lung === "RM")
                    <tr>
                        <td class="px-2">
                            <div class="font-weight-bold">{{friendly_date_time($entry->effective_date, false)}}</div>
                        </td>
                        <td class="px-2">
                            {{time_in_hrminsec($entry->time_in_seconds)}}
                        </td>
                        <td class="px-2">
                            {{$entry->did_pro_interact_with_client_about_rm ? 'Yes' : 'No'}}
                        </td>
                        <td class="px-2">
                            <div class="text-secondary in-table-markup">{!! $entry->content_text !!}</div>
                            <!--                                        <div class="text-secondary text-sm">{{$entry->content_detail}}</div>-->
                        </td>
                        <td class="px-2">
                            @if(!$activeRMBill)
                                @include('app.practice-management.care_month_add_entry_form', ['right' => true, 'entry' => $entry])
                                <div moe relative>
                                    <a start show class="text-danger">Delete</a>
                                    <form url="/api/careMonthEntry/remove" right class="text-left">
                                        <input type="hidden" name="uid" value="{{ $entry->uid }}">
                                        <p class="small">Are you sure you want to delete this RM entry?</p>
                                        <div class="d-flex align-items-center">
                                            <button class="btn btn-sm btn-danger mr-2" submit>Delete</button>
                                            <button class="btn btn-sm btn-default mr-2 border" cancel>Cancel</button>
                                        </div>
                                    </form>
                                </div>
                            @else
                                <span class="text-sm text-secondary">Can't modify since a bill exists</span>
                            @endif
                        </td>
                    </tr>
                @endif
            @endforeach
            </tbody>
        </table>

        <div class="d-flex align-items-center mt-3">
            <h6 class="my-0 text-secondary font-weight-bold text-dark lh-24px">Other Time Entries</h6>
        </div>
        <table class="table table-striped table-sm table-bordered mt-2 mb-0 table-hover">
            <thead>
            <tr>
                <th class="px-2 text-secondary border-bottom-0 width-100px">Date</th>
                @if($pro->pro_type === 'ADMIN')
                    <th class="px-2 text-secondary border-bottom-0">Pro</th>
                @endif
                <th class="px-2 text-secondary border-bottom-0 w-100">Comments</th>
            </tr>
            </thead>
            <tbody>
            @foreach($otherEntries as $entry)
                @if(!$entry->is_removed && $entry->cm_or_rm_or_rtm_msk_or_rtm_lung === "RM")
                    <tr>
                        <td class="px-2">
                            <div class="font-weight-bold">{{friendly_date_time($entry->effective_date, false)}}</div>
                        </td>
                        @if($pro->pro_type === 'ADMIN')
                            <td class="px-2 text-nowrap">
                                {{$entry->pro->displayName()}}
                            </td>
                        @endif
                        <td class="px-2">
                            <div class="text-secondary in-table-markup">{!! $entry->content_text !!}</div>
                        </td>
                    </tr>
                @endif
            @endforeach
            </tbody>
        </table>
    @else
        <h6 class="mb-2 text-secondary font-weight-bold text-dark lh-24px">Time Entries</h6>
        <div class="alert alert-secondary mt-2 mb-0">
            <b>{{ $patient->displayName() }}</b> is not enrolled in <b>RM</b> for this care month.
            <span moe class="">
                    <a start show class="font-weight-bold">Enroll Now</a>
                    <form url="/api/careMonth/setIsClientEnrolledInRmToTrue">
                        <input type="hidden" name="uid" value="{{ $careMonth->uid }}">
                        <p class="small">Enroll this client in RM?</p>
                        <div class="d-flex align-items-center">
                            <button class="btn btn-sm btn-primary mr-2" submit>Yes</button>
                            <button class="btn btn-sm btn-default mr-2 border" cancel>No</button>
                        </div>
                    </form>
                </span>
        </div>
    @endif
</div>
<div class="my-3 border p-3 d-none cm-tab" tab-key="bmi-summary">
    <div class="d-flex align-items-baseline mb-2">
        <b>BMI/Weight Management</b>
        <span class="mx-2 text-secondary">|</span>
        @include('app.patient.vitals-settings.bmi-management-form')
    </div>
    @include('app.patient.vitals-settings.bmi-management-summary')
</div>
<div class="my-3 border p-3 d-none cm-tab" tab-key="bp-summary">
    <div class="d-flex align-items-baseline mb-2">
        <b>BP Management</b>
        <span class="mx-2 text-secondary">|</span>
        @include('app.patient.vitals-settings.bp-management-form')
    </div>
    @include('app.patient.vitals-settings.bp-management-summary')
</div>
</div>
<script>
    (function() {
        function init() {

            $('.btn-stamp')
                .off('click')
                .on('click', function () {
                    let form = $(this).closest('form');
                    if(!form[0].checkValidity()) {
                        form[0].reportValidity();
                        return false;
                    }

                    showMask();

                    let payload = {
                        uid: form.find('[name="uid"]').val(),
                        memo: form.find('[name="memo"]').val(),
                    }

                    $.ajax({
                        url: form.attr('url'),
                        type:"POST",
                        data: JSON.stringify(payload),
                        contentType:"application/json; charset=utf-8",
                        dataType:"json",
                        success: function(_data) {
                            if(!hasResponseError(_data)) {
                                if(form.closest('.stag-popup').length) {
                                    refreshDynamicStagPopup();
                                }
                                else {
                                    fastReload();
                                }
                            }
                        }
                    }).then(() => {
                        hideMask();
                    });
                    return false;
                });

            $('.btn-bulk-stamp')
                .off('click')
                .on('click', function () {
                    let form = $(this).closest('form');
                    if(!form[0].checkValidity()) {
                        form[0].reportValidity();
                        return false;
                    }

                    showMask();

                    let payload = {
                        clientUid: '{{$patient->uid}}',
                        toStamp: form.find('.measurements-uids').val().split('|').map(_x => {
                            return {
                                measurementUid: _x,
                                memo: null,
                                detailJson: null
                            }
                        }),
                        shouldAddEntry: form.find('.shouldAddEntry').prop('checked') ? 1 : 0,
                        entryDate: form.find('[name="entryDate"]').val(),
                        entryMemo: form.find('[name="entryMemo"]').val(),
                        entryNumberOfSeconds: form.find('[name="entryNumberOfSeconds"]').val() ? +(form.find('[name="entryNumberOfSeconds"]').val()) : 0
                    }

                    if(form.find('[name="didProInteractWithClientAboutRm"]:checked').length) {
                        payload.didProInteractWithClientAboutRm = (form.find('[name="didProInteractWithClientAboutRm"]:checked').val() === 'true');
                    }

                    $.ajax({
                        url: form.attr('url'),
                        type:"POST",
                        data: JSON.stringify(payload),
                        contentType:"application/json; charset=utf-8",
                        dataType:"json",
                        success: function(_data) {
                            if(!hasResponseError(_data)) {
                                if(form.closest('.stag-popup').length) {
                                    refreshDynamicStagPopup();
                                }
                                else {
                                    fastReload();
                                }
                            }
                        }
                    }).then(() => {
                        hideMask();
                    });
                    return false;
                });

            $('.shouldAddEntry')
                .off('change')
                .on('change', function () {
                    let form = $(this).closest('form');
                    if(this.checked) {
                        form.find('.if-adding-time-entry').removeClass('d-none');
                    }
                    else {
                        form.find('.if-adding-time-entry').addClass('d-none');
                    }
                    return false;
                })
                .trigger('change');
        }
        addMCInitializer('cm-matrix-{{$patient->id}}', init, '#cm-matrix-{{$patient->id}}');
    }).call(window);
</script>
