<?php
$patientEngagementColorCodes = @Config::get('constants.client_engagement_status_color_codes');
?>
<div>
    @include('app.admin.patients-results-view-options')
</div>
<div class="table-responsive border-top" style="height: calc(100vh - 280px)" id="admin-patients-list-extended">
    <table class="table p-0 m-0 table-sm table-striped table-bordered border-bottom text-nowrap">
        <thead class="bg-light">
            <tr>
                <th class="border-0">@include('app.practice-management._sort_header', [
                    'route' => route('admin.patients'),
                    'label' => 'Status',
                    'key' => 'client_engagement_status_category',
                ])</th>
                <th class="border-0 width-90px text-secondary">#</th>
                <th class="border-0">@include('app.practice-management._sort_header', [
                    'route' => route('admin.patients'),
                    'label' => 'Name',
                    'key' => 'name_first',
                ])</th>
                @if ($pro->pro_type == 'ADMIN')
                    <th class="border-0 text-secondary">MCP</th>
                    {{-- <th class="border-0">NA</th> --}}
                    {{-- <th class="border-0">Initiative</th> --}}
                    {{-- <th class="border-9">Status</th> --}}
                    {{-- <th class="border-0">Source</th> --}}
                @endif
                <th class="border-0 text-secondary">State</th>
                <th class="border-0 text-secondary">Insurance</th>
                @if ($performer->pro->pro_type == 'ADMIN')
                    <th class="border-0 text-secondary">Ded.</th>
                @endif
                <th class="border-0 text-secondary">Age</th>
                <th class="border-0">@include('app.practice-management._sort_header', [
                    'route' => route('admin.patients'),
                    'label' => 'Last Visit',
                    'key' => 'most_recent_completed_mcp_note_date',
                ])</th>
                <th class="border-0 text-secondary"></th>
                <th class="border-0 text-secondary">Last Memo</th>
                <th class="border-0 text-secondary">Notes</th>
                <th class="border-0 text-secondary">Next Appt.</th>
                <th class="border-0">@include('app.practice-management._sort_header', [
                    'route' => route('admin.patients'),
                    'label' => 'BP/Pulse Timestamp',
                    'key' => 'most_recent_cellular_bp_measurement_at',
                ])</th>
                <th class="border-0">@include('app.practice-management._sort_header', [
                    'route' => route('admin.patients'),
                    'label' => 'Weight Timestamp',
                    'key' => 'most_recent_cellular_weight_measurement_at',
                ])</th>
                <th class="border-0">@include('app.practice-management._sort_header', [
                    'route' => route('admin.patients'),
                    'label' => 'Created',
                    'key' => 'created_at',
                ])</th>
                <th class="border-0 text-secondary">Assigned On</th>
                <th class="border-0 text-secondary">NA</th>

                <th class="border-0 text-secondary">Temp. Gun</th>
                <th class="border-0 text-secondary">Pulse Ox.</th>
                <th class="border-0 text-secondary">Cell. Bp</th>
                <th class="border-0 text-secondary">Wt. Scale</th>
                <th class="border-0 text-secondary">Companies</th>


                {{-- <th class="border-0">DOB</th> --}}
                {{-- <th class="border-0">Age</th> --}}
                {{-- <th class="border-0">Sex</th> --}}
                {{-- <th class="border-0">BMI</th> --}}
                {{-- <th class="border-0">BP</th> --}}
                {{-- <th class="border-0"><i class="fa fa-heartbeat"></i></th> --}}
                {{-- <th class="border-0">Pulse</th> --}}
                {{-- <th class="border-0">Weight</th> --}}
                {{-- <th class="border-0"># Cellular Measurements</th> --}}
                {{-- <th>Scale <i class="fa fa-battery"></i></th> --}}
                {{-- <th class="border-0">RPM</th> --}}
                {{-- <th class="border-0 d-none">Last Weight-In</th> --}}
                {{-- <th class="border-0 d-none">Last BP</th> --}}
                {{-- <th class="border-0">Email Address</th> --}}
            </tr>
        </thead>
        <tbody>
            @foreach ($patients as $patient)
                <tr>
                    <td
                        style="background-color:<?= @$patientEngagementColorCodes[$patient->client_engagement_status_category] ?: '' ?>;">
                        {{ $patient->client_engagement_status_category == 'DUMMY' ? 'Test Record' : $patient->client_engagement_status_category }}
                    </td>
                    <td>
                        <a native target="_blank" href="{{ route('patients.view.dashboard', $patient) }}">
                            {{ $patient->chart_number }}
                        </a>
                    </td>
                    <td>
                        <div class="d-flex align-items-baseline flex-nowrap">
                            <span>{{ $patient->displayName() }}</span>
                            <?php $latestMemo = $patient->latestMemo(); ?>
                            <div class="on-hover-show d-inline-block on-hover-opaque ml-auto mr-1">
                                <i class="fa fa-info-circle ml-1 {{ $latestMemo ? '' : 'opacity-35' }}"></i>
                                <div class="on-hover-content py-2 pl-3 text-nowrap text-dark"
                                    style="left:0;right:auto;">
                                    @if ($latestMemo)
                                        <p class="mb-1 font-weight-bold text-secondary">Last Memo:
                                            {{ $latestMemo->category }}</p>
                                        <div class="text-wrap mb-1">{{ $latestMemo->content }}</div>
                                        <div class="text-secondary text-sm mb-1">
                                            {{ friendly_date_time($latestMemo->created_at) }}</div>
                                        @if ($latestMemo->createdBy && $latestMemo->createdBy->pro)
                                            <div class="text-secondary text-sm">By
                                                {{ $latestMemo->createdBy->pro->displayName() }}</div>
                                        @endif
                                    @else
                                        <div class="text-secondary">No client memos.</div>
                                    @endif
                                </div>
                            </div>
                        </div>
                    </td>
                    @if ($pro->pro_type == 'ADMIN')
                        <td>
                        @if(@$patient->mcp)
                            {{ $patient->mcp->displayName() }}
                            @if(!$patient->mcp->is_hcp)
                                <small class="text-danger font-weight-bold"><i class="fas fa-exclamation-triangle fa-fw"></i> {{ $patient->mcp->name_first }} is no longer HCP.</small>
                            @endif
                        @else
                            --
                        @endif
                        </td>
                        {{-- <td>{{@$patient->defaultNaPro ? $patient->defaultNaPro->displayName() : '--'}}</td> --}}
                        {{-- <td>{{$patient->initiative}}</td> --}}
                        {{-- <td>{{$patient->client_engagement_status_category == 'DUMMY'? 'Test Record': $patient->client_engagement_status_category}}</td> --}}
                        {{-- <td>{{$patient->source}}</td> --}}
                    @endif
                    <td>{{ $patient->mailing_address_state }}</td>
                    <td class="{{ $patient->mpb_remaining === 0 ? 'deductible-zero' : '' }}">
                        @include('app.patient.coverage_column_renderer', ['patient' => $patient])

                    </td>
                    @if ($performer->pro->pro_type == 'ADMIN')
                        <td>
                            <small class="d-block text-sm text-muted">
                                <span class="font-weight-bold">{{ format_number(@$patient->mpb_remaining) }}</span>
                            </small>
                        </td>
                        <td>{{ $patient->age_in_years }}</td>
                    @endif
                    <td>
                        {{ friendly_date($patient->most_recent_completed_mcp_note_date) }}
                    </td>
                    <td>
                        @if ($patient->lastMcpAppointment)
                            <small class="text-muted">{{ $patient->lastMcpAppointment->pro->displayName() }}</small>
                        @endif
                    </td>
                    <td>
                        <?php $lastMemo = $patient->lastMemo(); ?>
                        @if ($lastMemo)
                            {{ friendly_date($lastMemo->created_at) }}
                            <?php
                        $daysAgo = date_diff(date_create($lastMemo->created_at), date_create('now'))->days;
                        if ($daysAgo > 0) {
                            ?>
                            <span class="text-sm text-secondary">({{ $daysAgo }} day{{ $daysAgo > 1 ? 's' : '' }}
                                ago)</span>
                            <?php
                        }
                        ?>
                        @else
                            -
                        @endif
                    </td>
                    <td class="p-0 pb-1">
                        <div if-details-view>
                            @if (count($patient->activeNotes))
                                <?php $noteIndex = 0; ?>
                                @foreach ($patient->activeNotes as $note)
                                    <?php $noteIndex++; ?>
                                    <div class="mt-1 bg-white border p-2">
                                        <div class="d-flex align-items-baseline">
                                            <span
                                                class="mr-2 font-weight-bold text-secondary">{{ $noteIndex }}.</span>
                                            <a native target="_blank"
                                                href="/patients/view/{{ $patient->uid }}/notes/view/{{ $note->uid }}">
                                                <b>{{ friendly_date_time($note->effective_dateest, false) }}</b>
                                            </a>
                                            <span class="mx-2 text-sm">/</span>
                                            <span>{{ $note->new_or_fu_or_na === 'NEW' ? 'New' : 'Follow-up' }}</span>
                                            <span class="mx-2 text-sm">/</span>
                                            <span>{{ $note->hcpPro ? $note->hcpPro->name_display : '-' }}</span>
                                            <span class="mx-2 text-sm">/</span>
                                            <span>{{ noteMethodDisplay($note->method) }}</span>
                                            @if ($note->hcpPro && $note->is_signed_by_hcp)
                                                <span class="mx-2 text-sm">/</span>
                                                <span class="text-success">Signed</span>
                                            @endif
                                        </div>
                                        <?php
                                        $bills = \App\Models\Bill::where('note_id', $note->id)
                                            ->where('bill_service_type', '<>', 'GENERIC')
                                            ->where('is_cancelled', false)
                                            ->orderBy('id', 'desc')
                                            ->get();
                                        ?>
                                        @if (count($bills))
                                            <hr class="my-2">
                                            <div class="d-flex align-items-start text-sm">
                                                <b class="text-secondary width-60px">Bills:</b>
                                                <div class="ml-2 flex-grow-1">
                                                    @foreach ($bills as $bill)
                                                        <div class="border border-info bg-aliceblue p-1 mb-1">
                                                            <div class="d-flex align-items-baseline">
                                                                <span>{{ $bill->code }}</span>
                                                                <span class="mx-2 text-sm">/</span>
                                                                <span>
                                                                    @if (strpos(strtolower($bill->code), 'treatment services') !== false)
                                                                        <?php
                                                                        $totalSeconds = $bill->number_of_units * 3600;
                                                                        $remainder = $totalSeconds % 60;
                                                                        if ($remainder !== 0) {
                                                                            if ($remainder < 30) {
                                                                                $totalSeconds = $totalSeconds - $remainder;
                                                                            } else {
                                                                                $totalSeconds = $totalSeconds + (60 - $remainder);
                                                                            }
                                                                        }
                                                                        ?>
                                                                        {{ time_in_hrminsec($totalSeconds) }}
                                                                    @else
                                                                        @if (!!$bill->number_of_units)
                                                                            {{ $bill->number_of_units }} unit(s)
                                                                        @else
                                                                            -
                                                                        @endif
                                                                    @endif
                                                                </span>
                                                                @if ($bill->is_signed_by_hcp)
                                                                    <span class="mx-2 text-sm">/</span>
                                                                    <span class="d-block text-nowrap">
                                                                        <i class="fa fa-check"></i>
                                                                        Signed
                                                                    </span>
                                                                @endif
                                                                @if ($bill->is_verified)
                                                                    <span class="mx-2 text-sm">/</span>
                                                                    <span class="d-block text-nowrap">
                                                                        <i class="fa fa-check"></i>
                                                                        Verified
                                                                    </span>
                                                                @endif
                                                                @if (!$bill->has_hcp_been_paid)
                                                                    <span class="mx-2 text-sm">/</span>
                                                                    <div class="text-nowrap mt-1 screen-only">
                                                                        <span class="">Expected: </span>
                                                                        <span
                                                                            class="font-weight-bold">${{ $bill->hcp_expected_payment_amount }}</span>
                                                                    </div>
                                                                @else
                                                                    <span class="mx-2 text-sm">/</span>
                                                                    <div class="text-nowrap mt-1 screen-only">
                                                                        <span class="">Paid: </span>
                                                                        <span
                                                                            class="font-weight-bold">${{ $bill->hcp_payment_amount }}</span>
                                                                    </div>
                                                                @endif
                                                            </div>
                                                        </div>
                                                    @endforeach
                                                </div>
                                            </div>
                                        @endif
                                        <?php
                                        $claims = \App\Models\Claim::where('note_id', $note->id)
                                            ->where('is_cancelled', false)
                                            ->orderBy('id', 'desc')
                                            ->get();
                                        ?>
                                        @if (count($claims))
                                            <hr class="my-2">
                                            <div class="d-flex align-items-start text-sm">
                                                <b class="text-secondary width-60px">Claims:</b>
                                                <div class="ml-2 flex-grow-1 border border-success">
                                                    <table class="table table-sm tabe-striped mb-0 border-0">
                                                        <tbody>
                                                            @foreach ($claims as $claim)
                                                                @if ($claim->status !== 'CANCELLED' || request('claims-filter') === 'all')
                                                                    <tr
                                                                        class="{{ $claim->status === 'CANCELLED' ? 'text-secondary bg-light on-hover-opaque' : '' }}">
                                                                        <td class="p-0 border-left border-right">
                                                                            @if ($claim->lines->count())
                                                                                <table
                                                                                    class="table table-sm table-condensed border-0 mb-0">
                                                                                    <thead>
                                                                                        <tr class="bg-light">
                                                                                            <th class="border-0">CPT
                                                                                            </th>
                                                                                            <th class="border-0">DOS
                                                                                            </th>
                                                                                            <th class="border-0">ICDs
                                                                                            </th>
                                                                                        </tr>
                                                                                    </thead>
                                                                                    <tbody class="">
                                                                                        @foreach ($claim->lines as $line)
                                                                                            <tr class="claim-line">
                                                                                                <td>{{ $line->cpt }}
                                                                                                    <div>Units:
                                                                                                        <b>{{ !@$line->units ? 1 : $line->units }}</b>
                                                                                                    </div>
                                                                                                </td>
                                                                                                <td class="text-nowrap">
                                                                                                    {{ friendlier_date($line->date_of_service) }}
                                                                                                </td>
                                                                                                <td>
                                                                                                    @if (count($line->claimLineIcds))
                                                                                                        @foreach ($line->claimLineIcds as $icd)
                                                                                                            <div>
                                                                                                                <b class="c-pointer border-secondary border-bottom"
                                                                                                                    title="{{ $icd->description }}">{{ $icd->code }}</b>
                                                                                                            </div>
                                                                                                        @endforeach
                                                                                                    @else
                                                                                                        <p>No ICDs set
                                                                                                        </p>
                                                                                                    @endif
                                                                                                </td>
                                                                                            </tr>
                                                                                        @endforeach
                                                                                    </tbody>
                                                                                </table>
                                                                            @else
                                                                                <p>No lines for this claim</p>
                                                                            @endif
                                                                        </td>
                                                                        <td class="border-right p-0">

                                                                            <!-- payer, company, location -->
                                                                            <div class="p-1">
                                                                                <div class="mt-1">
                                                                                    <div>
                                                                                        <b>{{ $claim->primaryPayer ? $claim->primaryPayer->name : '-' }}</b>
                                                                                        /
                                                                                        {{ $claim->status ? $claim->status : 'Status not set' }}
                                                                                    </div>
                                                                                </div>

                                                                                <div class="mt-1">
                                                                                    {{ $claim->companyPro && $claim->companyPro->company ? $claim->companyPro->company->name : '-' }}
                                                                                </div>

                                                                                <div class="mt-1">
                                                                                    {{ $claim->companyLocation ? $claim->companyLocation->line1 . ', ' . $claim->companyLocation->city : '-' }}
                                                                                </div>
                                                                            </div>
                                                                        </td>
                                                                    </tr>
                                                                @endif
                                                            @endforeach
                                                        </tbody>
                                                    </table>
                                                </div>
                                            </div>
                                        @endif
                                    </div>
                                @endforeach
                            @endif
                        </div>
                        <div if-grid-view class="p-1">
                            {{ count($patient->activeNotes) }}
                        </div>
                    </td>
                    <td>{{ $patient->nextMcpAppointment ? friendly_date_time($patient->nextMcpAppointment->raw_date . ' ' . $patient->nextMcpAppointment->raw_start_time) : '' }}
                        <span if-grid-view>
                            @if ($patient->nextMcpAppointment)
                                {{-- {{$patient->nextMcpAppointment->status}} --}}
                            @elseif($patient->mostRecentCompletedMcpNote && $patient->mostRecentCompletedMcpNote->follow_up_not_needed_memo)
                                <div class="w-100 text-nowrap overflow-hidden text-ellipsis max-width-170px"
                                    title="{{ $patient->mostRecentCompletedMcpNote->follow_up_not_needed_memo }}">
                                    <b>No</b>
                                    {{ $patient->mostRecentCompletedMcpNote->follow_up_not_needed_memo }}
                                </div>
                            @endif
                        </span>
                        <div if-details-view>
                            @if ($patient->nextMcpAppointment)
                                {{ $patient->nextMcpAppointment->status }}
                            @elseif($patient->mostRecentCompletedMcpNote && $patient->mostRecentCompletedMcpNote->follow_up_not_needed_memo)
                                <b>No</b>
                                {{ $patient->mostRecentCompletedMcpNote->follow_up_not_needed_memo }}
                            @endif
                        </div>
                    </td>
                    <td>{{ friendlier_date_time($patient->most_recent_cellular_bp_measurement_at) }}</td>
                    <td>{{ friendlier_date_time($patient->most_recent_cellular_weight_measurement_at) }}</td>
                    <td>
                        <div title="{{ friendly_date_time($patient->created_at) }}">
                            {{ friendly_date_time($patient->created_at, false) }}</div>
                        <div class="mt-1" if-details-view>
                            By <span>{{ $patient->creator ? $patient->creator->displayName() : '-' }}</span>
                        </div>
                    </td>
                    <td>{{ $patient->getMcpAssignedOn() }}</td>
                    <td>{{ $patient->defaultNaPro ? $patient->defaultNaPro->displayName() : '-' }}</td>

                    <td>{{ $patient->temparatureGunDeliveryStatus() }}</td>
                    <td>{{ $patient->pulseOximeterDeliveryStatus() }}</td>
                    <td>{{ $patient->hasBPDevice() ? 'DELIVERED' : '' }}</td>
                    <td>{{ $patient->hasWeightScaleDevice() ? 'DELIVERED' : '' }}</td>

                    {{-- <td>{{ friendly_date_time($patient->dob, false) }}</td> --}}
                    {{-- <td>{{ $patient->age_in_years ?  $patient->age_in_years : '-' }}</td> --}}
                    {{-- <td>{{ $patient->sex }}</td> --}}
                    {{-- <td>
                    <div class="d-none d-dflex flex-column">
                        @if ($patient->usual_bmi_min && $patient->usual_bmi_max)
                            <small class="text-muted">BMI (Usual):
                                <b>{{ $patient->usual_bmi_min }}</b> {{ $patient->usual_bmi_min_category }} to
                                <b>{{ $patient->usual_bmi_max }}</b> {{ $patient->usual_bmi_max_category }}</small>
                        @endif
                        @if ($patient->ideal_bmi)
                            <small class="text-muted">BMI (Ideal)
                                <b>{{ $patient->ideal_bmi }}</b> {{ $patient->ideal_bmi_category }}</small>
                        @endif
                    </div>
                </td> --}}
                    {{-- <td>
                    @if ($patient->most_recent_cellular_bp_measurement_at)
                        {{ $patient->most_recent_cellular_bp_sbp_mm_hg }}
                        / {{ $patient->most_recent_cellular_bp_dbp_mm_hg }}
                    @endif
                </td> --}}
                    {{-- <td><?= $patient->most_recent_cellular_bp_value_irregular ? '<i class="fa fa-heartbeat"></i>' : '' ?></td> --}}
                    {{-- <td>{{ $patient->most_recent_cellular_bp_value_pulse }}</td> --}}
                    {{-- <td>{{ $patient->most_recent_cellular_weight_value ? round($patient->most_recent_cellular_weight_value, 2) : '--' }}</td> --}}
                    {{-- <td class="d-none text-nowrap">
                    <?php $m = $patient->lastMeasurementOfType('Wt. (lbs.)'); ?>
                    {{$m && $m->value ? round($m->value, 2) : '-'}}
                </td> --}}
                    {{-- <td class="d-none text-nowrap">
                    <?php $m = $patient->lastMeasurementOfType('BP'); ?>
                    {{$m && $m->value ? $m->value : '-'}}
                </td> --}}
                    {{-- <td>{{count($patient->cellularMeasurements)}}</td> --}}
                    {{-- <td>{{$patient->email_address}}</td> --}}

                    <td>
                        <div class="d-flex flex-column">
                            @foreach ($patient->companyClients as $companyClient)
                            <span>{{ $companyClient->company->name }}</span>
                            @endforeach
                        </div>
                    </td>
                </tr>
            @endforeach

            @if (count($patients) === 0)
                <tr>
                    <td colspan="24">No records found!</td>
                </tr>
            @endif
        </tbody>
    </table>
</div>
<div class="px-3 pt-3 d-flex align-items-center">
    {{ $patients->withQueryString()->links() }}
    <div class="ml-4 mb-3">Showing <b>{{ $patients->firstItem() }}</b> to <b>{{ $patients->lastItem() }}</b> (page
        {{ $patients->currentPage() }}) of <b>{{ $patients->total() }}</b> patients</div>
</div>

<script>
    (function() {
        function init() {
            let panning = false,
                prevX = false,
                prevY = false;
            $('#admin-patients-list-extended')
                .off('mousedown.pan')
                .on('mousedown.pan', function(_e) {
                    if (panning && panning.length) return false;
                    if (_e.ctrlKey) {
                        prevX = _e.screenX;
                        prevY = _e.screenY;
                        panning = $(this);
                        return false;
                    }
                });
            $(document)
                .off('mousemove.pan')
                .on('mousemove.pan', function(_e) {
                    if (!panning || !panning.length) return;
                    let deltaX = _e.screenX - prevX,
                        deltaY = _e.screenY - prevY;
                    panning.scrollTop(panning.scrollTop() - deltaY);
                    panning.scrollLeft(panning.scrollLeft() - deltaX);
                    prevX = _e.screenX;
                    prevY = _e.screenY;
                });
            $(document)
                .off('mouseup.pan')
                .on('mouseup.pan', function(_e) {
                    panning = false;
                });

            $(document)
                .off('click.enable-grid', '.enable-grid')
                .on('click.enable-grid', '.enable-grid', function() {
                    $('#admin-patients-list-extended>table').addClass('stag-compact-grid');
                    localStorage.adminPatientsTableFormat = 'grid';
                    return false;
                });

            $(document)
                .off('click.disable-grid', '.disable-grid')
                .on('click.disable-grid', '.disable-grid', function() {
                    $('#admin-patients-list-extended>table').removeClass('stag-compact-grid');
                    localStorage.adminPatientsTableFormat = 'regular';
                    return false;
                });

            if (localStorage.adminPatientsTableFormat !== 'regular') {
                $('#admin-patients-list-extended>table').addClass('stag-compact-grid');
            } else {
                $('#admin-patients-list-extended>table').removeClass('stag-compact-grid');
            }
        }

        addMCInitializer('admin-patients-list-extended', init, '#admin-patients-list-extended');
    }).call(window);
</script>
