

<?php $__env->startSection('title', $page_title); ?>

<?php $__env->startPush('styles'); ?>
    <link rel="stylesheet" href="css/jquery-ui.css"/>
    <link href="css/bootstrap-datetimepicker.min.css" rel="stylesheet" type="text/css"/>
    <style>
        .small-btn {
            width: 20px !important;
            height: 20px !important;
            padding: 0 !important;
        }

        .small-btn i {
            font-size: 10px !important;
        }

        .customer.table td {
            vertical-align: top !important;
            padding: 0 !important;
        }
    </style>
<?php $__env->stopPush(); ?>

<?php $__env->startSection('content'); ?>
    <div class="d-flex flex-column-fluid">
        <div class="container-fluid">
            <!--begin::Notice-->
            <div class="card card-custom gutter-b">
                <div class="card-header flex-wrap py-5">
                    <div class="card-title">
                        <h3 class="card-label"><i class="<?php echo e($page_icon); ?> text-primary"></i> <?php echo e($sub_title); ?></h3>
                    </div>
                    <div class="card-toolbar">
                        <!--begin::Button-->
                        <a href="<?php echo e(route('damage.product')); ?>" class="btn btn-warning btn-sm font-weight-bolder">
                            <i class="fas fa-arrow-left"></i> Back</a>
                        <!--end::Button-->
                    </div>
                </div>
            </div>
            <!--end::Notice-->
            <!--begin::Card-->
            <div class="card card-custom">
                <div class="card-body">
                    <!--begin: Datatable-->
                    <div id="kt_datatable_wrapper" class="dataTables_wrapper dt-bootstrap4 no-footer">
                        <form action="" id="damage_store_form" method="post" enctype="multipart/form-data">
                            <?php echo csrf_field(); ?>
                            <div class="row">
                                <input type="hidden" name="damage_product_id" id="damage_product_id">
                                <div class="form-group col-md-3 required">
                                    <label for="invoice_no">Invoice No.</label>
                                    <input type="text" class="form-control" name="invoice_no" id="invoice_no"
                                           value="<?php echo e($invoice_no); ?>"/>
                                </div>
                                <div class="form-group col-md-3 required">
                                    <label for="sale_date">Date</label>
                                    <input type="date" class="form-control" name="date" id="sale_date"
                                           value="<?php echo e(date('Y-m-d')); ?>"/>
                                </div>

                                <div class="form-group col-md-3">
                                    <?php if(Auth::user()->warehouse_id): ?>
                                        <?php if (isset($component)) { $__componentOriginalc254754b9d5db91d5165876f9d051922ca0066f4 = $component; } ?>
<?php $component = $__env->getContainer()->make(Illuminate\View\AnonymousComponent::class, ['view' => 'components.form.selectbox','data' => ['labelName' => 'WareHouse','name' => 'warehouse_id','required' => 'required','col' => 'col-md-12','class' => 'selectpicker']]); ?>
<?php $component->withName('form.selectbox'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php $component->withAttributes(['labelName' => 'WareHouse','name' => 'warehouse_id','required' => 'required','col' => 'col-md-12','class' => 'selectpicker']); ?>
                                            <?php $__currentLoopData = $warehouses; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $value): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                <option value="<?php echo e($value->id); ?>" selected><?php echo e($value->name); ?></option>
                                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                         <?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__componentOriginalc254754b9d5db91d5165876f9d051922ca0066f4)): ?>
<?php $component = $__componentOriginalc254754b9d5db91d5165876f9d051922ca0066f4; ?>
<?php unset($__componentOriginalc254754b9d5db91d5165876f9d051922ca0066f4); ?>
<?php endif; ?>
                                    <?php endif; ?>
                                </div>

                                <div class="form-group col-md-6">
                                    <label for="product_code_name">Select Product</label>
                                    <div class="input-group mb-3">
                                        <div class="input-group-prepend">
                                            <span class="input-group-text" id="basic-addon1"><i
                                                    class="fas fa-barcode"></i></span>
                                        </div>
                                        <input type="text" class="form-control" name="product_code_name"
                                               id="product_code_name" placeholder="Scan/Search by product Code">
                                    </div>
                                </div>

                                <div class="form-group col-md-6">
                                    <label for="product_sku">Select Product SKU</label>
                                    <div class="input-group mb-3">
                                        <div class="input-group-prepend">
                                            <span class="input-group-text" id="basic-addon1"><i class="fas fa-barcode"></i></span>
                                        </div>
                                        <input type="text" class="form-control" name="product_sku"
                                               id="product_sku" placeholder="Scan/Search by product Sku">
                                    </div>
                                </div>
                                <div class="col-md-12 table-responsive">
                                    <table class="table table-bordered" id="product_table">
                                        <thead class="bg-primary">
                                        <th>Name</th>
                                        <th class="text-center">SKU</th>
                                        <th class="text-center">Code</th>
                                        <th class="text-center">Qty</th>
                                        <th class="text-right">Net Unit Price</th>
                                        <th class="text-right">Subtotal</th>
                                        <th></th>
                                        </thead>
                                        <tbody>

                                        </tbody>
                                        <tfoot class="bg-primary">
                                        <th colspan="3" class="font-weight-bolder">Total</th>
                                        <th id="total-qty" class="text-center font-weight-bolder">0</th>
                                        <th id="total-price" class="text-right font-weight-bolder">0</th>
                                        <th id="total" class="text-right font-weight-bolder">0.00</th>
                                        <th></th>
                                        </tfoot>
                                    </table>
                                </div>

                                <div class="col-md-12">
                                    <table class="table table-bordered">
                                        <thead class="bg-primary">
                                        <th><strong>Items</strong><span class="float-right" id="item">0.00</span></th>
                                        <th><strong>Total</strong><span class="float-right" id="subtotal">0.00</span></th>
                                        <th><strong>Grand Total</strong><span class="float-right" id="grand_total">0.00</span></th>
                                        <th></th>
                                        </thead>
                                    </table>
                                </div>
                                <div class="col-md-12">
                                    <input type="hidden" name="total_qty" value="">
                                    <input type="hidden" name="grand_total" value="">
                                    <input type="hidden" name="item" value="">
                                    <input type="hidden" name="grand_total" value="">
                                </div>

                                <div class="form-group col-md-12 text-center pt-5">
                                    <button type="button" class="btn btn-danger btn-sm mr-3"><i
                                            class="fas fa-sync-alt"></i> Reset
                                    </button>
                                    <button type="button" class="btn btn-primary btn-sm mr-3" id="save-btn"
                                            onclick="store_data()"><i class="fas fa-save"></i> Save
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                    <!--end: Datatable-->
                </div>
            </div>
            <!--end::Card-->
        </div>
    </div>
<?php $__env->stopSection(); ?>

<?php $__env->startPush('scripts'); ?>
    <script src="js/jquery-ui.js"></script>
    <script src="js/moment.js"></script>
    <script src="js/bootstrap-datetimepicker.min.js"></script>
    <script>
        $(document).ready(function () {

            //array data depend on warehouse
            var product_array = [];
            var product_code = [];
            var product_name = [];
            var product_qty = [];

            // array data with selection
            var product_price = [];
            var product_discount = [];


            var rowindex;
            var row_product_price;

            $('#product_code_name').on('input', function () {
                var warehouse_id = $('#warehouse_id option:selected').val();
                var temp_data = $('#product_code_name').val();
                if (!warehouse_id) {
                    $('#product_code_name').val(temp_data.substring(0, temp_data.length - 1));
                    notification('error', 'Please select warehouse');
                }
            });

            $('#product_code_name').autocomplete({
                source: function (request, response) {
                    // Fetch data
                    $.ajax({
                        url: "<?php echo e(url('product-autocomplete-search')); ?>",
                        type: 'post',
                        dataType: "json",
                        data: {
                            _token: _token,
                            search: request.term,
                            warehouse_id: $('#warehouse_id option:selected').val()
                        },
                        success: function (data) {
                            console.log(data);
                            response(data);
                        }
                    });
                },
                response: function (event, ui) {
                    if (ui.content.length == 1) {
                        let code = ui.content[0].code;
                        let productId = ui.content[0].product_id;
                        let hasVariant = ui.content[0].variant;
                        let variant_id = ui.content[0].variant_id;
                        let variation = ui.content[0].label;
                        $(this).autocomplete("close");
                        product_barcode_search(productId, hasVariant, code, variant_id, variation);
                        notification('success', 'Successfully Added To Cart');
                    }
                    ;
                },
                select: function (event, ui) {
                    let code = ui.item.code;
                    let productId = ui.item.product_id;
                    let hasVariant = ui.item.variant;
                    let variant_id = ui.item.variant_id;
                    let variation = ui.item.label;
                    product_barcode_search(productId, hasVariant, code, variant_id, variation);
                },
            }).data('ui-autocomplete')._renderItem = function (ul, item) {
                return $("<li class='ui-autocomplete-row'></li>")
                    .data("item.autocomplete", item)
                    .append(item.label)
                    .appendTo(ul);
            };

            //for sku only
            $('#product_sku').on('input', function () {
                var warehouse_id = $('#warehouse_id option:selected').val();
                var temp_data = $('#product_sku').val();
                if (!warehouse_id) {
                    $('#product_sku').val(temp_data.substring(0, temp_data.length - 1));
                    notification('error', 'Please select Warehouse');
                }
            });

            $('#product_sku').autocomplete({
                source: function (request, response) {
                    // Fetch data
                    $.ajax({
                        url: "<?php echo e(url('showroom-stock-transfer-sku-search')); ?>",
                        type: 'post',
                        dataType: "json",
                        data: {
                            _token: _token,
                            search: request.term,
                            warehouse_id: $('#warehouse_id option:selected').val()
                        },
                        success: function (data) {
                            response(data);
                        }
                    });
                },
                // minLength: 3,
                response: function (event, ui) {
                    if (ui.content.length == 1) {
                        let sku = ui.content[0].sku;
                        let productId = ui.content[0].product_id;
                        let hasVariant = ui.content[0].product_variation_status;
                        let variation = ui.content[0].label;
                        $(this).autocomplete("close");
                        product_sku_search(productId, hasVariant, sku);
                        notification('success', 'Successfully Added To Cart');
                    }
                },
                select: function (event, ui) {
                    let sku = ui.item.sku;
                    let productId = ui.item.product_id;
                    let hasVariant = ui.item.product_variation_status;
                    let variation = ui.item.label;
                    product_sku_search(productId, hasVariant, sku);
                },
            }).data('ui-autocomplete')._renderItem = function (ul, item) {
                return $("<li class='ui-autocomplete-row'></li>")
                    .data("item.autocomplete", item)
                    .append(item.label)
                    .appendTo(ul);
            };

            $('#product_table').on('keyup', '.qty', function () {
                rowindex = $(this).closest('tr').index();
                if ($(this).val() < 1 && $(this).val() != '') {
                    $('#product_table tbody tr:nth-child(' + (rowindex + 1) + ') .qty').val(1);
                    notification('error', 'Qunatity can\'t be less than 1');
                }
                checkQuantity($(this).val(), true, input = 2);
            });

            $('#product_table').on('keyup', '.net_unit_price', function () {
                rowindex = $(this).closest('tr').index();
                if ($(this).val() < 1 && $(this).val() != '') {
                    $('#product_table tbody tr:nth-child(' + (rowindex + 1) + ') .net_unit_price').val(1);
                    notification('error', 'Net unit price can\'t be less than 1');
                } else {
                    product_price[rowindex] = $('#product_table tbody tr:nth-child(' + (rowindex + 1) +
                        ') .net_unit_price').val();
                }
                var qty = $('#product_table tbody tr:nth-child(' + (rowindex + 1) + ') .qty').val();
                if (qty > 0) {
                    checkQuantity(qty, true, input = 1);
                }

            });

            $('#product_table').on('click', '.remove-product', function () {
                rowindex = $(this).closest('tr').index();
                product_price.splice(rowindex, 1);
                product_qty.splice(rowindex, 1);
                product_discount.splice(rowindex, 1);
                $(this).closest('tr').remove();
                calculateTotal();
                notification('success', 'Product Removed Successfully');
            });

            var count = 1;

            function product_barcode_search(product_id, hasVariant, code, variant_id, variation) {
                $.ajax({
                    url: "<?php echo e(route('warehouse.product')); ?>",
                    type: 'POST',
                    data: {
                        code: code,
                        _token: _token,
                        warehouse_id: $('#warehouse_id option:selected').val(),
                        product_id: product_id,
                        hasVariant: hasVariant
                    },
                    success: function (data) {
                        if (data.qty > 0) {
                            var flag = 1;
                            $('.product-code').each(function (i) {
                                if ($(this).val() == data.code) {
                                    rowindex = i;
                                    var qty = parseFloat($('#product_table tbody tr:nth-child(' + (rowindex + 1) + ') .qty').val()) + 1;
                                    $('#product_table tbody tr:nth-child(' + (rowindex + 1) + ') .qty').val(qty);
                                    checkQuantity(String(qty), true, input = 2);
                                    flag = 0;
                                }
                            });
                            $('#product_code_name').val('');
                            if (flag) {
                                var newRow = $('<tr>');
                                var cols = '';
                                cols += `<td>` + data.name + `<input type="hidden" name="products[` +
                                    count + `][name]" value="` + data.name + `"></td>`;
                                cols += `<td class="product-sku text-center">` + data.sku + `</td>`;
                                cols += `<td class="text-center">` + data.code + `</td>`;
                                cols +=
                                    `<td><input type="text" class="form-control qty text-center" name="products[` + count + `][qty]" id="products_` + count + `_qty" value="1"></td>`;
                                cols +=
                                    `<td><input type="text" class="form-control text-right net_unit_price" name="products[` +
                                    count + `][net_unit_price]" id="products_` + count + `_net_unit_price" value="${data.price}"></td>`;
                                cols += `<td class="sub-total text-right"></td>`;
                                cols +=
                                    `<td class="text-center d-flex"><button type="button" class="btn btn-danger btn-sm remove-product"><i class="fas fa-trash"></i></button></td>`;

                                cols += `<input type="hidden" class="product-id" name="products[` + count + `][id]"  value="` + data.id + `">`;
                                cols += `<input type="hidden" class="product_sku" name="products[` + count + `][sku]"  value="` + data.sku + `">`;

                                cols += `<input type="hidden" class="product_code" name="products[` + count + `][product_code]"  value="` + data.code + `">`;

                                cols += `<input type="hidden" class="subtotal_value" name="products[` + count + `][subtotal]">`;

                                newRow.append(cols);
                                $('#product_table tbody').append(newRow);

                                product_price.push(parseFloat(data.price));
                                product_qty.push(data.qty);
                                rowindex = newRow.index();
                                checkQuantity(1, true, input = 2);
                                count++;
                            }
                        } else {
                            $('#product_code_name').val('');
                            notification('error', 'No Stock Available For This Product');
                        }
                    },
                    error: function (xhr, ajaxOption, thrownError) {
                        console.log(thrownError + '\r\n' + xhr.statusText + '\r\n' + xhr.responseText);
                    }
                });
            }

            function product_sku_search(product_id, hasVariant, sku) {
                $.ajax({
                    url: "<?php echo e(route('sku.product')); ?>",
                    type: 'POST',
                    data: {
                        sku: sku,
                        _token: _token,
                        warehouse_id: $('#warehouse_id option:selected').val(),
                        product_id: product_id,
                        hasVariant: hasVariant
                    },
                    success: function (dataArray) {
                        console.log(dataArray);
                        $.each(dataArray, function (index, data) {
                            if (data.qty > 0) {
                                var flag = 1;
                                $('.product-code').each(function (i) {
                                    if ($(this).val() == data.code) {
                                        rowindex = i;
                                        var qty = parseFloat($('#product_table tbody tr:nth-child(' + (rowindex + 1) + ') .qty').val()) + 1;
                                        $('#product_table tbody tr:nth-child(' + (rowindex + 1) + ') .qty').val(qty);
                                        checkQuantity(String(qty), true, input = 2);
                                        flag = 0;
                                    }
                                });
                                $('#product_sku').val('');
                                if (flag) {
                                    var newRow = $('<tr>');
                                    var cols = '';
                                    cols += `<td>` + data.name + `<input type="hidden" name="products[` +
                                        count + `][name]" value="` + data.name + `"></td>`;
                                    cols += `<td class="product-sku text-center">` + data.sku + `</td>`;
                                    cols += `<td class="text-center">` + data.code + `</td>`;
                                    cols +=
                                        `<td><input type="text" class="form-control qty text-center" name="products[` + count + `][qty]" id="products_` + count + `_qty" value="1"></td>`;
                                    cols +=
                                        `<td><input type="text" class="form-control text-right net_unit_price" name="products[` +
                                        count + `][net_unit_price]" id="products_` + count + `_net_unit_price" value="${data.price}"></td>`;
                                    cols += `<td class="sub-total text-right"></td>`;
                                    cols +=
                                        `<td class="text-center d-flex"><button type="button" class="btn btn-danger btn-sm remove-product"><i class="fas fa-trash"></i></button></td>`;

                                    cols += `<input type="hidden" class="product-id" name="products[` + count + `][id]"  value="` + data.id + `">`;
                                    cols += `<input type="hidden" class="product_sku" name="products[` + count + `][sku]"  value="` + data.sku + `">`;

                                    cols += `<input type="hidden" class="product_code" name="products[` + count + `][product_code]"  value="` + data.code + `">`;

                                    cols += `<input type="hidden" class="subtotal_value" name="products[` + count + `][subtotal]">`;

                                    newRow.append(cols);
                                    $('#product_table tbody').append(newRow);

                                    product_price.push(parseFloat(data.price));
                                    product_qty.push(data.qty);
                                    rowindex = newRow.index();
                                    checkQuantity(1, true, input = 2);
                                    count++;
                                }
                            } else {
                                $('#product_sku').val('');
                                notification('error', 'No Stock Available For This Product');
                            }
                        });
                    },
                    error: function (xhr, ajaxOption, thrownError) {
                        console.log(thrownError + '\r\n' + xhr.statusText + '\r\n' + xhr.responseText);
                    }
                });
            }

            function checkQuantity(qty, flag, input = 2) {
                if (qty > parseFloat(product_qty[rowindex])) {
                    notification('error', 'Quantity exceed stock quantity');
                    if (flag) {
                        qty = qty.substring(0, qty.length - 1);
                        if (qty < 1) {
                            $('#product_table tbody tr:nth-child(' + (rowindex + 1) + ')').find('.qty').val(0);
                        } else {
                            $('#product_table tbody tr:nth-child(' + (rowindex + 1) + ')').find('.qty').val(qty);
                        }
                    } else {
                        $('#product_table tbody tr:nth-child(' + (rowindex + 1) + ')').find('.qty').val("0");
                        return;
                    }
                }
                calculateProductData(qty, input);
            }

            function calculateProductData(quantity, input = 2) {
                var net_unit_price = parseFloat($('#product_table tbody tr:nth-child(' + (rowindex + 1) + ') .net_unit_price').val());
                var sub_total = (net_unit_price * quantity);


                if (input == 2) {
                    $('#product_table tbody tr:nth-child(' + (rowindex + 1) + ')').find('.net_unit_price').val(net_unit_price > 0 ? net_unit_price.toFixed(2) : '');
                }
                $('#product_table tbody tr:nth-child(' + (rowindex + 1) + ')').find('td:nth-child(6)').text(sub_total.toFixed(2));
                $('#product_table tbody tr:nth-child(' + (rowindex + 1) + ')').find('.subtotal_value').val(sub_total.toFixed(2));

                calculateTotal();
            }

            function calculateTotal() {
                //sum of qty
                var total_qty = 0;
                $('.qty').each(function () {
                    if ($(this).val() == '') {
                        total_qty += 0;
                    } else {
                        total_qty += parseFloat($(this).val());
                    }
                });
                $('#total-qty').text(total_qty);
                $('input[name="total_qty"]').val(total_qty);

                //sum of subtotal
                var total = 0;
                $('.sub-total').each(function () {
                    console.log($(this).text());
                    total += parseFloat($(this).text());
                });
                $('#total').text(total.toFixed(2));
                $('input[name="grand_total"]').val(total.toFixed(2));

                calculateGrandTotal();
            }

            function calculateGrandTotal() {
                var item = $('#product_table tbody tr:last').index();
                var total_qty = parseFloat($('#total-qty').text());
                var subtotal = parseFloat($('#total').text());


                item = ++item + '(' + total_qty + ')';
                var grand_total = subtotal;
                var net_total = grand_total;

                $('#item').text(item);
                $('input[name="item"]').val($('#product_table tbody tr:last').index() + 1);
                $('#subtotal').text(subtotal.toFixed(2));

                $('#grand_total').text(grand_total.toFixed(2));
                $('input[name="grand_total"]').val(grand_total.toFixed(2));
                $('input[name="net_total"]').val(net_total.toFixed(2));
            }
        });

        function store_data() {
            var rownumber = $('table#product_table tbody tr:last').index();
            if (rownumber < 0) {
                notification("error", "Please insert product to order table!")
            } else {
                let form = document.getElementById('damage_store_form');
                let formData = new FormData(form);
                let url = "<?php echo e(route('damage.product.store')); ?>";
                $.ajax({
                    url: url,
                    type: "POST",
                    data: formData,
                    dataType: "JSON",
                    contentType: false,
                    processData: false,
                    cache: false,
                    beforeSend: function () {
                        $('#save-btn').addClass('spinner spinner-white spinner-right');
                    },
                    complete: function () {
                        $('#save-btn').removeClass('spinner spinner-white spinner-right');
                    },
                    success: function (data) {
                        $('#sale_store_form').find('.is-invalid').removeClass('is-invalid');
                        $('#sale_store_form').find('.error').remove();
                        if (data.status == false) {
                            $.each(data.errors, function (key, value) {
                                var key = key.split('.').join('_');
                                $('#damage_store_form input#' + key).addClass('is-invalid');
                                $('#damage_store_form textarea#' + key).addClass('is-invalid');
                                $('#damage_store_form select#' + key).parent().addClass('is-invalid');
                                $('#damage_store_form #' + key).parent().append('<small class="error text-danger">' + value + '</small>');
                            });
                        } else {
                            notification(data.status, data.message);
                            if (data.status == 'success') {
                                window.location.replace("<?php echo e(route('damage.product')); ?>");
                            }
                        }
                    },
                    error: function (xhr, ajaxOption, thrownError) {
                        console.log(thrownError + '\r\n' + xhr.statusText + '\r\n' + xhr.responseText);
                    }
                });
            }

        }
    </script>
<?php $__env->stopPush(); ?>

<?php echo $__env->make('layouts.app', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH /home/iconshoppercom/iconshopper/Modules/DamageProduct/Resources/views/create.blade.php ENDPATH**/ ?>