@section('extraCss')
<style>
    .select2-dropdown, .select2-dropdown--above, .select2-container--open .select2-dropdown--below {
        min-width:200px !important;
    }
</style>
<style>
    .pos-sale-orderCombinations td,
    .pos-sale-orderCombinations td input{
        font-size:11px;
    }
    .selectedOrderProducts th .form-control,
    .selectedOrderProducts td .form-control {}
    .selectedOrderProducts th,
    .selectedOrderProducts td,
    .selectedOrderProducts th .form-control,
    .selectedOrderProducts td .form-control
     {
        font-size:10px;
        padding:5px;
    }
</style>
@endsection

<div class="alert alert-info processingOrder" style="display: none;">Saving order please wait...</div>
<form
    method="POST"
    enctype="multipart/form-data"
    name="posPurchaseReturnFromMain"
    class="posPurchaseReturnFromMain"
    @if(isset($posPurchaseReturn->id))
        action="{{ route('pos-purchase-returns.update', ['id' => $posPurchaseReturn->id]) }}"
    @else
        action="{{ route('pos-purchase-returns.store') }}"
    @endif
    onsubmit="$('.posPurchaseReturnFromMain').hide(); $('.processingOrder').show()"
>
@csrf
@isset($posPurchaseReturn->id)
	{{ method_field('PUT') }}
@endisset
<div class="row orderFormRow">
    <div class="col-md-3">
        <div class="row">
            <div class="col-md-12"><h5>Basic Details</h5><hr/></div>
            <div class="form-group col-md-12">
                <label for="manual_ref_no">Manual Ref#</label>
                <input name="manual_ref_no" id="manual_ref_no" class="form-control" placeholder="Enter Manual Ref. no." required value="{{ empty($posPurchaseReturn->manual_ref_no) ? 'N/A' : $posPurchaseReturn->manual_ref_no }}"/>
            </div>
            <div class="form-group col-md-12">
                <label for="from_pos">FROM POS</label>
                @if(!empty($posPurchaseReturn->from_pos))
                <input type="hidden" name="from_pos" id="from_pos" value="{{ $posPurchaseReturn->from_pos }}">
                <p><b>{{ $posPurchaseReturn->fromWarehouse->name }} ({{ $posPurchaseReturn->fromWarehouse->warehouse_code }})</b></p>
                @else
                <select name="from_pos" id="from_pos" class="form-control select2" data-placeholder="Select Return From" required>
                    <option value="">Select POS</option>
                    @foreach($ALL_POS as $warehouse)
                    @if(!empty($stores))
                        @if(in_array($warehouse->id, $storeData))
                        <option value="{{ $warehouse->id }}" {{ !empty($posPurchaseReturn->from_pos) && $posPurchaseReturn->from_pos == $warehouse->id ? 'selected' : '' }}>{{ $warehouse->warehouse_code . ' ('.$warehouse->name.')' }}</option>
                        @endif
                    @else
                        <option value="{{ $warehouse->id }}" {{ !empty($posPurchaseReturn->from_pos) && $posPurchaseReturn->from_pos == $warehouse->id ? 'selected' : '' }}>{{ $warehouse->warehouse_code . ' ('.$warehouse->name.')' }}</option>
                    @endif
                    @endforeach
                </select>
                @endif
            </div>
            <div class="form-group col-md-12">
                <label for="to_party">TO WAREHOUSE</label>
                @if(!empty($posPurchaseReturn->to_pos))
                <input type="hidden" name="to_pos" id="to_pos" value="{{ $posPurchaseReturn->to_pos }}">
                <p><b>{{ $posPurchaseReturn->toWarehouse->name }} ({{ $posPurchaseReturn->toWarehouse->warehouse_code }})</b></p>
                @else
                <select name="to_pos" id="to_pos" class="form-control select2" data-placeholder="Select Return To" required>
                    <option value="">Select Warehouse</option>
                    @foreach($ALL_WAREHOUSES as $warehouse)
                    <option value="{{ $warehouse->id }}" {{ !empty($posPurchaseReturn->to_pos) && $posPurchaseReturn->to_pos == $warehouse->id ? 'selected' : '' }}>{{ $warehouse->warehouse_code . ' ('.$warehouse->name.')' }}</option>
                    @endforeach
                </select>
                @endif
            </div>
            <div class="form-group col-md-12">
                <label for="shipto">Reason</label>
                <textarea name="reason" id="reason" class="form-control" placeholder="Enter reason for return." required>{{ empty($posPurchaseReturn->reason) ? '' : $posPurchaseReturn->reason }}</textarea>
            </div>
            @if(isset($posPurchaseReturn->approve) && $posPurchaseReturn->approve == 5)
            <div class="col-md-12">
                <div class="form-group">
                    <label for="approve1">
                        <input type="radio" id="approve1" value="5" checked name="approve">&nbsp;Keep this return as draft to add more products later.
                    </label>
                </div>
                <div class="form-group">
                    <label for="approve2">
                        <input type="radio" id="approve2" value="0" name="approve">&nbsp;Save this return, there will be no product addition later.
                    </label>
                </div>
            </div>
            @elseif(isset($posPurchaseReturn->approve) && $posPurchaseReturn->approve == 0)
            <div class="col-md-12">
                <div class="alert alert-warning">Waiting for approval</div>
                <input type="hidden" name="approve" value="0">
            </div>
            @elseif(isset($posPurchaseReturn->approve) && $posPurchaseReturn->approve == 1)
            <div class="col-md-12">
                <div class="alert alert-success">Approved</div>
                <input type="hidden" name="approve" value="1">
            </div>
            @else
            <div class="col-md-12">
                <div class="form-group">
                    <label for="approve1">
                        <input type="radio" id="approve1" value="5" checked name="approve">&nbsp;Keep this return as draft to add more products later.
                    </label>
                </div>
                <div class="form-group">
                    <label for="approve2">
                        <input type="radio" id="approve2" value="0" name="approve">&nbsp;Save this return, there will be no product addition later.
                    </label>
                </div>
            </div>
            @endif

            <div class="col-md-12">
                <button class="btn btn-lg btn-primary" type="button" onclick="saveReturnOrder();"><i class="fa fas fa-save"></i> Save Return</button>
            </div>
        </div>
    </div>
    <div class="col-md-9">
        <div class="row">
            <div class="col-md-12">
                <h5>Return Products</h5><hr/>
            </div>
            <div class="col-md-10">
                <div class="form-group">
                    <label for="returnBarcode">Scan Barcode</label>
                    <input type="text" class="form-control" id="returnBarcode" placeholder="Scan barcode here" {{ isset($posPurchaseReturn->id) && $posPurchaseReturn->approve != 5 ? 'readonly' : ''  }}>
                </div>
            </div>
            <div class="col-md-2">
                <div class="form-group">
                    <label for="returnBoxnum">Enter Box Number</label>
                    <input type="number" class="form-control" id="returnBoxnum" placeholder="Enter Box Number" {{ isset($posPurchaseReturn->id) && $posPurchaseReturn->approve != 5 ? 'readonly' : ''  }}>
                </div>
            </div>
            <div class="col-md-12 fixTableParent">
                {{-- PRODUCTS SELECTED --}}
                <table class="table table-striped table-bordered selectedOrderProducts fixTable">
                    <thead>
                        <tr>
                            <th width="8%">HSN</th>
                            <th width="14%">CODE</th>
                            <th width="8%">ARTICLE</th>
                            <th width="8%">COLOR</th>
                            <th width="8%">SIZE</th>
                            <th width="8%">BARCODE</th>
                            <th width="8%">QTY</th>
                            <th width="8%">MRP</th>
                            <th width="8%">DISCOUNT (%)</th>
                            <th width="8%">DISCOUNT (Amt.)</th>
                            <th width="8%">TAX</th>
                            <th width="8%">FINAL</th>
                            <th width="2%"></th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                    <tfoot></tfoot>
                </table>
                {{-- PRODUCTS SELECTED --}}
            </div>
        </div>
    </div>
</div>
</form>

@section('extraJs')
<script>
    $(document).ready(function () {
        $("#returnBarcode").on('keypress',function(e) {
        if(e.which == 13) {
            var boxNum = $.trim($("#returnBoxnum").val());
            var barcode = $.trim($("#returnBarcode").val());
            var toPos = $.trim($("#to_pos").val());
            var fromPos = $.trim($("#from_pos").val());
            console.log(toPos, ' ---> ', fromPos);
            if(toPos == '' || fromPos == '') {
                toastr.error('Please select source pos and target warehouse for return.');
                return false;
            } else if(boxNum == '' || barcode == '') {
                toastr.error('Please fill in both barcode and box number to get return product');
                return false;
            } else if(parseInt($('.returnRow'+barcode+'').length) > 0) {
                toastr.error('Barcode '+barcode+' is already inwarded!');
                return false;
            } else {
                console.log('Firing HTTP Request')
                $.post("{{ route('get-return-product') }}", {
                    _token: document.tokenForm._token.value,
                    to_pos: toPos,
                    from_pos: fromPos,
                    boxNum: boxNum,
                    barcode: barcode,
                    return_id: {{ !empty($posPurchaseReturn->id) ? $posPurchaseReturn->id : 0 }},
                }, function(result) {
                    var response = jQuery.parseJSON(result);
                    if (response.status == false) {
                        toastr.error(response.info);
                        return false;
                    } else if (response.status == true) {
                        var articleInfo = response.articleInfo;
                        var productInfo = response.product;
                        toastr.success(response.info);
                        var discper = parseFloat(response.warehouse.discount);
                        var discamt = (discper/100) * productInfo.mrp;
                        var discamt = discamt.toFixed(2);
                        var finalmrp = productInfo.mrp - discamt;
                        finalmrp = finalmrp.toFixed(2);

                        var html = '\
                        <tr class="returnRow returnRow'+productInfo.barcode+'">\
                            <td>'+productInfo.hsn+'<input type="hidden" name="hsn[]" value="'+productInfo.hsn+'"/></td>\
                            <td>'+productInfo.productcode+'<input type="hidden" name="productcode[]" value="'+productInfo.productcode+'"/></td>\
                            <td>'+productInfo.article+'<input type="hidden" name="article[]" value="'+productInfo.article+'"/></td>\
                            <td>'+productInfo.color+'<input type="hidden" name="color[]" value="'+productInfo.color+'"/></td>\
                            <td>'+productInfo.size+'<input type="hidden" name="size[]" value="'+productInfo.size+'"/></td>\
                            <td>'+barcode+'<input type="hidden" name="barcode[]" value="'+productInfo.barcode+'"/></td>\
                            <td>1<input type="hidden" name="qty[]" value="1"/></td>\
                            <td>'+productInfo.mrp+'<input type="hidden" name="mrp[]" value="'+productInfo.mrp+'"/></td>\
                            <td><input type="hidden" readonly class="form-control" name="discper[]" value="'+discper+'"/>'+discper+'</td>\
                            <td><input type="hidden" readonly class="form-control" name="discamt[]" value="'+discamt+'"/>'+discamt+'</td>\
                            <td><input type="hidden" readonly class="form-control" name="tax[]" value="'+productInfo.tax+'"/>'+productInfo.tax+'</td>\
                            <td>\
                            <input type="hidden" readonly class="form-control" name="final[]" value="'+finalmrp+'"/>'+finalmrp+'\
                            <input type="hidden" class="form-control" name="productid[]" value="'+productInfo.id+'"/>\
                            <input type="hidden" class="form-control" name="product_id[]" value="'+articleInfo.product_id+'"/>\
                            <input type="hidden" class="form-control" name="variant_id[]" value="'+articleInfo.variant_id+'"/>\
                            <input type="hidden" class="form-control" name="color_id[]" value="'+articleInfo.color_id+'"/>\
                            <input type="hidden" class="form-control" name="size_id[]" value="'+articleInfo.size_id+'"/>\
                            <input type="hidden" class="form-control" name="size_id[]" value="'+articleInfo.size_id+'"/>\
                            <input type="hidden" class="form-control" name="boxnum[]" value="'+boxNum+'"/>\
                            </td>\
                            <td><a href="#" onclick="$(\'.returnRow'+productInfo.barcode+'\').remove();"><i class="fa fas fa-times text-danger"></i></a></td>\
                        </tr>\
                        ';
                        $(".selectedOrderProducts tbody").prepend(html);
                        $("#returnBarcode").val('');
                        return false;
                    }
                    return false;
                });
            }
        }
    });

        @if(!empty($posPurchaseReturn->id))
            // 
            $.post("{{ route('get-return-order-products') }}", {
                    _token: document.tokenForm._token.value,
                    to_pos: {{ $posPurchaseReturn->to_pos }},
                    from_pos: {{ $posPurchaseReturn->from_pos }},
                    return_id: {{ $posPurchaseReturn->id }}
                }, function(result) {
                    var response = jQuery.parseJSON(result);
                    if (response.status == false) {
                        toastr.error(response.info);
                        return false;
                    } else if (response.status == true) {
                        var productInfos = response.products;
                        toastr.success(response.info);
                        for(i = 0; i < productInfos.length; i++) {
                            var productInfo = productInfos[i]; 
                            var disc = parseFloat(productInfo.discount);
                            var discper = (disc/productInfo.net_unit_cost) * 100;
                            discper = discper.toFixed(2);
                            var discamt = disc;
                            var discamt = discamt.toFixed(2);
                            var finalmrp = productInfo.net_unit_cost - discamt;
                            finalmrp = finalmrp.toFixed(2);

                            var html = '\
                            <tr class="returnRow returnRow'+productInfo.barcode+'">\
                                <td>'+productInfo.hsn+'<input type="hidden" name="hsn[]" value="'+productInfo.hsn+'"/></td>\
                                <td>'+productInfo.productcode+'<input type="hidden" name="productcode[]" value="'+productInfo.productcode+'"/></td>\
                                <td>'+productInfo.article+'<input type="hidden" name="article[]" value="'+productInfo.article+'"/></td>\
                                <td>'+productInfo.color+'<input type="hidden" name="color[]" value="'+productInfo.color+'"/></td>\
                                <td>'+productInfo.size+'<input type="hidden" name="size[]" value="'+productInfo.size+'"/></td>\
                                <td>'+productInfo.barcode+'<input type="hidden" name="barcode[]" value="'+productInfo.barcode+'"/></td>\
                                <td>1<input type="hidden" name="qty[]" value="1"/></td>\
                                <td>'+productInfo.net_unit_cost+'<input type="hidden" name="mrp[]" value="'+productInfo.net_unit_cost+'"/></td>\
                                <td><input type="hidden" readonly class="form-control" name="discper[]" value="'+discper+'"/>'+discper+'</td>\
                                <td><input type="hidden" readonly class="form-control" name="discamt[]" value="'+discamt+'"/>'+discamt+'</td>\
                                <td><input type="hidden" readonly class="form-control" name="tax[]" value="'+productInfo.tax+'"/>'+productInfo.tax+'</td>\
                                <td>\
                                <input type="hidden" readonly class="form-control" name="final[]" value="'+finalmrp+'"/>'+finalmrp+'\
                                <input type="hidden" class="form-control" name="productid[]" value="'+productInfo.id+'"/>\
                                <input type="hidden" class="form-control" name="product_id[]" value="'+productInfo.product_id+'"/>\
                                <input type="hidden" class="form-control" name="variant_id[]" value="'+productInfo.variant_id+'"/>\
                                <input type="hidden" class="form-control" name="boxnum[]" value="'+productInfo.box_num+'"/>\
                                </td>';
                                @if(isset($posPurchaseReturn->id) && $posPurchaseReturn->approve != 5)
                                html+='<td class="text-success"></td>';
                                @else
                                html+='<td><a href="#" onclick="$(\'.returnRow'+productInfo.barcode+'\').remove();"><i class="fa fas fa-times text-danger"></i></a></td>';
                                @endif
                                html+='</tr>\
                            ';
                            
                            $(".selectedOrderProducts tbody").prepend(html);
                            $("#returnBarcode").val('');
                        }
                        return false;
                    }
                    return false;
                });
            // 
        @endif
    });

    function saveReturnOrder() {
        @if(isset($posPurchaseReturn->approve) && $posPurchaseReturn->approve != 5)
            toastr.error('Order is either approved or waiting for approval. So it cannot be modified now!');
            return false;
        @endif
        if($.trim($("#manual_ref_no").val()) == '') {
            toastr.error('Manual reference number is empty');
            return false;
        }
        if($.trim($("#from_pos").val()) == '') {
            toastr.error('Please select the source POS');
            return false;
        }
        if($.trim($("#to_pos").val()) == '') {
            toastr.error('Please select the target Warehouse');
            return false;
        }
        if($.trim($("#reason").val()) == '') {
            toastr.error('Please enter the return reason');
            return false;
        }

        if(parseInt($(".returnRow").length) <= 0) {
            toastr.error('There is no item added in the return products. Please add atleast one product to save return.');
            return false;
        }

        document.posPurchaseReturnFromMain.submit();

    }

</script>
@endsection