@extends ('layouts/template')

@section('content')

    <div id="practice-supply-orders-ready-to-ship" class="p-3 mcp-theme-1">
        <div class="card">

            <div class="card-header px-3 py-3 d-flex align-items-center bg-white">
                <strong class="font-size-14">
                    Supply Orders - Ready to Ship ({{$counts['supplyOrdersReadyToShip']}})
                </strong>
                <span class="mx-3 text-secondary">|</span>
                <a href="{{route('practice-management.supply-orders-shipment-underway')}}">Shipment Underway ({{$counts['supplyOrdersShipmentUnderway']}})</a>
                <span class="mx-3 text-secondary">|</span>
                <a href="{{route('practice-management.supply-orders')}}">All ({{$counts['supplyOrders']}})</a>
<!--                <a href="{{route('practice-management.supply-orders-ready-to-ship')}}" class="ml-auto">Clear Filters</a>-->
            </div>
            <div class="card-body p-0">
                <table class="table table-sm table-condensed p-0 m-0" style="table-layout: fixed">
                    <thead class="bg-light">
                    <tr>
<!--                        <th class="border-0">Date</th>-->
                        <th class="border-0">Patient</th>
                        <th class="border-0">Address</th>
                        <th class="border-0">Item(s)</th>
                        <th class="border-0">Devices</th>
                        <th class="border-0">Actions</th>
                    </tr>
                    </thead>
                    <div>
                    <?php
                    $prevClientAndAddress = null;
                    $shipmentIndex = 0;
                    ?>
                    @foreach ($supplyOrders as $supplyOrder)
                        <?php
                            $patient = $supplyOrder->client;
                        $currentClientAndAddress = implode('|', [$supplyOrder->client_id, $supplyOrder->mailing_address_full]);
                        $sameClientAndAddress = false;
                        ?>
                        @if($currentClientAndAddress !== $prevClientAndAddress)
                            <tr class="sep"><td colspan="4"></td></tr>
                            <?php
                            $shipmentIndex++;
                            $prevClientAndAddress = $currentClientAndAddress;
                            ?>
                        @else
                            <?php $sameClientAndAddress = true; ?>
                        @endif
                        <tr class="{{$supplyOrder->is_cancelled ? 'bg-light' : ''}}"
                            data-client-uid="{{$supplyOrder->client->uid}}"
                            data-address-line1="{{$supplyOrder->mailing_address_line1}}"
                            data-address-line2="{{$supplyOrder->mailing_address_line2}}"
                            data-address-city="{{$supplyOrder->mailing_address_city}}"
                            data-address-state="{{$supplyOrder->mailing_address_state}}"
                            data-address-zip="{{$supplyOrder->mailing_address_zip}}"
                            data-shipment-index="{{$shipmentIndex}}"
                            data-supply-order-uid="{{$supplyOrder->uid}}">
<!--                            <td class="align-top border-top-0">{{friendlier_date_time($supplyOrder->created_at)}}</td>-->
                            <td class="align-top border-top-0">
                                @if(!$sameClientAndAddress)
                                    <a href="{{route('patients.view.supply-orders',['patient'=>$supplyOrder->client, 'supplyOrder'=>$supplyOrder])}}">{{$supplyOrder->client->displayName()}}</a>
                                @endif
                            </td>
                            <td class="align-top border-top-0">
                                @if(!$sameClientAndAddress)
                                    {!! $supplyOrder->mailing_address_full ? implode(" ", [$supplyOrder->mailing_address_line1 . ' ' . $supplyOrder->mailing_address_line2, $supplyOrder->mailing_address_city . ' ' . $supplyOrder->mailing_address_state . ' ' . $supplyOrder->mailing_address_zip]) : '-'  !!}
                                @endif
                            </td>
                            <td class="align-top border-top-0">
                                {{$supplyOrder->product->title}}
                                <span class="text-secondary text-sm">(Created: {{friendlier_date_time($supplyOrder->created_at)}})</span>
                                <div moe relative class="d-block">
                                    <a start
                                       show><i class="fa fa-times"></i></a>
                                    <form url="/api/supplyOrder/cancel" right>
                                        <input type="hidden" name="uid" value="{{ $supplyOrder->uid }}">
                                        <div class="mb-2">
                                           <p>Cancel?</p>
                                        </div>
                                        <div class="d-flex align-items-center">
                                            <button class="btn btn-sm btn-primary mr-2" submit>Yes</button>
                                            <button class="btn btn-sm btn-default mr-2 border" cancel>No
                                            </button>
                                        </div>
                                    </form>
                                </div>
                            </td>
                            <td>
                                @if(!$sameClientAndAddress)
                                    @foreach($patient->devices as $device)
                                        <div>
                                            <div class="px-2">{{ friendly_date_time($device->device->created_at) }}</div>
                                            <div class="px-2">{{ $device->device->category }}</div>
                                            <div class="px-2">{{ $device->device->imei }}</div>
                                        </div>
                                    @endforeach
                                @endif
                            </td>
                            <td class="align-top border-top-0">
                                @if(!$sameClientAndAddress)
                                    <a href="#" id="generate-shipment">Generate Shipment</a>
                                @endif
                            </td>
                        </div>
                    @endforeach
                    </tbody>
                </table>
                <div>
                    {{$supplyOrders->links()}}
                </div>
            </div>
        </div>
    </div>

    <script>
        (function() {

            function hasError (_data) {
                let msg = 'Unknown error!';
                if (_data) {
                    if (_data.success) return false;
                    else if (_data.message) msg = _data.message;
                }
                toastr.error(msg);
                return true;
            }

            function init() {
                $(document)
                    .off('click', '#generate-shipment')
                    .on('click', '#generate-shipment', function() {
                        let row = $(this).closest('tr');
                        $.post('/api/shipment/create', {
                            clientUid: row.attr('data-client-uid'),
                            mailingAddressLine1: row.attr('data-address-line1'),
                            mailingAddressLine2: row.attr('data-address-line2'),
                            mailingAddressCity: row.attr('data-address-city'),
                            mailingAddressState: row.attr('data-address-state'),
                            mailingAddressZip: row.attr('data-address-zip'),
                        }, (_data) => {
                            if(!hasError(_data)) {
                                let addToShipmentRequests = [],
                                    shipmentIndex = row.attr('data-shipment-index'),
                                    rows = $('tr[data-shipment-index="' + shipmentIndex + '"]'),
                                    totalSupplyOrders = rows.length,
                                    succeededSupplyOrders = 0;
                                rows.each(function() {
                                    let supplyOrderUid = $(this).attr('data-supply-order-uid');
                                    addToShipmentRequests.push((function () {
                                        return $.post('/api/supplyOrder/putInShipment', {
                                            uid: supplyOrderUid,
                                            shipmentUid: _data.data
                                        }, (_data) => {
                                            if(!hasError(_data)) {
                                                succeededSupplyOrders++;
                                            }
                                        }, 'json');
                                    })());
                                });
                                Promise.all(addToShipmentRequests).then(() => {
                                    // all requests finished successfully
                                    fastReload();
                                }).catch(() => {
                                    // all requests finished but one or more failed
                                    alert(succeededSupplyOrders + ' supply requests added to shipment. ' +
                                        (totalSupplyOrders - succeededSupplyOrders) + ' could not be added to shipment'
                                    );
                                    fastReload();
                                })
                            }
                        }, 'json');

                        // 1. create shipment
                            // 2. put each supply-order in shipment
                                // 3 . reload once all done
                    });
            }

            addMCInitializer('practice-supply-orders-ready-to-ship', init, '#practice-supply-orders-ready-to-ship')

        }).call(window);
    </script>
@endsection
