@extends ('layouts/template')

@section('content')
    <link href="/c3/c3.min.css" rel="stylesheet">
    <script src="/c3/d3.v5.min.js" charset="utf-8"></script>
    <script src="/c3/c3.min.js"></script>

    <?php
    $careMonths = [];
    foreach ($patients as $iPatient) {
        if(!!$iPatient->entries_json) {
            $iPatient->entries_json = json_decode($iPatient->entries_json);
            $myEntries = [];
            $otherEntries = [];
            for ($i = 0; $i < count($iPatient->entries_json); $i++) {
                if($iPatient->entries_json[$i]->proUid === $pro->uid) {
                    $myEntries[] = $iPatient->entries_json[$i];
                }
                else {
                    $otherEntries[] = $iPatient->entries_json[$i];
                }
            }
            $iPatient->myEntries = $myEntries;
            $iPatient->otherEntries = $otherEntries;
        }
        if(!!$iPatient->measurements_json) {
            $iPatient->measurements_json = json_decode($iPatient->measurements_json);
        }
        if(!!$iPatient->measurements_bp_json) {
            $iPatient->measurements_bp_json = json_decode($iPatient->measurements_bp_json);
            for ($i = 0; $i < count($iPatient->measurements_bp_json); $i++) {
                $timestampInSec = floor($iPatient->measurements_bp_json[$i]->ts / 1000);
                $iPatient->measurements_bp_json[$i]->date_display = friendly_date_time_short_with_tz_from_timestamp($timestampInSec, 'EASTERN', '-', 'm/d/y');
                $iPatient->measurements_bp_json[$i]->date_standard = friendly_date_time_short_with_tz_from_timestamp($timestampInSec, 'EASTERN', '-', 'Y-m-d');
                $iPatient->measurements_bp_json[$i]->time_display = friendly_date_time_short_with_tz_from_timestamp($timestampInSec, 'EASTERN', '-', 'h:i A');
            }
        }
        if(!!$iPatient->measurements_weight_json) {
            $iPatient->measurements_weight_json = json_decode($iPatient->measurements_weight_json);
            for ($i = 0; $i < count($iPatient->measurements_weight_json); $i++) {
                $timestampInSec = floor($iPatient->measurements_weight_json[$i]->ts / 1000);
                $iPatient->measurements_weight_json[$i]->date_display = friendly_date_time_short_with_tz_from_timestamp($timestampInSec, 'EASTERN', '-', 'm/d/y');
                $iPatient->measurements_weight_json[$i]->date_standard = friendly_date_time_short_with_tz_from_timestamp($timestampInSec, 'EASTERN', '-', 'Y-m-d');
                $iPatient->measurements_weight_json[$i]->time_display = friendly_date_time_short_with_tz_from_timestamp($timestampInSec, 'EASTERN', '-', 'h:i A');
                $iPatient->measurements_weight_json[$i]->numericValue = round($iPatient->measurements_weight_json[$i]->numericValue, 1);
            }
        }
        $iPatient->month_display = friendly_month($iPatient->care_month_start_date);
        $careMonths[$iPatient->care_month_uid] = $iPatient;
    }
    $specificDate = request()->input('specificDate');
    ?>

    <style>
        table#table-pm-manager-matrix {
            position: relative;
            border-collapse: separate !important;
            border-spacing: 0;
        }
        table#table-pm-manager-matrix thead tr th {
            background-color: #f8f9fa;
            z-index: 2;
        }
        table#table-pm-manager-matrix thead tr th:not(.v-sep-before) {
            border-left-width: 0 !important;
        }
        table#table-pm-manager-matrix thead tr:nth-child(1) th {
            text-align: center;
            position: sticky;
            top: 0;
            z-index: 2;
            height: 28px;
        }
        table#table-pm-manager-matrix thead tr:nth-child(2) th {
            text-align: center;
            position: sticky;
            top: 28px;
            z-index: 2;
            height: 28px;
            border-bottom: 1px solid #ddd !important;
        }
        table#table-pm-manager-matrix thead th {

        }
        table#table-pm-manager-matrix th:nth-child(1) {
            position: sticky;
            left: 0;
            z-index: 3 !important;
            background-color: #f8f9fa;
        }
        table#table-pm-manager-matrix th:nth-child(2) {
            position: sticky;
            left: 41px;
            z-index: 3 !important;
            background-color: #f8f9fa;
            border-right: 2px solid #ddd !important;
        }
        table#table-pm-manager-matrix tbody tr td:nth-child(1) {
            position: sticky;
            left: 0;
            z-index: 1;
            background-color: #f8f9fa;
            border-right: 1px solid #ddd !important;
        }
        table#table-pm-manager-matrix tbody tr td:nth-child(2) {
            position: sticky;
            left: 41px;
            z-index: 1;
            background-color: #f8f9fa;
            border-right: 2px solid #ddd !important;
        }
        table#table-pm-manager-matrix tbody tr td {
            border-top-width: 0 !important;
        }
        table#table-pm-manager-matrix tbody tr td:not(.v-sep-before) {
            border-left-width: 0 !important;
        }
    </style>
    <style>
        #rpm-admin-stats-graph .stat-bg-total-light {
            background-color: #fbe7ce;
        }
        #rpm-admin-stats-graph .stat-bg-total-dark {
            background-color: #f6b26b;
        }
        #rpm-admin-stats-graph .stat-bg-recd-light {
            background-color: #d8ead2;
        }
        #rpm-admin-stats-graph .stat-bg-recd-dark {
            background-color: #69a751;
        }
        #rpm-admin-stats-graph .stat-bg-not-recd-light {
            background-color: #f3cdcc;
        }
        #rpm-admin-stats-graph .stat-bg-not-recd-dark {
            background-color: #e06665;
        }
        #rpm-admin-stats-graph .stat-bg-crit-light {
            background-color: #dbd3eb;
        }
        #rpm-admin-stats-graph .stat-bg-crit-dark {
            background-color: #aa98d5;
        }
    </style>
    <div class="p-3 mcp-theme-1" id="practice-rpm-manager">

        <div class="card h-100">

            <div class="card-header px-2 py-2 d-flex align-items-baseline">
                <span class="font-size-16">RPM Manager - {{$viewingAs}} - {{friendly_month($cmStartDate)}}</span>
            </div>

            <div class="card-body p-0">
                <div class="d-flex align-items-baseline p-2 border-bottom">
                    <form action="" class="flex-grow-1">
                        <div class="d-flex align-items-center">
                            <div class="mr-2 d-inline-flex align-items-center">
                                <label class="mb-0 mr-1">Month</label>
                                <select name="m" class="form-control form-control-sm min-width-unset pl-0 font-weight-bold"
                                        onchange="fastLoad('{{route('practice-management.rpm-manager')}}?' + $(this).closest('form').serialize())">
                                    <option value="">All</option>
                                    <option value="01" {{$month && intval($month) === 1 ? 'selected' : ''}}>Jan</option>
                                    <option value="02" {{$month && intval($month) === 2 ? 'selected' : ''}}>Feb</option>
                                    <option value="03" {{$month && intval($month) === 3 ? 'selected' : ''}}>Mar</option>
                                    <option value="04" {{$month && intval($month) === 4 ? 'selected' : ''}}>Apr</option>
                                    <option value="05" {{$month && intval($month) === 5 ? 'selected' : ''}}>May</option>
                                    <option value="06" {{$month && intval($month) === 6 ? 'selected' : ''}}>Jun</option>
                                    <option value="07" {{$month && intval($month) === 7 ? 'selected' : ''}}>Jul</option>
                                    <option value="08" {{$month && intval($month) === 8 ? 'selected' : ''}}>Aug</option>
                                    <option value="09" {{$month && intval($month) === 9 ? 'selected' : ''}}>Sep</option>
                                    <option value="10" {{$month && intval($month) === 10 ? 'selected' : ''}}>Oct</option>
                                    <option value="11" {{$month && intval($month) === 11 ? 'selected' : ''}}>Nov</option>
                                    <option value="12" {{$month && intval($month) === 12 ? 'selected' : ''}}>Dec</option>
                                </select>
                            </div>
                            <div class="mr-2 d-inline-flex align-items-center">
                                <label class="mb-0 mr-1">Year</label>
                                <select name="y" class="form-control form-control-sm min-width-unset pl-0 font-weight-bold"
                                        onchange="fastLoad('{{route('practice-management.rpm-manager')}}?' + $(this).closest('form').serialize())">
                                    <option value="">All</option>
                                    <option value="2020" {{$year && intval($year) === 2020 ? 'selected' : ''}}>2020</option>
                                    <option value="2021" {{$year && intval($year) === 2021 ? 'selected' : ''}}>2021</option>
                                    <option value="2022" {{$year && intval($year) === 2022 ? 'selected' : ''}}>2022</option>
                                    <option value="2023" {{$year && intval($year) === 2023 ? 'selected' : ''}}>2023</option>
                                </select>
                            </div>
                            @if(count($proRoles) > 1)
                                <div class="mr-2 d-inline-flex align-items-center">
                                    <label class="mb-0 mr-1 text-nowrap">View As</label>
                                    <select name="viewingAs" class="form-control form-control-sm min-width-unset pl-0 font-weight-bold"
                                            onchange="fastLoad('{{route('practice-management.rpm-manager')}}?' + $(this).closest('form').serialize())">
                                        @foreach($proRoles as $proRole)
                                            <option value="{{$proRole}}" {{$viewingAs === $proRole ? 'selected' : ''}}>{{$proRole}}</option>
                                        @endforeach
                                    </select>
                                </div>
                            @else
                                <input type="hidden" name="viewingAs" value="{{$viewingAs}}">
                            @endif
                            @if($pro->pro_type === 'ADMIN' && $viewingAs !== 'ADMIN')
                                <div class="mr-2 d-inline-flex align-items-center">
                                    <label class="mb-0 mr-1 text-nowrap">{{$viewingAs}}</label>
                                    <div class="position-relative">
                                        <select name="proUid" class="form-control form-control-sm min-width-unset pl-0 font-weight-bold"
                                                provider-search data-pro-uid="{{request()->input('proUid')}}"
                                                onchange="fastLoad('{{route('practice-management.rpm-manager')}}?' + $(this).closest('form').serialize())">
                                        </select>
                                    </div>
                                </div>
                            @endif
                            {{--
                            <div class="mr-2 d-inline-flex align-items-center">
                                <label class="mb-0 mr-1 text-nowrap">Date</label>
                                <input name="specificDate" class="form-control form-control-sm min-width-unset pl-1 font-weight-bold"
                                       value="{{$specificDate}}"
                                       type="date" min="{{$cmStartDate}}" max="{{$cmEndDate}}"
                                       onchange="fastLoad('{{route('practice-management.rpm-manager')}}?' + $(this).closest('form').serialize())">
                            </div>
                            --}}
                            <div class="mr-2 d-inline-flex align-items-center">
                                <label class="mb-0 mr-1 text-nowrap">Mins.</label>
                                <select name="mins" class="form-control form-control-sm min-width-unset pl-0 font-weight-bold"
                                        onchange="fastLoad('{{route('practice-management.rpm-manager')}}?' + $(this).closest('form').serialize())">
                                    <option value="" {{!$mins ? 'selected' : ''}}>All</option>
                                    <option value="<20" {{$mins === '<20' ? 'selected' : ''}}>Less than 20</option>
                                    <option value="20-40" {{$mins === '20-40' ? 'selected' : ''}}>Betw. 20 &amp; 40</option>
                                    <option value="40+" {{$mins === '40+' ? 'selected' : ''}}>40 or more</option>
                                </select>
                            </div>
                            <a href="#" onclick="return fastLoad('{{route('practice-management.rpm-manager')}}')">Clear</a>
                            @if($paginator->total())
                                <div class="d-inline-flex align-items-baseline ml-auto mb-0-pagination">
                                    <div class="mr-2"><b>{{$paginator->firstItem()}}</b> to <b>{{$paginator->lastItem()}}</b> (page {{$paginator->currentPage()}}) of <b>{{$paginator->total()}}</b></div>
                                    {!! $paginator->onEachSide(1)->withQueryString()->links() !!}
                                    <select class="form-control form-control-sm min-width-unset width-140px px-2 ml-2" onchange="fastLoad('{{ route('practice-management.rpm-manager') }}?{{queryLineExcept(['per_page', 'page'])}}&per_page=' + this.value)">
                                        <option {{$perPage == 25 ? 'selected' : ''}} value="25">25/page</option>
                                        <option {{$perPage == 50 ? 'selected' : ''}} value="50">50/page</option>
                                        <option {{$perPage == 75 ? 'selected' : ''}} value="75">75/page</option>
                                        <option {{$perPage == 100 ? 'selected' : ''}} value="100">100/page</option>
                                    </select>
                                </div>
                            @endif
                        </div>
                        <div id="rpm-admin-stats-graph" class="w-100">

                            <div class="mt-2 pt-2 border-top w-100">
                                <div class="d-flex align-items-stretch justify-content-center">
                                    <div class="width-140px mr-3 stat-bg-total-light d-inline-flex flex-column">
                                        <div class="flex-grow-1 py-1 d-flex align-items-end"><span class="w-100 text-center">Total Patients</span></div>
                                        <div class="font-size-16 font-weight-bold stat-bg-total-dark w-100 py-1 text-center">
                                            {{$stats['totalPatients']}}
                                        </div>
                                    </div>
                                    <div class="width-140px mr-3 stat-bg-recd-light d-inline-flex flex-column">
                                        <div class="flex-grow-1 py-1 d-flex align-items-end">
                                            <span class="w-100 text-center">With Meas. On:</span>
                                        </div>
                                        <div style="padding: 0 1px">
                                            <input type="date" name="wmo" class="border-0 py-0 px-1 w-100 rounded-0 text-center"
                                                   onchange="$('[name=nmo]').val(this.value); fastLoad('{{route('practice-management.rpm-manager')}}?' + $(this).closest('form').serialize());"
                                                   value="{{request()->input('wmo') ?: date('Y-m-d')}}">
                                        </div>
                                        <div class="font-size-16 font-weight-bold stat-bg-recd-dark w-100 py-1 text-center">
                                            {{$stats['withMeasOn']}}
                                        </div>
                                    </div>
                                    <div class="width-140px mr-3 stat-bg-not-recd-light d-inline-flex flex-column">
                                        <div class="flex-grow-1 py-1 d-flex align-items-end"><span class="w-100 text-center">No Meas. On:</span></div>
                                        <div style="padding: 0 1px">
                                            <input type="date" name="nmo" class="border-0 py-0 px-1 w-100 rounded-0 text-center"
                                                   onchange="$('[name=wmo]').val(this.value); fastLoad('{{route('practice-management.rpm-manager')}}?' + $(this).closest('form').serialize());"
                                                   value="{{request()->input('wmo') ?: date('Y-m-d')}}">
                                        </div>
                                        <div class="font-size-16 font-weight-bold stat-bg-not-recd-dark w-100 py-1 text-center">
                                            {{$stats['noMeasOn']}}
                                        </div>
                                    </div>
                                    <div class="width-140px mr-3 stat-bg-crit-light d-inline-flex flex-column">
                                        <div class="flex-grow-1 py-1 d-flex align-items-end"><span class="w-100 text-center">With >= 16 Meas. days</span></div>
                                        <div class="font-size-16 font-weight-bold stat-bg-crit-dark w-100 py-1 text-center">
                                            {{$stats['gt16MD']}}
                                        </div>
                                    </div>
                                    <div class="width-140px mr-3 stat-bg-crit-light d-inline-flex flex-column">
                                        <div class="flex-grow-1 py-1 d-flex align-items-end"><span class="w-100 text-center">With >= 20m Interaction</span></div>
                                        <div class="font-size-16 font-weight-bold stat-bg-crit-dark w-100 py-1 text-center">
                                            {{$stats['gt20M']}}
                                        </div>
                                    </div>
                                    <div class="width-140px mr-3 stat-bg-crit-light d-inline-flex flex-column">
                                        <div class="flex-grow-1 py-1 d-flex align-items-end"><span class="w-100 text-center">With >= 40m Interaction</span></div>
                                        <div class="font-size-16 font-weight-bold stat-bg-crit-dark w-100 py-1 text-center">
                                            {{$stats['gt40M']}}
                                        </div>
                                    </div>
                                </div>
                                @if(date('m') == $month && date('Y') == $year)
                                    <div class="mt-2 font-size-14 text-center">
                                        Days left in the month ({{friendly_month(date('Y-m-d'))}}):
                                        <b class="font-size-14">{{date('t') - date('j')}}</b>
                                    </div>
                                @endif
                            </div>
                        </div>
                    </form>
                </div>
                <div class="rpm-manager-table-container">
                    <table class="table table-sm table-bordered table-striped table-hover p-0 mb-4 min-width-1100px border-0" id="table-pm-manager-matrix">
                    <thead class="bg-light">
                    <tr>
                        <th class="border-top-0 border-bottom-0 border-left-0"></th>
                        <th class="border-top-0 border-bottom-0"></th>
                        <th class="border-top-0 border-bottom-0"></th>
                        @if($viewingAs !== 'RME')
                            <th class="border-top-0 border-bottom-0"></th>
                        @endif
                        @if($viewingAs === 'ADMIN')
                            <th class="border-top-0 border-bottom-0 rmgr-name-column"></th>
                            <th class="border-top-0 border-bottom-0 rmgr-name-column"></th>
                            <th class="border-top-0 border-bottom-0 rmgr-name-column"></th>
                        @endif
                        <th class="border-top-0 border-bottom-0"></th>
                        @if(date('m') == $month && date('Y') == $year) {{-- dslm --}}
                            <th class="border-top-0 border-bottom-0"></th>
                        @endif
                        <th class="border-top-0 border-bottom-0"></th>
                        <th class="border-top-0 border-bottom-0 bg-aliceblue text-nowrap" colspan="3"># Meas. Days</th>
                        <th class="border-top-0 border-bottom-0 text-nowrap" colspan="2">
                            @if($specificDate)
                                Values: <span class="text-info">{{$specificDate}}</span>
                            @else
                                Latest Value
                            @endif
                        </th>
                        @if($viewingAs !== 'RME')
                            <th class="border-top-0 border-bottom-0 bg-aliceblue text-nowrap" colspan="2">
                                @if($specificDate)
                                    Entries: <span class="text-info">{{$specificDate}}</span>
                                @else
                                    Latest Entry
                                @endif
                            </th>
                        @endif
                        <th class="border-top-0 border-bottom-0"></th>
                        @if($viewingAs !== 'RME')
                            <th class="border-top-0 border-bottom-0 bg-aliceblue" colspan="{{$viewingAs === 'ADMIN' ? 3 : 1}}">Time</th>
                        @endif
                        <th class="border-top-0 border-bottom-0 bg-aliceblue v-sep-before" colspan="{{$viewingAs === 'ADMIN' ? 3 : 1}}">Reimb.</th>
                        @if($viewingAs === 'ADMIN' && !(date('m') == $month && date('Y') == $year))
                            <th class="border-top-0 border-bottom-0 bg-aliceblue v-sep-before" colspan="3">Claim</th>
                        @endif
                        <th class="border-top-0 border-bottom-0 border-right-0 w-25"></th>
                    </tr>
                    <tr>
                        <th class="border-bottom-0 border-top border-left-0 text-right">#</th>
                        <th class="border-bottom-0 border-top">Name</th>
                        <th class="border-bottom-0 border-top">Age</th>
                        @if($viewingAs !== 'RME')
                            <th class="border-bottom-0 border-top">ICDs</th>
                        @endif
                        @if($viewingAs === 'ADMIN')
                            <th class="border-bottom-0 border-top">MCP</th>
                            <th class="border-bottom-0 border-top">RMM</th>
                            <th class="border-bottom-0 border-top">RME</th>
                        @endif
                        <th class="border-bottom-0 border-top">NV</th>
                        @if(date('m') == $month && date('Y') == $year)
                            <th class="border-bottom-0 border-top">DSLM</th>
                        @endif
                        <th class="border-bottom-0 border-top">DSLV</th>

                        <!--# Meas. Days-->
                        <th class="border-bottom-0 border-top">All</th>
                        <th class="border-bottom-0 border-top">BP</th>
                        <th class="border-bottom-0 border-top">WT</th>

                        <th class="border-bottom-0 border-top">BP</th>
                        <th class="border-bottom-0 border-top">WT</th>

                        @if($viewingAs !== 'RME')
                            <th class="border-bottom-0 border-top">Mine</th>
                            <th class="border-bottom-0 border-top">Others</th>
                        @endif

                        <th class="border-bottom-0 border-top text-nowrap">
                            <i class="fa fa-phone rotateh text-sm opacity-60"></i>
                            @if($viewingAs === 'ADMIN')
                                Inter.
                            @else
                                MCPI
                            @endif
                        </th>

                        <!--Time-->
                        @if($viewingAs !== 'RME')
                            @if($viewingAs === 'ADMIN' || $viewingAs === 'MCP')
                                <th class="border-bottom-0 border-top">MCP</th>
                            @endif
                            @if($viewingAs === 'ADMIN' || $viewingAs === 'RMM')
                                <th class="border-bottom-0 border-top">RMM</th>
                            @endif
                            @if($viewingAs === 'ADMIN')
                                <th class="border-bottom-0 border-top">Total</th>
                            @endif
                        @endif

                        <!--Reimb.-->
                        @if($viewingAs === 'ADMIN' || $viewingAs === 'MCP')
                            <th class="border-bottom-0 border-top v-sep-before">MCP</th>
                        @endif
                        @if($viewingAs === 'ADMIN' || $viewingAs === 'RMM')
                            <th class="border-bottom-0 border-top {{$viewingAs === 'RMM' ? 'v-sep-before' : ''}}">RMM</th>
                        @endif
                        @if($viewingAs === 'ADMIN' || $viewingAs === 'RME')
                            <th class="border-bottom-0 border-top {{$viewingAs === 'RME' ? 'v-sep-before' : ''}}">RME</th>
                        @endif

                        <!--Claim-->
                        @if($viewingAs === 'ADMIN' && !(date('m') == $month && date('Y') == $year))
                            <th class="border-bottom-0 border-top v-sep-before">4</th>
                            <th class="border-bottom-0 border-top">7</th>
                            <th class="border-bottom-0 border-top">8</th>
                        @endif

                        <th class="border-bottom-0 border-top border-right-0"></th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php
                    $daysRemaining = date('t') - date('j');
                    $index = $paginator->firstItem();
                    ?>
                    @foreach ($patients as $iPatient)
                        @include('app.practice-management.rpm-manager.row', compact('iPatient', 'index', 'month', 'year', 'viewingAs', 'daysRemaining', 'specificDate'))
                        <?php
                        $index++;
                        ?>
                    @endforeach
                    </tbody>
                </table>
                </div>
            </div>
        </div>
    </div>
    <script>
        (function () {

            window.RM_careMonths = {!! json_encode($careMonths) !!};

            function reInitMoes() {
                $('[moe][initialized]').removeAttr('initialized');
                initMoes();
            }

            let popoverVisible = false,
                wtPopoverVisibleForCM = false,
                bpPopoverVisibleForCM = false,
                wtPopoverShowTimer = false,
                bpPopoverShowTimer = false,
                wtPopoverHideTimer = false,
                bpPopoverHideTimer = false;

            function hideAllPopovers() {
                $('.rpm-manager-popover').removeClass('show');
                popoverVisible = false;
                bpPopoverVisibleForCM = false;
                wtPopoverVisibleForCM = false;
            }

            function init() {
                let parent = $('#practice-rpm-manager');

                parent.find('[cm-rte]').each(function() {

                    $(this).wrap(
                        $('<div class="border-left border-right rte-holder"/>')
                            .attr('data-shortcuts', '')
                    );

                    // give a unique id to this editor instance
                    var editorID = Math.ceil(Math.random() * 99999), fieldName = $(this).attr('data-name');

                    var el = this;
                    var existingContent = $(el).attr('data-content') ? $(el).attr('data-content') : $(el).html();
                    var quill = new Quill(el, {
                        theme: 'snow',
                        modules: stagQuillConfig
                    });

                    var toolbar = $(quill.container).prev('.ql-toolbar');

                    // add button for new shortcut
                    var newSCButton = $('<button class="btn bg-white btn-sm btn-default text-primary w-auto px-2 border py-0 ' +
                        'text-sm add-shortcut" data-editor-id="' + editorID + '">+ Shortcut</button>');
                    toolbar.append(newSCButton);

                    quill.root.innerHTML = existingContent;

                    $('<input type="hidden" name="' + fieldName + '">').val(existingContent).insertAfter(el);

                    quill.on('text-change', function(delta, oldDelta, source) {
                        $(el).next('[name="' + fieldName + '"]').val(quill.root.innerHTML);
                    });

                    $(quill.container)
                        .find('.ql-editor[contenteditable]')
                        .attr('data-field', fieldName)
                        .attr('data-editor-id', editorID)
                        .attr('with-shortcuts', 1);

                });

                parent
                    .off('mouseenter', '.rpm-manager-weight-popover-trigger')
                    .on('mouseenter', '.rpm-manager-weight-popover-trigger', function() {

                        let cmUID = $(this).closest('tr').attr('data-care-month-uid');

                        // if WT GP already visible for this care month, STOP
                        if(wtPopoverVisibleForCM === cmUID) {
                            console.log('Wt GP already visible for CM');
                            return false;
                        }
                        else {
                            hideAllPopovers();
                        }

                        // cancel any existing timers
                        if(wtPopoverShowTimer) { clearTimeout(wtPopoverShowTimer); wtPopoverShowTimer = false; }
                        if(bpPopoverShowTimer) { clearTimeout(bpPopoverShowTimer); bpPopoverShowTimer = false; }

                        wtPopoverShowTimer = setTimeout(() => {
                            $('.rpm-manager-popover').removeClass('show');
                            $('#rpm-manager-weight-popover-' + $(this).attr('data-uid')).addClass('show');
                            prepareMeasurementsPopover($(this).attr('data-uid'), 'weight');
                            popoverVisible = true;
                            wtPopoverVisibleForCM = cmUID;
                            bpPopoverVisibleForCM = false;
                        }, 500);

                        return false;
                    });

                parent
                    .off('mouseenter', '.rpm-manager-bp-popover-trigger')
                    .on('mouseenter', '.rpm-manager-bp-popover-trigger', function() {

                        let cmUID = $(this).closest('tr').attr('data-care-month-uid');

                        // if WT GP already visible for this care month, STOP
                        if(bpPopoverVisibleForCM === cmUID) {
                            console.log('BP GP already visible for CM');
                            return false;
                        }
                        else {
                            // hide any currently displays popups immediately
                            hideAllPopovers();
                        }

                        // cancel any existing timers
                        if(bpPopoverShowTimer) { clearTimeout(bpPopoverShowTimer); bpPopoverShowTimer = false; }
                        if(wtPopoverShowTimer) { clearTimeout(wtPopoverShowTimer); wtPopoverShowTimer = false; }

                        bpPopoverShowTimer = setTimeout(() => {
                            $('.rpm-manager-popover').removeClass('show');
                            $('#rpm-manager-bp-popover-' + $(this).attr('data-uid')).addClass('show');
                            prepareMeasurementsPopover($(this).attr('data-uid'), 'bp');
                            popoverVisible = true;
                            bpPopoverVisibleForCM = cmUID;
                            wtPopoverVisibleForCM = false;
                        }, 500);

                        return false;

                    });

                parent
                    .off('mouseleave', '.rpm-manager-weight-popover-trigger')
                    .on('mouseleave', '.rpm-manager-weight-popover-trigger', function() {
                        if(wtPopoverVisibleForCM) {
                            if(wtPopoverHideTimer) { clearTimeout(wtPopoverHideTimer); wtPopoverHideTimer = false; }
                            wtPopoverHideTimer = setTimeout(() => {
                                $('#rpm-manager-weight-popover-' + $(this).attr('data-uid')).removeClass('show');
                                popoverVisible = false;
                                wtPopoverVisibleForCM = false;
                            }, 750);
                        }
                        else if(wtPopoverShowTimer) {
                            clearTimeout(wtPopoverShowTimer);
                            wtPopoverShowTimer = false;
                        }
                        return false;
                    });

                parent
                    .off('mouseleave', '.rpm-manager-bp-popover-trigger')
                    .on('mouseleave', '.rpm-manager-bp-popover-trigger', function() {
                        if(bpPopoverVisibleForCM) {
                            if(bpPopoverHideTimer) { clearTimeout(bpPopoverHideTimer); bpPopoverHideTimer = false; }
                            bpPopoverHideTimer = setTimeout(() => {
                                $('#rpm-manager-bp-popover-' + $(this).attr('data-uid')).removeClass('show');
                                popoverVisible = false;
                                bpPopoverVisibleForCM = false;
                            }, 750);
                        }
                        else if(bpPopoverShowTimer) {
                            clearTimeout(bpPopoverShowTimer);
                            bpPopoverShowTimer = false;
                        }
                        return false;
                    });

                $(document)
                    .off('mousedown.discard-popover')
                    .on('mousedown.discard-popover', function(_e) {
                        if(!($(_e.target).closest('.rpm-manager-popover').length) && $('.rpm-manager-popover.show').length) {
                            setTimeout(() => {
                                hideAllPopovers();
                                if(bpPopoverShowTimer) { clearTimeout(bpPopoverShowTimer); bpPopoverShowTimer = false; }
                                if(wtPopoverShowTimer) { clearTimeout(wtPopoverShowTimer); wtPopoverShowTimer = false; }
                            }, 100);
                            return false;
                        }
                    });

                $(document)
                    .off('keydown.discard-bp-popover')
                    .on('keydown.discard-bp-popover', function(_e) {
                        if(_e.which === 27) {
                            setTimeout(() => {
                                hideAllPopovers();
                                if(bpPopoverShowTimer) { clearTimeout(bpPopoverShowTimer); bpPopoverShowTimer = false; }
                                if(wtPopoverShowTimer) { clearTimeout(wtPopoverShowTimer); wtPopoverShowTimer = false; }
                            }, 100);
                            return false;
                        }
                    });

                parent
                    .off('click', '.btn-quick-stamp')
                    .on('click', '.btn-quick-stamp', function() {
                        showMask();
                        $.post('/api/measurement/stamp', {
                            uid: $(this).attr('data-uid'),
                            memo: 'Reviewed'
                        }, _data => {
                            if(!hasResponseError(_data)) {
                                $(this).parent().html('<i class="fa fa-check text-sm"></i>' +
                                    '<span class="text-sm ml-1">Stamped</span>');
                            }
                        }, 'json').then(function() {
                            hideMask();
                        })
                        return false;
                    });

                parent
                    .off('click', '.rpm-manager-popover-trigger')
                    .on('click', '.rpm-manager-popover-trigger', function() {
                        if(popoverVisible) {
                            $('.rpm-manager-popover').removeClass('show');
                            popoverVisible = false;
                            bpPopoverVisibleForCM = false;
                            wtPopoverVisibleForCM = false;
                            return false;
                        }
                        openDynamicStagPopup('/patients/view/' + $(this).attr('data-client-uid') + '/care-months/view/' + $(this).attr('data-uid'),
                            'care-month-dashboard-' + $(this).attr('data-client-uid'),
                            $(this).attr('data-cm-title'),
                            'refresh-' + $(this).attr('data-uid'),
                            'tall overflow-visible'
                        );
                        return false;
                    });
            }

            function prepareMeasurementsPopover(_careMonthUid, _type) {
                let careMonth = RM_careMonths[_careMonthUid],
                    measurements = careMonth['measurements_' + _type + '_json'];
                if(!measurements) measurements = [];

                // graph
                if(_type === 'bp') {
                    initBpGraph(measurements, _careMonthUid);
                }
                else if(_type === 'weight') {
                    initWeightGraph(measurements, _careMonthUid);
                }

                // matrix
                let table = $('#rpm-manager-' + _type + '-matrix-' + _careMonthUid), tbody = table.find('tbody');
                tbody.empty();
                for (let i = 0; i < measurements.length; i++) {
                    let m = measurements[i];

                    // tr
                    let tr = $('<tr/>').attr('data-uid', m.uid);

                    // date, time
                    $('<td class="w-25 text-nowrap"/>').addClass('p-1 text-sm').text(m.date_display + ' ' + m.time_display).appendTo(tr);

                    // value
                    if(_type === 'bp') {
                        $('<td class="pl-2"/>').addClass('p-1 text-sm').text(m.sbpMmHg + '/' + m.dbpMmHg).appendTo(tr);
                    }
                    else if(_type === 'weight') {
                        $('<td class="pl-2"/>').addClass('p-1 text-sm').text(m.numericValue).appendTo(tr);
                    }

                    // stamp
                    // MCPs and RMMs get stamp UI
                    let stamp = '';
                    @if($viewingAs === 'MCP')
                    {{-- nop --}}
                    @elseif($viewingAs === 'RMM')
                    if(!m.hasBeenStampedByRmm) {
                        $('<td/>').addClass('p-1')
                            .append(
                                $('<a/>').addClass('text-sm btn-quick-stamp c-pointer text-nowrap').attr('data-uid', m.uid).text('Stamp')
                            )
                            .appendTo(tr);
                    }
                    else {
                        $('<td/>').addClass('p-1')
                            .append(
                                $('<i/>').addClass('fa fa-check text-sm')
                            )
                            .append(
                                $('<span/>').addClass('text-sm ml-1').text('Stamped')
                            )
                            .appendTo(tr);
                    }
                    @elseif($viewingAs === 'ADMIN')
                    stamp = $('<div class="d-flex align-items-baseline flex-nowrap" />');
                    if(!m.hasBeenStampedByMcp) {
                        stamp.append('<i class="fa fa-circle text-sm opacity-35 text-danger"></i>');
                    }
                    else {
                        stamp.append('<i class="fa fa-circle text-sm opacity-35 text-success"></i>');
                    }
                    stamp.append('<span class="ml-1 mr-2 text-sm">MCP</span>');
                    if(!m.hasBeenStampedByRmm) {
                        stamp.append('<i class="fa fa-circle text-sm opacity-35 text-danger"></i>');
                    }
                    else {
                        stamp.append('<i class="fa fa-circle text-sm opacity-35 text-success"></i>');
                    }
                    stamp.append('<span class="ml-1 text-sm">RMM</span>');
                    $('<td/>').append(stamp).appendTo(tr);
                    @endif

                    tr.appendTo(tbody);
                }
            }

            function filterLatestMeasurementEachDay(_measurements) {
                let filtered = [], addedDates = {};
                for (let i = _measurements.length - 1; i >=0 ; i--) {
                    if(!addedDates[_measurements[i].date_standard]) {
                        addedDates[_measurements[i].date_standard] = 1;
                        filtered.push(_measurements[i]);
                    }
                }
                return filtered;
            }

            function initBpGraph(_measurements, _careMonthUid) {
                let filtered = filterLatestMeasurementEachDay(_measurements);
                $('#rpm-manager-bp-graph-container-' + _careMonthUid)
                    .empty()
                    .append('<div id="rpm-manager-bp-graph-' + _careMonthUid + '"></div>');
                c3.generate({
                    size: {
                        height: 120,
                        width: 400
                    },
                    bindto: '#rpm-manager-bp-graph-' + _careMonthUid,
                    data: {
                        x: 'x',
                        columns: [
                            ['x', ...filtered.map(_x => _x.date_standard)],
                            ['Systolic BP', ...filtered.map(_x => _x.sbpMmHg)],
                            ['Diastolic BP', ...filtered.map(_x => _x.dbpMmHg)]
                        ]
                    },
                    axis: {
                        x: {
                            type: 'timeseries'/*,
                            tick: {
                                format: '%Y-%m-%d',
                                multiline: true,
                                fit: true,
                                rotate: -45
                            },*/
                        },
                        y: {
                            show: true,
                            tick: {
                                count: 5,
                                format: function (x) { return Math.ceil(x); }
                            },
                            label: {
                                text: 'BP',
                                position: 'outer-middle'
                            },
                            min: 40,
                            max: 220
                        },
                    },
                    legend: {
                        show: false
                    }/*,
                    regions: [
                        {axis: 'y', start: 100, end: 130, class: 'safe-region', label: 'Safe Systolic BP: 100 to 130 mmHg'},
                        {axis: 'y', start: 60, end: 90, class: 'safe-region', label: 'Safe Diastolic BP: 60 to 90 mmHg'}
                    ]*/
                });
            }

            function initWeightGraph(_measurements, _careMonthUid) {
                let filtered = filterLatestMeasurementEachDay(_measurements);
                $('#rpm-manager-weight-graph-container-' + _careMonthUid)
                    .empty()
                    .append('<div id="rpm-manager-weight-graph-' + _careMonthUid + '"></div>');
                c3.generate({
                    size: {
                        height: 120,
                        width: 400
                    },
                    bindto: '#rpm-manager-weight-graph-' + _careMonthUid,
                    data: {
                        x: 'x',
                        columns: [
                            ['x', ...filtered.map(_x => _x.date_standard)],
                            ['Weight', ...filtered.map(_x => _x.numericValue)]
                        ]
                    },
                    axis: {
                        x: {
                            type: 'timeseries'/*,
                            tick: {
                                format: '%Y-%m-%d',
                                multiline: true,
                                fit: true,
                                rotate: -45
                            },*/
                        },
                        y: {
                            show: true,
                            tick: {
                                count: 5,
                                format: function (x) { return Math.ceil(x); }
                            },
                            label: {
                                text: 'Weight',
                                position: 'outer-middle'
                            },
                            /*min: 70,
                            max: 250*/
                        },
                    },
                    legend: {
                        show: false
                    },
                    regions: [
                        // {axis: 'y', start: 100, end: 140, class: 'safe-region', label: 'Safe Weight: 100 to 140 lbs'},
                    ]
                });
            }

            function prepareEntriesPopup(_careMonthUid, _type) {
                let careMonth = RM_careMonths[_careMonthUid],
                    entries = careMonth[_type + 'Entries'];

                // misc
                $('#rpm-manager-' + _type + '-entries-popup-title').text(careMonth.client_name + ' (' + careMonth.dob + ')');
                $('#rpm-manager-' + _type + '-entries-caremonth').text('Care Month of: ' + careMonth.month_display + '  |  ' + (_type === 'my' ? 'My Time Entries' : 'Other Time Entries'));

                // matrix
                if(!entries) entries = [];
                let table = $('#rpm-manager-' + _type + '-entries-matrix'), tbody = table.find('tbody');
                tbody.empty();
                for (let i = 0; i < entries.length; i++) {
                    let e = entries[i];

                    // tr
                    let tr = $('<tr/>').attr('data-uid', e.uid);

                    // pro
                    if(_type === 'other') {
                        $('<td/>').text(e.proNameFirst + ' ' + e.proNameLast).appendTo(tr);
                    }

                    // date
                    $('<td/>').text(e.effectiveDate.month + '/' + e.effectiveDate.day + '/' + e.effectiveDate.year).appendTo(tr);

                    // minutes
                    $('<td/>').text(Math.round(e.timeInSeconds/60)).appendTo(tr);

                    // communicated
                    $('<td/>').text('-').appendTo(tr);

                    // comments
                    $('<td/>').text($('<div/>').html(e.contentText).text()).appendTo(tr);

                    tr.appendTo(tbody);
                }
            }

            addMCInitializer('practice-rpm-manager', init, '#practice-rpm-manager');
        }).call(window);
    </script>
@endsection
