@extends ('layouts/template')

@section('content')

<div class="p-3 mcp-theme-1" id="processing-bill-matrix">

    <div class="card">

        <div class="card-header px-2 py-1">
            <div class="font-weight-bold text-nowrap mb-2">
                <i class="fas fa-user"></i>
                Processing Bills
            </div>
            <div class="d-flex align-items-center mb-2">
                <div class="width-200px">
                    <select provider-search data-pro-uid="{{ @$targetPro->uid }}" name="proUid" class="form-control form-control-sm mr-auto width-200px min-width-unset" onchange="return billsFilter('', this.value, true)">
                        <option value="" {{!@$targetPro ? 'selected' : ''}}>All Pros</option>
                    </select>
                </div>
                <div class="width-300px ml-2 d-inline-flex">
                    <select name="filter" class="form-control form-control-sm min-width-unset flex-grow-1" onchange="return billsFilter('f', this.value)">
                        <option {{request()->input('f') === '' ? 'selected' : ''}} value="">All Bills</option>
                        <option {{request()->input('f') === 'verified' ? 'selected' : ''}} value="verified">Verified
                            Only
                        </option>
                        <option {{request()->input('f') === 'not-verified' ? 'selected' : ''}} value="not-verified">Not
                            Verified Only
                        </option>
                    </select>
                    <select name="filter" class="form-control form-control-sm min-width-unset flex-grow-1 ml-2" onchange="return billsFilter('t', this.value)">
                        <option {{!request()->input('t') || request()->input('t') === 'hcp' ? 'selected' : ''}} value="hcp">
                            HCP Bills
                        </option>
                        <option {{request()->input('t') === 'na' ? 'selected' : ''}} value="na">Generic Bills</option>
                    </select>
                </div>
                <div class="ml-4 d-inline-flex align-items-center">
                    <span class="mr-2">Bal Post Date</span>
                    <input type="date" value="{{request()->input('bs')}}" onchange="return billsFilter('bs', this.value)" class="form-control form-control-sm width-150px" name="bpdFrom">
                    <span class="mx-2">to</span>
                    <input type="date" value="{{request()->input('be')}}" onchange="return billsFilter('be', this.value)" class="form-control form-control-sm width-150px" name="bpdTo">
                </div>
                <button class="ml-auto btn btn-sm btn-primary pay-selected-pros px-3 font-weight-bold" disabled>Pay Selected</button>
            </div>
            <div class="d-flex align-items-center">
                <select name="filter" class="form-control form-control-sm width-200px" onchange="return billsFilter('c', this.value)">
                    <option {{!request()->input('c') ? 'selected' : ''}} value="">All Companies</option>
                    @foreach($companies as $company)
                    <option {{request()->input('c') == $company->id ? 'selected' : ''}} value="{{$company->id}}">
                        {{$company->name}}
                    </option>
                    @endforeach
                </select>
                <select name="filter" class="form-control form-control-sm width-300px ml-2 " onchange="return billsFilter('s', this.value)">
                    <option {{!request()->input('s') ? 'selected' : ''}} value="">All Services</option>
                    @foreach($codes as $code)
                    <option {{request()->input('s') == $code->code ? 'selected' : ''}} value="{{$code->code}}">
                        {{$code->code}}
                    </option>
                    @endforeach
                </select>
                @if(@$targetPro || count(array_filter(request()->all(), function($_x) { return !!$_x && $_x !== 'na' && $_x !== 'hcp';})))
                <a href="/practice-management/processing-bill-matrix" class="ml-4">Clear Filters</a>
                @endif
            </div>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-sm table-striped table-hover p-0 m-0">
                    <thead class="bg-light">
                        <tr>
                            <th class="border-bottom-0 border-top-0">
                                <label class="d-flex align-items-center m-0">
                                    <input type="checkbox" class="chk-all-bills" /> <span class="ml-2">All</span>
                                </label>
                            </th>
                            <th class="border-bottom-0 border-top-0">Context</th>
                            <th class="border-bottom-0 border-top-0">Effective Date</th>
                            <th class="border-bottom-0 border-top-0">Bal Post Date</th>
                            @if(!request()->input('t') || request()->input('t') === 'hcp')
                            <th class="border-bottom-0 border-top-0">Pro</th>
                            @elseif(request()->input('t') === 'na')
                            <th class="border-bottom-0 border-top-0">Pro</th>
                            @endif
                            <th class="border-bottom-0 border-top-0">Client</th>
                            <th class="border-bottom-0 border-top-0">Insurance</th>
                            <th class="border-bottom-0 border-top-0">State</th>
                            <th class="border-bottom-0 border-top-0">Company Pro</th>
                            <th class="border-bottom-0 border-top-0">Code</th>
                            <th class="border-bottom-0 border-top-0">Units</th>
                            <th class="border-bottom-0 border-top-0">Verified?</th>
                            <th class="border-bottom-0 border-top-0">Cancelled?</th>
                            @if(!request()->input('t') || request()->input('t') === 'hcp')
                            <th class="border-bottom-0 border-top-0">HCP Expected Amount</th>
                            @elseif(request()->input('t') === 'na')
                            <th class="border-bottom-0 border-top-0">NA Expected Amount</th>
                            @endif
                            <th class="border-bottom-0 border-top-0">Pro Signed?</th>
                            <th class="border-bottom-0 border-top-0"></th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach ($bills as $row)
                        <tr>
                            <td class="align-top">
                                @if($row->is_verified)
                                <input type="checkbox" data-uid="{{$row->uid}}" class="chk-bill align-middle" />
                                @endif
                            </td>
                            <td>
                                @if($row->note)
                                <a href="/patients/view/{{ $row->client->uid }}/notes/view/{{ $row->note->uid }}">
                                    Note
                                </a>
                                @elseif($row->careMonth)
                                    <div>
                                        <a href="/patients/view/{{$row->client->uid}}/care-months/view/{{$row->careMonth->uid}}">
                                            Care Month
                                        </a>
                                    </div>
                                    
                                @elseif($row->client)
                                <a href="/patients/view/{{ $row->client->uid }}">
                                    Chart
                                </a>
                                @else
                                    Admin.
                                @endif
                               
                                @if($row->is_verified)
                                    @if(!request()->input('t') || request()->input('t') === 'hcp')
                                        @if(!$row->hcp_company_pro_id)
                                            <div class="mt-1 text-danger text-sm">
                                                <i class="fa fa-exclamation-triangle"></i>
                                                <span class="">Company pro not set!</span>
                                            </div>
                                        @endif
                                    @elseif(request()->input('t') === 'na')
                                        {{-- TODO --}}
                                    @endif
                                @endif
                            </td>
                           
                            <td>{{friendly_date($row->effective_date)}}</td>
                            <td>{{friendly_date($row->balance_post_date)}}</td>
                            <td>

                                @if(!request()->input('t') || request()->input('t') === 'hcp')
                                    {{$row->hcp->name_last}}, {{$row->hcp->name_first}}
                                @elseif(request()->input('t') === 'na')
                                    {{$row->genericPro->name_last}}, {{$row->genericPro->name_first}}
                                @endif

                            </td>
                            <td>
                                @if($row->client)
                                {{$row->client->name_last}}, {{$row->client->name_first}}
                                @endif
                            </td>
                            <td>
                            @if($row->client)
                                @include('app.patient.coverage_column_renderer', ['patient'=>$row->client])
                            @endif
                            </td>
                            <td>
                                @if($row->client)
                                {{$row->client->mailing_address_state}}
                                @endif
                            </td>
                            <td>
                                    
                                    @if(!request()->input('t') || request()->input('t') === 'hcp')
                                        <div class="mt-1 text-secondary">
                                            @if($row->hcpCompanyPro)
                                                {{$row->hcpCompanyPro ? $row->hcpCompanyPro->company->name : '-'}}
                                            @else 
                                                <i>[company pro is not set]</i>
                                            @endif
                                            <div moe class="ml-1">
                                                <a class="text-primary" href="" show start><i class="fa fa-edit"></i></a>
                                                <form url="/api/bill/swapHcpCompanyPro">
                                                    <input type="hidden" name="uid" value="{{$row->uid}}">
                                                    <div class="mb-2">
                                                        <select name="hcpCompanyProUid" class="form-control form-control-sm">
                                                            <option value="">-- select --</option>
                                                            @foreach($row->hcp->companyPros as $companyPro)
                                                                <option value="{{$companyPro->uid}}">{{$companyPro->company->name}}</option>
                                                            @endforeach
                                                        </select>
                                                    </div>
                                                    <div class="mb-0">
                                                        <button class="btn btn-primary btn-sm" submit>Submit</button>
                                                        <button class="btn btn-default border btn-sm" cancel>Cancel</button>
                                                    </div>
                                                </form>
                                            </div>
                                        </div>
                                    @elseif(request()->input('t') === 'na')
                                        
                                        <div class="mt-1 text-secondary">
                                            @if($row->genericCompanyPro && $row->genericCompanyPro->company)
                                                {{$row->genericCompanyPro->company->name}}
                                            @else 
                                                <i>[company pro is not set]</i>
                                            @endif
                                            <div moe class="">
                                                <a class="text-primary" href="" show start><i class="fa fa-edit"></i></a>
                                                <form url="/api/bill/swapGenericCompanyPro">
                                                    <input type="hidden" name="uid" value="{{$row->uid}}">
                                                    <div class="mb-2">
                                                        <select name="genericCompanyProUid" class="form-control form-control-sm">
                                                            <option value="">-- select --</option>
                                                            @foreach($row->genericPro->companyPros as $companyPro)
                                                                <option value="{{$companyPro->uid}}">{{$companyPro->pro->displayName() . ' / ' . $companyPro->company->name}}</option>
                                                            @endforeach
                                                        </select>
                                                    </div>
                                                    <div class="mb-0">
                                                        <button class="btn btn-primary btn-sm" submit>Submit</button>
                                                        <button class="btn btn-default border btn-sm" cancel>Cancel</button>
                                                    </div>
                                                </form>
                                            </div>
                                        </div>
                                        
                                    @endif
                                        
                                </td>
                            <td>{{$row->code}}
                                @if($row->generic_target_entity_type && $row->generic_target_entity_uid)
                                <div class="mt-1 text-sm text-secondary">{{$row->generic_target_entity_type}}</div>
                                @endif
                            </td>
                            <td>{{str_contains($row->code, 'Treatment Services') || str_contains($row->code, 'Administrative Services') ? ceil((float) $row->number_of_units * 60) . ' mins' : $row->number_of_units}}</td>
                            <td>
                                {!! $row->is_verified ? '<i class="fa fa-check text-success"></i> ' . friendly_date($row->marked_verified_at, true) : 'No' !!} 
                                @if(!$row->is_cancelled)
                                    @if(!$row->is_verified)
                                        <div class="d-block mt-1" moe>
                                            <a href="" show start>Mark Verified</a>
                                            <form url="/api/bill/markAsVerified">
                                                <input type="hidden" name="uid" value="{{$row->uid}}">
                                                <p>Mark As Verified?</p>
                                                <div class="mb-0">
                                                    <button class="btn btn-success btn-sm" submit>Submit</button>
                                                    <button class="btn btn-default border btn-sm" cancel>Cancel</button>
                                                </div>
                                            </form>
                                        </div>
                                    @else
                                        <div class="d-block mt-1" moe>
                                            <a class="" href="" show start>Undo</a>
                                            <form url="/api/bill/undoMarkAsVerified">
                                                <input type="hidden" name="uid" value="{{$row->uid}}">
                                                <p>Undo Mark As Verified?</p>
                                                <div class="mb-0">
                                                    <button class="btn btn-success btn-sm" submit>Submit</button>
                                                    <button class="btn btn-default border btn-sm" cancel>Cancel</button>
                                                </div>
                                            </form>
                                        </div>
                                    @endif
                                @endif
                            </td>

                            <td>
                                @if($row->is_cancelled)
                                    <div class="text-warning-mellow font-weight-bold">Cancelled</div>
                                    @if($row->cancellation_memo)
                                        <div class="text-dark text-sm font-italic my-1">{{$row->cancellation_memo}}</div>
                                    @endif
                                    @if($row->is_cancelled_by_administrator)
                                        <div class="text-secondary text-sm text-nowrap">(by Administrator)</div>
                                    @endif
                                    <div moe class="mt-1">
                                        <a class="text-nowrap" href="" show start>Update Memo</a>
                                        <form url="/api/bill/updateCancellationMemo">
                                            <input type="hidden" name="uid" value="{{$row->uid}}">
                                            <p>Update Cancellation Memo</p>
                                            <div class="mb-2">
                                                <textarea class="text form-control form-control-sm" name="cancellationMemo"
                                                        placeholder="">{{$row->cancellation_memo ? $row->cancellation_memo : ($pro->pro_type === 'ADMIN' ? 'Please contact billing.' : '')}}</textarea>
                                            </div>
                                            <div>
                                                <button class="btn btn-success btn-sm" submit>Submit</button>
                                                <button class="btn btn-default border btn-sm" cancel>Cancel</button>
                                            </div>
                                        </form>
                                    </div>
                                @else
                                    <div class="d-block" moe relative="">
                                        <a class="text-danger" href="" show start>Cancel</a>
                                        <form url="/api/bill/markCancelled" right="">
                                            <input type="hidden" name="uid" value="{{$row->uid}}">
                                            <p class="mb-2">Cancel this bill?</p>
                                            <div class="mb-2">
                                                <label class="mb-1 text-secondary">Cancellation Memo</label>
                                                <textarea type="text" name="memo" placeholder="Memo" class="form-control form-control-sm">@if($pro->pro_type === 'ADMIN')Please contact billing.@endif</textarea>
                                            </div>
                                            <div class="mb-0">
                                                <button class="btn btn-danger btn-sm" submit>Yes</button>
                                                <button class="btn btn-default border btn-sm" cancel>No</button>
                                            </div>
                                        </form>
                                    </div>
                                @endif
                            </td>
                            
                            @if(!request()->input('t') || request()->input('t') === 'hcp')
                            <td>${{$row->hcp_expected_payment_amount}}</td>
                            @elseif(request()->input('t') === 'na')
                            <td>${{number_format($row->generic_pro_expected_payment_amount, 2)}}</td>
                            @endif
                            @if(!request()->input('t') || request()->input('t') === 'hcp')
                            <td>{{$row->is_signed_by_hcp ? 'Yes' : 'No'}}</td>
                            @elseif(request()->input('t') === 'na')
                            <td>{{$row->is_signed_by_generic_pro ? 'Yes' : 'No'}}</td>
                            @endif
                            <td>
                                @if($row->is_verified)
                                <a href="#" data-uid="{{$row->uid}}" class="pay-bill">Pay</a>
                                @endif
                            </td>
                        </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    <div class="mt-3">
        {{$bills->withQueryString()->links()}}
    </div>
</div>
<script>
    (function() {
        window.billsFilter = function(_key, _value, _isClient = false) {

            <?php
            $keys = ['f', 'bs', 'be', 't', 'c', 's'];
            $currentParams = [];
            for ($i = 0; $i < count($keys); $i++) {
                if (!!request()->input($keys[$i])) {
                    $currentParams[$keys[$i]] = request()->input($keys[$i]);
                }
            }
            ?>

            let targetProUid = _isClient ? _value : $('[provider-search]').attr('data-pro-uid'),
                base = '/practice-management/processing-bill-matrix' + (targetProUid ? '/' + targetProUid : ''),
                keys = ['f', 'bs', 'be', 't', 'c', 's'].filter(_x => _x !== _key),
                currentParams = {!!json_encode($currentParams) !!},
                url = [];

            // base
            url.push(base);
            url.push('?');

            // params
            let getParams = [];
            for (let i = 0; i < keys.length; i++) {
                if (currentParams[keys[i]]) {
                    getParams.push(keys[i] + '=' + encodeURIComponent(currentParams[keys[i]]));
                }
            }

            // new params
            getParams.push(_key + '=' + encodeURIComponent(_value));

            // generate url
            url.push(getParams.join('&'));

            // go
            fastLoad(url.join(''));

            return false;
        };

        function init() {
            $('.pay-bill')
                .off('click')
                .on('click', function() {
                    showMask();
                    $.post('/api/bill/payUnpaidProsOnBillExpectedAmount', {
                        uid: $(this).attr('data-uid')
                    }, _data => {
                        if (!hasResponseError(_data)) {
                            toastr.success('Bill paid successfully');
                            fastReload();
                        }
                    }).then(function() {
                        hideMask();
                    });
                    return false;
                });
            $('.pay-selected-pros')
                .off('click')
                .on('click', function() {
                    if (!$('.chk-bill:checked').length) return false;
                    showMask();
                    let uids = [];
                    $('.chk-bill:checked').each(function() {
                        uids.push($(this).attr('data-uid'));
                    });
                    $.post('/api/bill/bulkPayUnpaidProsOnBillExpectedAmount', {
                        billUids: uids.join('|')
                    }, _data => {
                        if (!hasResponseError(_data)) {
                            toastr.success('Selected bills paid successfully');
                            fastReload();
                        }
                    }).then(function() {
                        hideMask();
                    });
                    return false;
                });
            $('.chk-bill')
                .off('change')
                .on('change', function() {
                    console.log('123')
                    $('.pay-selected-pros').prop('disabled', !$('.chk-bill:checked').length);
                    $('.chk-all-bills').prop('checked', ($('.chk-bill:checked').length === $('.chk-bill').length));
                    return false;
                });
            $('.chk-all-bills')
                .off('change')
                .on('change', function() {
                    console.log('12')
                    $('.chk-bill')
                        .prop('checked', this.checked)
                        .first()
                        .trigger('change');
                    return false;
                });
        }
        addMCInitializer('processing-bill-matrix', init, '#processing-bill-matrix');
    }).call(window);
</script>
@endsection
