<script>
    $(document).ready(function (){
        $('.inventory-listing').select2();
        $('#inventory-items-table').dataTable();

        loadInventoryPurchaseOrderDetails();
    });
    var d = document.getElementsByClassName("dr");
    for (var i = 0; i < d.length; i++) {
        d[i].innerHTML = (i+1)+".";
    }

    function loadInventoryPurchaseOrderDetails(){
        {{--Anytime we change the Item, we fethc item Details to provide a place to make a sale--}}
        $('.inventory-listing').change(function (){
            let selectedItem = $(this);
            if(selectedItem.val() != ""){
                let divToLoad = selectedItem.closest('.items-to-be-sold').find('.selected-inventory-details')
                    .html('<div class="guestDetails_input"><div class="guestDetails_inputLabel"> &nbsp;</div><div class="guestDetails_input"><img src="{{asset('images/load-indicators.gif')}}" border=0></div></div>');
                /**Using AJax, fetch details to allow creation of sale order**/
                $.ajax({
                    method: "GET",
                    url: 'get-inventory-details-for-purchase-order/'+selectedItem.val(),
                    data: selectedItem.val(),
                    success: function (res){
                        if(res != ''){
                            selectedItem.closest('.items-to-be-sold').find('.selected-inventory-details').html(res);
                        }else{
                            divToLoad.html('<b class="error">No Details found for the Selected Item</b>')
                        }
                    }
                });
            }
        });
    }

    /**A Button to be used to Delete a Purchase Order Item**/
    function deletePurchaseOrderItem(id){
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
        if (confirm('Are you sure to Delete this Item from Purchase Order?')) {
            $.ajax({
                method: 'DELETE',
                url: '/delete-purchase-order-item/' + id,
                data: id,
                success: function (res) {
                    if (res == 'error') {
                        alert('System is unable to perform the Requested action. Please Try Again!');
                        location.reload();
                    } else if (res == 'success') {
                        alert('Item Deleted from Purchase Order Successfully');
                        location.reload();
                    } else {
                        alert('System Encountered an Error. Please Contact System Admin for Help');
                        location.reload();
                    }
                }
            });
        }
        return false;
    }

    /**A Function That Will be used to Edit an Item in the Purchase Order's List**/
    function editPurchaseOrderItem(id){
        var route_link = '/edit-purchase-order-item/'+id;

        $('#edit_dialog_content').html('<div style="text-align: center; margin: 20px 0 20px 0;"><img src="{{asset('images/loads/loader.gif')}}" border=0></div>')
            .load(encodeURI(route_link))
            .dialog({
                modal: true,
                width: 600,
                title: "Edit Purchase order Details",
                buttons: [
                    {
                        text: "Save Purchase Order Changes",
                        icon: "ui-icon-check",
                        click: function(e) {
                            if(confirm('Are you sure to Save Entered Details?')){
                                e.preventDefault();
                                var datas = $('#edit-purchase-order-details').serializeArray();

                                $.ajax({
                                    method: "POST",
                                    url: route_link,
                                    data: datas,
                                    success: function (res){
                                        if(res == 'success'){
                                            alert('Details Updated Created Successfully');
                                            location.reload();
                                        }else if(res == 'error'){
                                            alert('An Error occurred and System is unable to perform the requested action. Try again');
                                            location.reload();
                                        }else{
                                            alert('System Encountered an Error. Please Contact System Admin');
                                            location.reload();
                                        }
                                    }
                                });
                            }
                            return false;
                        }
                    }
                ],
                open: function() {
                    $(this).parent().css({'top': 50});
                }
            });
    }
</script>
<style>
    #inventory-items-table th, td {
        text-align: left;
        padding: 5px;
    }
    #inventory-items-table tr:hover {background-color: #a3aef6;}
</style>
{!! Form::open(['action'=>['Modules\InventoryDashboardController@storeAddItemsToPurchaseOrder', 'id'=>$id],'method'=>'POST', 'id'=>'add-items-to-purchase-order']) !!}
<div class="error" style="text-align: center;">On this Window, You can add Items and their Quantities to a Purchase Order</div>
<div class="guestDetails_inputDivider"></div>
<button type="submit" disabled style="display: none" aria-hidden="true"></button>
<div class="error" style="text-align: center;font-weight: bold">1. Current Items on Purchase Order</div>
<table id="inventory-items-table" class="display" style="width:100%; border-collapse: collapse">
    <thead>
    <tr style="background-color: #a1b5d3">
        <th>No</th>
        <th>Item Name</th>
        <th>Batches Of</th>
        <th>Requested Quantity</th>
        <th>Edit Quantity</th>
        <th>Delete Item</th>
    </tr>
    </thead>
    <tbody>
    @foreach($purchaseOrder->items as $item)
        <tr>
            <td class="dr"></td>
            <td><b class="error">{!! $item->item ? $item->item->name : '' !!}</b></td>
            <td>{{$item->batches_of}}</td>
            <td>{{$item->quantity}}</td>
            <td><i class="fa fa-pencil error" onclick="editPurchaseOrderItem('{{$item->id}}')"  style="cursor: pointer;font-size: 14px"></i></td>
            <td><i class="fa fa-trash error" onclick="deletePurchaseOrderItem('{{$item->id}}')" style="cursor: pointer;font-size: 14px"></i></td>
        </tr>
    @endforeach
    </tbody>
    <tfoot>
    <tr style="background-color: #a1b5d3">
        <th>No</th>
        <th>Item Name</th>
        <th>Batches Of</th>
        <th>Requested Quantity</th>
        <th>Edit Quantity</th>
        <th>Delete Item</th>
    </tr>
    </tfoot>
</table>
<div class="guestDetails_inputDivider"></div>
<div class="error" style="text-align: center;font-weight: bold">2. Add More Items to Purchase Order</div><br>
<div class="items-to-be-sold">
    <div class="guestDetails_input">
        <div class="guestDetails_inputLabel">
            Select Item to be Added to a Purchase Order <span class="error">*</span>
        </div>
        <div class="guestDetails_input">
            <select name="purchase-order-item[]" class="inventory-listing" style="width: 280px">
                <option value="">--Select Item--</option>
                @foreach($list as $row)
                    <option value="{!! $row->id !!}">{!! html_entity_decode($row->name) !!}</option>
                @endforeach
            </select>
        </div>
    </div>
    <div class="selected-inventory-details"></div>
</div>
<div class="guestDetails_inputDivider"></div>
<div class="added-fields"></div>
<button type="button" id="add-field" style="height: 25px">+Add Another Field</button><br><br>
{!! Form::close() !!}

<script>
    $(document).ready(function () {
        //add and remove vehicle fields
        var addButton = $('#add-field'); //Add button selector
        var wrapper = $('.added-fields'); //Input field wrapper
        var x = 1;
        var fieldHTML = '<div class="items-to-be-sold">' +
            '<div class="guestDetails_input">\n' +
            '  <div class="guestDetails_inputLabel">Select Item to be Sold <span class="error">*</span></div>\n' +
            '    <div class="guestDetails_input">\n' +
            '<select name="purchase-order-item[]" class="inventory-listing" style="width: 280px">'+
            '<option value="">--Select Item--</option>'+
            @foreach($list as $row)
                '<option value="{!! $row->id !!}">{!! htmlspecialchars($row->name, ENT_QUOTES) !!}</option>'+
            @endforeach
                '</select>'+
            '    </div>\n' +
            '</div>\n' +
            '<div class="selected-inventory-details"></div>\n'+
            '<div class="guestDetails_input">' +
                '<div class="guestDetails_inputLabel">&nbsp;</div>' +
                '<div class="guestDetails_input">' +
                '<button type="button" id="remove-button"> <i class="fa fa-trash"></i> </button>' +
                '</div>' +
            '</div>'+
            '<div class="guestDetails_inputDivider input_divider1"></div>'+
            '</div>';
        //Once add button is clicked
        $(addButton).click(function(){
            x++; //Increment field counter

            $(wrapper).append(fieldHTML); //Add field html
            $(wrapper).find('.inventory-listing').select2(); //Add the Select 2 Option

            loadInventoryPurchaseOrderDetails();
        });
        //Once remove button is clicked
        $(wrapper).on('click', '#remove-button', function(e){
            e.preventDefault();
            $(this).closest('.items-to-be-sold').remove(); //Remove field html
            x--; //Decrement field counter
        });
    });
</script>
