@extends('layouts.app')

@section('content')
<div class="mb-4 d-flex">
    <h3 class="text-muted my-auto"><b><i class="fa fa-barcode mr-2"></i>Order Booking</b></h3>
</div>
<div class="card">
    <div class="card-body">
        <form action="{{ route('booking.index') }}" method="GET">
            <div class="form-group">
                <input type="text" name="order" class="form-control" value="{{ Request::input('order') }}" placeholder="Order #">
            </div>
            <div class="form-group">
                <button class="btn btn-primary btn-sm">Fetch Order</button>
            </div>
        </form>
        <?php $itemsIds = []; ?>
        @if(Request::has('order'))
        <?php 
            $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

            $order_token = substr(str_shuffle(str_repeat($pool, 5)), 0, 26);
        ?>
<form id="item_grid" action="{{ URL::to(route('booking.store')) }}" method="POST">
            @csrf
            <input type="hidden" name="order_token" placeholder="order_token" value="{{ $order_token }}">
            <input type="hidden" name="remarks" placeholder="remarks" value="Handle With Care">
            <input type="hidden" name="order_number" placeholder="order_number" value="{{ Request::input('order') }}">
            <input type="hidden" name="id" placeholder="id" value="{{ $order->id }}">
            <input type="hidden" name="order_id" placeholder="order_id" value="{{ $order->order_id }}">
            <input type="hidden" name="apiId" placeholder="apiId" value="{{ $apiId }}">
            <input type="hidden" name="country" placeholder="country" value="{{ $order->country }}">
            <input type="hidden" name="country_code" placeholder="country_code" value="{{ $order->country_code }}">
            <input type="hidden" name="postcode" placeholder="postcode" value="{{ $order->postcode }}">
            <input type="hidden" name="international_subtotal" placeholder="international_subtotal" value="{{ $order->international_subtotal }}">
            <input type="hidden" name="international_shipping_amount" placeholder="international_shipping_amount" value="{{ $order->international_shipping_amount }}">
            <div class="row">
                <div class="col-12 col-md-6">
                    <ul class="booking-general-details my-4 list-unstyled">
                        <li>
                            <div class="text"><i class="fas fa-user"></i> Name: <b>{{ ucfirst($order->customer_name) }}</b></div>
                            <input type="hidden" name="customer_name" value="{{ $order->customer_name }}">
                        </li>
                        <li>
                            {{-- <div class="text"><i class="fas fa-city"></i> City: <b>{{ ucfirst($order->customer_city) }}</b></div> --}}
                            <div class="text"><i class="fas fa-city"></i> City:<input type="text" name="destination_city" value="{{ $order->customer_city }}"></div>
                        </li>
                        <li>
                            <div class="text"><i class="fas fa-address-card"></i> Address: <b>{{ ucfirst($order->customer_address) }}</b></div>
                            <input type="hidden" name="customer_address" value="{{ $order->customer_address }}">
                        </li>
                       
                        <li>
                            {{-- <div class="text"><i class="fas fa-phone-square"></i> Phone: <b>{{ $order->customer_phone }}</b></div> --}}
                            <div class="text"><i class="fas fa-phone-square"></i> Phone: <input type="text" name="customer_mobile_no" value="{{ validate_customer_phone($order->customer_phone) }}"></div>
                        </li>
                        <li>
                            <div class="text"><i class="fas fa-phone-square"></i> Email: <b>{{ is_null($order->customer_email)? 'user@makeupcityshop.com' : $order->customer_email }}</b></div>
                            <input type="hidden" name="customer_email" value="{{ is_null($order->customer_email)? 'user@makeupcityshop.com' : $order->customer_email }}">
                        </li>
                    </ul>   
                </div>
                <div class="col-12 col-md-6">
                    <ul class="booking-general-details my-4 list-unstyled">
                        <li>
                            <div class="text"><i class="fas fa-money-bill"></i> Subtotal: <b>{{ number_format($order->subtotal, 2) }}</b></div>
                            <input type="hidden" name="order_subtotal" value="{{ $order->subtotal }}">
                        </li>
                        <li>
                            <div class="text"><i class="fas fa-shipping-fast"></i> Shipping Amount: <b>{{ number_format($order->shipping_amount, 2) }}</b></div>
                            <input type="hidden" name="order_shipping_amount" value="{{ $order->shipping_amount }}">
                        </li>
                        <li>
                            <div class="text"><i class="fas fa-tag"></i> Tax Amount: <b>{{ number_format($order->tax_amount, 2) }}</b></div>
                            <input type="hidden" name="order_tax_amount" value="{{ $order->tax_amount }}">
                        </li>
                        <li>
                            <div class="text"><i class="fas fa-tags"></i> Discount Amount: <b>{{ number_format($order->discount_amount, 2) }}</b></div>

			    <input type="hidden" name="order_discount_amount" value="{{ $order->discount_amount }}">

 <input type="hidden" name="order_total_amount" value="{{ $order->total_line_items_price }}">			</li>
                        <li>
                            <div class="text"><i class="fas fa-money-check"></i> Payment Method: <b>{{ $order->payment_method }}</b></div>
                            <input type="hidden" name="order_payment_method" class="order_payment_method_check"  value="{{ $order->payment_method }}">
                        </li>
                        <li>
                            <div class="text"><i class="fas fa-truck"></i> Shipping Method: <b>{{ !is_null($api)? $api->name : 'DHL' }}</b></div>
                            <input type="hidden" name="order_shipping_method" value="{{ !is_null($api)? $api->name : 'DHL' }}">
                        </li>
                    </ul>
                </div>
            </div>
            @if($order->shipping_courier == 'Forrun(Express) - Express Delivery (within 2 hours)' && Auth::user()->id != 88)
                <div class="alert alert-danger">
                    This order is Forrun(Express) - Express Delivery and cannot be booked by this account. 
                </div>
            @else
            <div class="scan-items">
                <div class="form-group">
                    <input id="scanupc" type="text" class="form-control scan-control" placeholder="Scan UPC">
                </div>
            </div>
            <span class="package-info"></span>
            <span onclick="increasePackage();" style="color: rgb(0, 132, 255)"> - Add Package</span>
            @endif
            <div class="table-wrapper">
                <table class="table item-table table-responsive">
                    <thead class=" text-primary">
                        <th>Upc</th>
                        <th>Sku</th>
                        <th>Weight</th>
                        <th>Row Total</th>
                        <th>Ordered Quantity</th>
                        <th>Remaining Quantity</th>
                        <th>Scanned Quantity</th>
                        <th>Remarks</th>
                        <th>Package</th>
                    </thead>
                    <tbody>
                        @if(!is_null($api) && $api->name == 'GoPanda' && $order->customer_city == 'Jaranwala')
                            @foreach($orderItems as $orderItem)
                                @if(checkBrandCode($orderItem->brand_id))
                                    @if(checkIfItemIsShipped($orderItem->order_product_id))
                                        @if(checkIfItemInventory($orderItem->upc))
                                            @php
                                                $itemsIds[] = $orderItem->order_product_id;
                                                $extraUpcs = [];
                                                $upcSku = DB::table('sku_upc_example')->where('sku', $orderItem->item_sku)->get();
                                                if(!is_null($upcSku)){
                                                    foreach($upcSku as $val){
                                                        $extraUpcs[] = $val->upc;
                                                    }
                                                }
                                                $allUpcs = array_filter(array_unique(array_merge([$orderItem->upc], $extraUpcs)));
                                            @endphp
                                            <input type="hidden"
                                                   name="item_id[]"
                                                   class="js-item-upc"
                                                   data-upc="{{ $orderItem->upc }}"
                                                   data-upc-aliases="{{ implode(',', $allUpcs) }}"
                                                   value="{{ $orderItem->order_product_id }}">
                                            <input type="hidden" name="hscode[]" class="form-control" value="{{ $orderItem->hscode }}">
                                            <input type="hidden" name="international_row_total[]" class="form-control" value="{{ $orderItem->international_row_total }}">
                                            <input type="hidden" name="item_name[]" class="form-control" value="{{ $orderItem->item_name }}">
                                            <input type="hidden" name="order_product_id[]" class="form-control" value="{{ $orderItem->order_product_id }}">
                                            <tr class="{{ $orderItem->order_product_id }}">
                                                <td>
                                                    {{ implode(',', $allUpcs) }}
                                                    <input type="hidden" name="upc[]" value="{{ $orderItem->upc }}">
                                                </td>
                                                <td>
                                                    {{ $orderItem->item_sku }}
                                                    <input type="hidden" name="sku[]" value="{{ $orderItem->item_sku }}">
                                                </td>
                                                <td>
                                                    {{ $orderItem->item_weight }}
                                                    <input type="hidden" name="item_weight[]" value="{{ $orderItem->item_weight }}">
                                                </td>
                                                <td>
                                                    {{ number_format(($orderItem->item_row_total), 2) }}
                                                    <input type="hidden" name="item_row_total[]" value="{{ $orderItem->item_row_total }}">
                                                    <input type="hidden" name="item_discount[]" value="{{ $orderItem->item_discount_amount }}">
                                                    <input type="hidden" name="item_tax[]" value="{{ $orderItem->item_tax_amount }}">
                                                </td>
                                                <td class="ordered_quantity_{{ $orderItem->order_product_id }}">
                                                    <div>{{ floor($orderItem->item_quantity_ordered) }}</div>
                                                    <input type="hidden" name="quantity_ordered[]" value="{{ floor($orderItem->item_quantity_ordered) }}">
                                                </td>
                                                <td class="remaining_quantity_{{ $orderItem->order_product_id }}">
                                                    <div>{{ floor($orderItem->item_quantity_ordered) - floor($orderItem->qty_confirmed) }}</div>
                                                    <input type="hidden" name="quantity_remaining[]" value="{{ floor($orderItem->item_quantity_ordered) - floor($orderItem->qty_confirmed) }}">
                                                </td>
                                                <td class="confirmed_quantity_{{ $orderItem->order_product_id }}">
                                                    <div>{{ floor($orderItem->qty_confirmed) }}</div>
                                                    <input type="hidden" name="quantity_confirmed[]" value="{{ floor($orderItem->qty_confirmed) }}">
                                                </td>
                                                <td class="remarks_{{ $orderItem->order_product_id }}">
                                                    <select class="form-control remarks_change" data-id="{{ $orderItem->order_product_id }}" name="item_remarks[]"> 
                                                        <option value="Pending">Pending</option> 
                                                        <option value="Shipped">Shipped</option> 
                                                        <option value="Out of Stock">Out of Stock</option> 
                                                    </select>
                                                </td>
                                                <td class="package_{{ $orderItem->order_product_id }}">
                                                    <input type="text" name="package[]" class="form-control">
                                                </td>
                                            </tr>
                                        @endif
                                    @endif
                                @endif
                            @endforeach
                        @else
                            @foreach($orderItems as $orderItem)
                                    @if(checkIfItemIsShipped($orderItem->order_product_id) == true)
                                        @php
                                            $itemsIds[] = $orderItem->order_product_id;
                                            $extraUpcs = [];
                                            $upcSku = DB::table('sku_upc_example')->where('sku', $orderItem->item_sku)->get();
                                            if(!is_null($upcSku)){
                                                foreach($upcSku as $val){
                                                    $extraUpcs[] = $val->upc;
                                                }
                                            }
                                            $upcAliases = array_filter(array_unique(array_merge([$orderItem->upc], $extraUpcs)));
                                        @endphp
                                        <input type="hidden"
                                               name="item_id[]"
                                               class="js-item-upc"
                                               data-upc="{{ $orderItem->upc }}"
                                               data-upc-aliases="{{ implode(',', $upcAliases) }}"
                                               value="{{ $orderItem->order_product_id }}">
                                        <input type="hidden" name="hscode[]" class="form-control" value="{{ $orderItem->hscode }}">
                                        <input type="hidden" name="international_row_total[]" class="form-control" value="{{ $orderItem->international_row_total }}">
                                        <input type="hidden" name="item_name[]" class="form-control" value="{{ $orderItem->item_name }}">
                                        <input type="hidden" name="order_product_id[]" class="form-control" value="{{ $orderItem->order_product_id }}">
                                        <tr class="{{ $orderItem->order_product_id }}">
                                            <td>
                                                {{ implode(',', $upcAliases) }}
                                                <input type="hidden" name="upc[]" value="{{ $orderItem->upc }}">
                                            </td>
                                            <td>
                                                {{ $orderItem->item_sku }}
                                                <input type="hidden" name="sku[]" value="{{ $orderItem->item_sku }}">
                                            </td>
                                            <td>
                                                {{ $orderItem->item_weight }}
                                                <input type="hidden" name="item_weight[]" value="{{ $orderItem->item_weight }}">
                                            </td>
                                            <td>
                                                {{ number_format(($orderItem->item_row_total), 2) }}
                                                <input type="hidden" name="item_row_total[]" value="{{ $orderItem->item_row_total }}">
                                                <input type="hidden" name="item_discount[]" value="{{ $orderItem->item_discount_amount }}">
                                                <input type="hidden" name="item_tax[]" value="{{ $orderItem->item_tax_amount }}">
                                            </td>
                                            <td class="ordered_quantity_{{ $orderItem->order_product_id }}">
                                                <div>{{ floor($orderItem->item_quantity_ordered) }}</div>
                                                <input type="hidden" name="quantity_ordered[]" value="{{ floor($orderItem->item_quantity_ordered) }}">
                                            </td>
                                            <td class="remaining_quantity_{{ $orderItem->order_product_id }}">
                                                <div>{{ floor($orderItem->item_quantity_ordered) - floor($orderItem->qty_confirmed) }}</div>
                                                <input type="hidden" name="quantity_remaining[]" value="{{ floor($orderItem->item_quantity_ordered) - floor($orderItem->qty_confirmed) }}">
                                            </td>
                                            <td class="confirmed_quantity_{{ $orderItem->order_product_id }}">
                                                <div>{{ floor($orderItem->qty_confirmed) }}</div>
                                                <input type="hidden" name="quantity_confirmed[]" value="{{ floor($orderItem->qty_confirmed) }}">
                                            </td>
                                            <td class="remarks_{{ $orderItem->order_product_id }}">
                                                <select class="form-control remarks_change" data-id="{{ $orderItem->order_product_id }}" name="item_remarks[]"> 
                                                    <option value="Pending">Pending</option> 
                                                    <option value="Shipped">Shipped</option> 
                                                    <option value="Out of Stock">Out of Stock</option> 
                                                </select>
                                            </td>
                                            <td class="package_{{ $orderItem->order_product_id }}">
                                                <input type="text" name="package[]" class="form-control">
                                            </td>
                                        </tr>
                                    @endif
                            @endforeach
                        @endif
                    </tbody>
                </table>
            </div>  
            @if(!is_null($api))
                @if(!is_null($api->extra_fields))
                    <?php 
                        $extra_fields = json_decode($api->extra_fields, true);
                    ?>
                    @foreach($extra_fields as $key => $value)
                        <div class="form-group">
                            <label for="">{{ ucfirst(str_replace('_', ' ', $key)) }}</label>
                            <select name="{{ $key }}" id="{{ $key }}" class="form-control">
                                @foreach($value as $key2 => $value2)
                                    <option value="{{ str_replace('-', '', $key2) }}">{{ $value2 }}</option>
                                @endforeach
                            </select>
                        </div>
                    @endforeach
                @endif
            @endif
            @if($order->shipping_courier == 'Forrun(Express) - Express Delivery (within 2 hours)' && Auth::user()->id != 88)
                <p class="text-right" style="color:red">This order is Forrun(Express) - Express Delivery <br> and cannot be booked by this account.</p>
            @else
                <div class="form-group">
                    <button type="button"  id="submitBtn" onclick="disableSubmitButton();"  class="shariq btn btn-primary btn-sm boot-btn btnbookorder">Book </button>
                </div>
            @endif
        </form>
        @endif
    </div>
</div>
@endsection


@section('script') 
   
<script>
function disableSubmitButton() {
    // Submit button ko disable karein
    document.getElementById("submitBtn").disabled = true;
}
</script>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/scannerdetection/1.2.0/jquery.scannerdetection.js"></script>
	  

	    <script>





        var itemsIdsString = "<?php echo implode(',', $itemsIds); ?>";
        itemsIdsString = itemsIdsString.split(',');
        var confrimedItems = [];
        var packageValue = 1;

        jQuery(document).scannerDetection({
            timeBeforeScanTest: 200,
            startChar: [120],
            endChar: [13], 
            onComplete: function(barcode, qty){ 
                $('.scan-control').val(barcode);
                detechUPC(barcode);
            }
        });

        function normalizeUpc(value) {
            return (value || '').toString().trim();
        }

        function findItemInputByUpc(upc) {
            var targetUpc = normalizeUpc(upc);
            if (!targetUpc) {
                return $();
            }

            var $allInputs = $('table').find('input.js-item-upc');

            var $direct = $allInputs.filter(function(){
                return normalizeUpc($(this).attr('data-upc')) === targetUpc;
            });

            if ($direct.length) { 
                return $direct.first();
            }

            var $matched = $allInputs.filter(function(){
                var aliasesRaw = $(this).attr('data-upc-aliases') || '';
                var match = false;

                $.each(aliasesRaw.split(','), function(_, alias){
                    if (normalizeUpc(alias) === targetUpc) {
                        match = true;
                        return false;
                    }
                });

                return match;
            });

            return $matched.first();
        }

        function detechUPC(upc_param){
            var upc = normalizeUpc(upc_param);
            var matchedInput = findItemInputByUpc(upc);

            if(matchedInput.length === 0){
                swal("Error", "Wrong UPC", "error");
                setTimeout(function(){ swal.close(); }, 3000);
                return false;
            }

            var item_id = matchedInput.val();
            var ordered_quantity = parseInt($('table').find('.ordered_quantity_'+item_id+' input').val());
            var remaining_quantity = parseInt($('table').find('.remaining_quantity_'+item_id+' input').val());
            var confirmed_quantity = parseInt($('table').find('.confirmed_quantity_'+item_id+' input').val());


            if(remaining_quantity != 0){
                $('table').find('.current_confirmed_'+item_id+' input').val(remaining_quantity);

                remaining_quantity = remaining_quantity-1;
                $('table').find('.remaining_quantity_'+item_id+' div').html(remaining_quantity);
                $('table').find('.remaining_quantity_'+item_id+' input').val(remaining_quantity);
                
                confirmed_quantity = confirmed_quantity+1;
                $('table').find('.confirmed_quantity_'+item_id+' div').html(confirmed_quantity);
                $('table').find('.confirmed_quantity_'+item_id+' input').val(confirmed_quantity);

                swal("Success", "Item Scanned", "success");
                setTimeout(function(){ swal.close(); }, 1000);
            }else{
                swal("Error", "Item Already Scanned", "error");
                setTimeout(function(){ swal.close(); }, 2000);
            }

            if(ordered_quantity == confirmed_quantity){
                $('table').find('.'+item_id).css({'background-color' : '#48C749', 'color' : '#ffffff'});

                confrimedItems.push(item_id);
                position = itemsIdsString.indexOf(item_id);
                itemsIdsString.splice(position, 1);

                $('.remarks_'+item_id).children('select').val('Shipped');

                $('.package_'+item_id).children('input').val(packageValue);
            }else{
                $('table').find('.'+item_id).css({'background-color' : '#48C749', 'color' : '#ffffff'});

                confrimedItems.push(item_id);
                position = itemsIdsString.indexOf(item_id);
                itemsIdsString.splice(position, 1);

                $('.package_'+item_id).children('input').val(packageValue);
            }
        }

        function popup(){
            $('.lds-dual-ring').show();
        }

        $(document).ready(function(){
            $(".scan-control").val("");
			document.getElementById("scanupc").focus();
			document.getElementById("scanupc").select();

            $('.package-info').html('Package: '+packageValue)

            $.each(itemsIdsString, function(index, item_id){
                $('.remarks_'+item_id).children('select').val('Pending');
            });

            $("#item_grid").keypress(function(e) {
                if (e.which == 13) {
                    return false;
                }
            });

            $('.scan-control').on('input', function(){
                detechUPC($(this).val());
            });

            $('.remarks_change').on('change', function(){
                var item_id = $(this).data('id');

                var remaining_qty = $('.ordered_quantity_'+item_id).children('input').val() - $('.confirmed_quantity_'+item_id).children('input').val();
                
                if(remaining_qty == 0){
                    if($(this).val() != 'Shipped'){
                        $(this).val('Shipped');
                    }
                }else{
                    if($(this).val() == 'Shipped'){
                        $(this).val('Pending');
                    }
                }
            });
        });

        function increasePackage(){
            var addPackage = false;

            $.each($('table').find("input[name='package[]']"), function(i, v){
                if(parseInt($(v).val()) === packageValue){
                    addPackage = true;
                }
            });
            
            if(addPackage){
                packageValue++;

                $('.package-info').html('Package: '+packageValue);
            }else{
                swal("Error", "Please scan item with current package value first", "error");
                setTimeout(function(){ swal.close(); }, 2000);
            }
        }

        $('.boot-btn').on('click', function(event){
            event.preventDefault();
            var notScanned = false;
            var confrimedItemsStatus = true;
            var itemsIdsStringStatus = true;
            var scannedShipped = true;

            $.each(confrimedItems, function(index, item_id){
                if($('.package_'+item_id).children('input').val() == ''){
                    confrimedItemsStatus = false;
                    $('.package_'+item_id).children('input').css({'border' : '2px solid #c03'});
                }else{
                    $('.package_'+item_id).children('input').css({'border' : '1px solid #ced4da'});
                }

                $('.remarks_'+item_id).children('select').css({'border' : '1px solid #ced4da'});
            });

            if(!confrimedItemsStatus){
                swal("Error", "Package is required with scanned items", "error");
                setTimeout(function(){ swal.close(); }, 2000);
                return false;
            }

            $.each(itemsIdsString, function(index, item_id){
                if($('.remarks_'+item_id).children('select').val() == ''){
                    itemsIdsStringStatus = false;
                    $('.remarks_'+item_id).children('select').css({'border' : '2px solid #c03'});
                }else{
                    $('.remarks_'+item_id).children('select').css({'border' : '1px solid #ced4da'});
                }

                $('.package_'+item_id).children('input').css({'border' : '1px solid #ced4da'});
            });

            if(!itemsIdsStringStatus){
                swal("Error", "Please add remakrs with non scanned items", "error");
                setTimeout(function(){ swal.close(); }, 2000);
                return false;
            }

            if(itemsIdsStringStatus && confrimedItemsStatus){
                $.each($('tr'), function(i, v){
                    if($(v).css('background-color') == 'rgb(72, 199, 73)'){
                        notScanned = true;
                    }
                });

                if(notScanned){
                    $('.lds-dual-ring').show();
                    $('#item_grid').submit();
                }else{
                    swal("Error", "Please scan Item first", "error");
                    setTimeout(function(){ swal.close(); }, 2000);
                }
            }
        });
    </script>
@endsection
