<div class="popup-content-container px-3 d-flex flex-column" style="max-height: calc(100vh - 180px)" id="measurements-mass-stamp">
    @if(count($measurementsPendingStamping))
    <div class="d-flex align-items-baseline">
        <div>
            <a href="#" class="btn btn-primary text-white font-weight-bold btn-stamp-all">Stamp All On Page</a>
        </div>
        <div class="ml-auto d-inline-flex align-items-baseline">
            <span class="mr-3"><b>{{$measurementsPendingStamping->total()}}</b> measurements remaining</span>
            {{ $measurementsPendingStamping->onEachSide(0)->withQueryString()->links() }}
        </div>
    </div>
    @endif
    <div class="flex-grow-1 overflow-auto border mb-3">
    @if($measurementsPendingStamping && count($measurementsPendingStamping))
        <table class="table table-sm table-striped mb-0">
            <thead>
            <tr>
                <th class="border-bottom-0 border-top-0 text-secondary">Patient</th>
                <th class="border-bottom-0 border-top-0 text-secondary">Type</th>
                <th class="border-bottom-0 border-top-0 text-secondary">Value</th>
                <th class="border-bottom-0 border-top-0 text-secondary">Timestamp</th>
            </tr>
            </thead>
            <tbody>
            @foreach($measurementsPendingStamping as $row)
                <tr class="stamp-row"
                    data-client-uid="{{$row->client->uid}}"
                    data-caremonth-uid="{{$row->careMonth->uid}}"
                    data-uid="{{$row->uid}}"
                    data-date="{{date_short_with_tz_from_timestamp_divide1000($row->ts, 'EASTERN')}}">
                    <td class="pl-2">
                        <a native target="_blank" href="{{ route('patients.view.dashboard', $row->client) }}">
                            {{$row->client->displayName()}}
                        </a>
                    </td>
                    <td class="text-nowrap">
                        {{$row->label}}
                    </td>
                    <td>
                        @if($row->label === 'BP')
                            {{ $row->sbp_mm_hg }}/{{ $row->dbp_mm_hg }}
                        @elseif($row->label === 'Wt. (lbs.)')
                            {{ round(floatval($row->numeric_value), 2) }}
                        @endif
                    </td>
                    <td class="text-secondary">
                        {{ friendly_date_time_short_with_tz_from_timestamp_divide1000($row->ts, 'EASTERN') }} EST
                    </td>
                </tr>
            @endforeach
            </tbody>
        </table>
    @else
        <div class="p-3">
            No measurement pending stamping
        </div>
    @endif
    </div>
</div>
<script>
    (function() {
        function init() {
            $('.btn-stamp-all')
                .off('click')
                .on('click', function() {

                    let clients = {};
                    $('tr.stamp-row').each(function() {
                        if(!clients[$(this).attr('data-client-uid')]) {
                            clients[$(this).attr('data-client-uid')] = {
                                clientUid: $(this).attr('data-client-uid'),
                                uids: [],
                                careMonths: {},
                            };
                        }
                        clients[$(this).attr('data-client-uid')].uids.push($(this).attr('data-uid'));
                        if(!clients[$(this).attr('data-client-uid')].careMonths[$(this).attr('data-caremonth-uid')]) {
                            clients[$(this).attr('data-client-uid')].careMonths[$(this).attr('data-caremonth-uid')] = [];
                        }
                        if(clients[$(this).attr('data-client-uid')].careMonths[$(this).attr('data-caremonth-uid')].indexOf($(this).attr('data-date')) === -1) {
                            clients[$(this).attr('data-client-uid')].careMonths[$(this).attr('data-caremonth-uid')].push($(this).attr('data-date'));
                        }
                    });

                    // 1 bulk stamp req per client
                        // 1 add entry req per unique date per caremonth per client

                    showMask();

                    let apiRequests = [];

                    for(let clientUid in clients) {
                        if(clients.hasOwnProperty(clientUid)) {

                            // bulk stamp all measurements for this client
                            let payload = {
                                clientUid: clientUid,
                                toStamp: clients[clientUid].uids.map(_x => {
                                    return {
                                        measurementUid: _x,
                                        memo: null,
                                        detailJson: null
                                    }
                                }),
                                shouldAddEntry: 0
                            };
                            apiRequests.push($.ajax({
                                url: "/api/measurement/bulkStamp",
                                type: 'post',
                                data: JSON.stringify(payload),
                                contentType:"application/json; charset=utf-8",
                                dataType:"json",
                                success: function(jsonSaveResponse) {},
                                error: function(jqXHR, textStatus, errorThrown) {}
                            }));

                            // for each caremonth of this client, add entry to each unique day with measurement
                            for(let careMonthUid in clients[clientUid].careMonths) {
                                if(clients[clientUid].careMonths.hasOwnProperty(careMonthUid)) {
                                    for (let i = 0; i < clients[clientUid].careMonths[careMonthUid].length; i++) {
                                        payload = {
                                            careMonthUid: careMonthUid,
                                            proUid: '{{$pro->uid}}',
                                            effectiveDate: clients[clientUid].careMonths[careMonthUid][i],
                                            timeInSeconds: 75
                                        };
                                        apiRequests.push($.ajax({
                                            url: "/api/careMonthEntry/createForRm",
                                            type: 'post',
                                            data: payload,
                                            dataType:"json",
                                            success: function(jsonSaveResponse) {},
                                            error: function(jqXHR, textStatus, errorThrown) {}
                                        }));
                                    }
                                }
                            }

                        }
                    }


                    Promise.all(apiRequests).then(() => {
                        hideMask();
                        refreshDynamicStagPopup();
                    });

                    return false;
                });
        }
        addMCInitializer('measurements-mass-stamp', init, '#measurements-mass-stamp')
    }).call(window);
</script>

