<?php $__env->startSection('section-title', 'Purchase'); ?>
<?php $__env->startSection('page-title', 'Add Purchase'); ?>
<?php $__env->startSection('action-button'); ?>
    <a href="<?php echo e(route('purchase.index')); ?>" class="btn add_list_btn">
        <i class="mr-2 feather icon-list"></i>
        Purchase List
    </a>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('content'); ?>
    <div class="row width-auto">
        
        <div class="col-lg-12">
            <div class="card m-b-30" style="margin: 0px 30px;margin-top: -25px;margin-bottom:70px;padding-top:10px">
                <div class="card-body">
                    <form class="needs-validation" novalidate id="purchaseForm" action="<?php echo e(route('purchase.store')); ?>"
                        method="POST" enctype="multipart/form-data">
                        <?php echo csrf_field(); ?>
                        <div class="form-row">
                            
                            <div class="mb-3 col-md-6">
                                <label class="form-label font-weight-bold">
                                    Date *
                                </label>
                                <input type="date" class="form-control" value="<?php echo e(date('Y-m-d')); ?>" name="date"
                                    required>
                            </div>
                            
                            <div class="mb-3 col-md-6">
                                <label for="validationCustom02" class="form-label font-weight-bold">Purchase No *</label>
                                <input type="text" class="form-control" value="<?php echo e($purchase_no); ?>" name="purchase_no"
                                    required readonly>
                            </div>
                        </div>
                        <div class="form-row">
                            
                            <div class="mb-3 col-md-6">
                                <label class="form-label font-weight-bold">
                                    Note</label>
                                <input type="text" class="form-control" placeholder="Enter Note" name="note">
                            </div>
                            
                            <div class="mb-3 col-md-6">
                                <div class="row">
                                    <div class="col-md-11 col-10" style="margin-right: -7px">
                                        <label class="form-label font-weight-bold">Supplier *</label>
                                        <select class="select2" id="supplier" name="supplier_id" required>
                                            
                                            <?php $__currentLoopData = $suppliers; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $supplier): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                <option value="<?php echo e($supplier->id); ?>"><?php echo e($supplier->name); ?></option>
                                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                        </select>
                                    </div>
                                    <div class="col-md-1 col-2 m-0 p-0">
                                        <label class="form-label font-weight-bold"></label>
                                        <div class="" style="margin-top: 7px">
                                            
                                            <a href="#" data-toggle="modal" data-target="#addModal"
                                                class="btn extra_btn">
                                                <i class="feather icon-plus"></i>
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <hr>

                        <div class="form-row">
                            
                            <div class="mb-3 col-md-12 text-center">
                                <div class="input-group mb-3">
                                    <div class="input-group-prepend">
                                        <span class="input-group-text"  style="border-top-left-radius: 25px;border-bottom-left-radius: 25px;background:#000ce2;color:white;" id="basic-addon1"><i
                                                class="fa fa-barcode"></i></span>
                                    </div>
                                    <input type="text" id="product_search" class="form-control"
                                        placeholder="Type & Barcode" aria-label="Type & Barcode"
                                        onkeydown="return event.keyCode !== 13" autocomplete="off">
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-12 col-12 table-responsive">
                                <table class="table table-bordered text-center table-sm">
                                    <thead style="background: #000ce2;border:none">
                                        <tr class=" container-fluid" style="background: #000ce2;color:white">
                                            
                                            <th width="25%" style="border-radius: 25px 0 0 25px; padding: 10px; background: #000ce2;">Product</th>
                                            <th width="10%">Rate</th>
                                            <th width="35%">Qty</th>
                                            <th width="20%">Sub Total</th>
                                            <th width="5%" style="border-radius: 0 25px 25px 0; padding: 10px; background: #000ce2;">
                                                <i class="fa fa-trash"></i>
                                            </th>
                                        </tr>
                                    </thead>
                                    <tbody id="table_body">

                                    </tbody>
                                    <tfoot>
                                        <tr class="bg-light-primary">
                                            <td colspan="3" class="text-right fw-bold">Grand Total</td>
                                            <td colspan="1">
                                                <input type="number" step="any" style="min-width:100px"
                                                    name="estimated_amount" value="0" class="form-control" readonly>
                                            </td>
                                            <td class="text-right"></td>
                                        </tr>
                                        
                                        <tr class="bg-light-primary">
                                            <td colspan="3" class="text-right fw-bold">Discount</td>
                                            <td colspan="1">
                                                <input type="number" step="any" name="discount_amount" min="0"
                                                    value="0" class="form-control discount_amount" required>
                                            </td>
                                            <td class="text-right"></td>
                                        </tr>
                                        
                                        <tr class="">
                                            <td colspan="3" class="text-right fw-bold">Payable
                                                Amount</td>
                                            <td colspan="1">
                                                <input type="number" step="any" name="total_amount" min="0"
                                                    value="0" class="form-control total_amount" readonly>
                                            </td>
                                            <td class="text-right"></td>
                                        </tr>
                                        
                                        <tr class="">
                                            <td colspan="3" class="text-right fw-bold text-black">Bank Account</td>
                                            <td colspan="1">
                                                <select class="select2" name="bank_id" required>
                                                    <?php $__currentLoopData = $bank_accounts; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $bank_account): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                        <option value="<?php echo e($bank_account->id); ?>">
                                                            <?php echo e($bank_account->bank_name); ?></option>
                                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                                </select>
                                            </td>
                                            <td class="text-right"></td>
                                        </tr>
                                        
                                        <tr class="">
                                            <td colspan="3" class="text-right fw-bold text-black">Paid
                                                Amount</td>
                                            <td colspan="1">
                                                <input type="number" step="any" name="paid_amount" min="0"
                                                    value="0" class="form-control paid_amount" required>
                                            </td>
                                            <td class="text-right"></td>
                                        </tr>
                                        
                                        <tr class="bg-light-danger due_amount">
                                            <td colspan="3" class="text-right fw-bold">Due
                                                Amount</td>
                                            <td colspan="1">
                                                <input type="number" step="any" name="due_amount" min="0"
                                                    value="0" class="form-control due_amount" readonly>
                                            </td>
                                            <td class="text-right"></td>
                                        </tr>
                                    </tfoot>
                                </table>
                                
                                <div class="row submitAndReset" style="display: block;">
                                    <div class="text-center col-md-12">
                                        <button type="reset" class="btn col-sm-4 reset_button"  style="padding: 5px 20px; background: #f04438;color:white; border-radius:25px" >Reset</button>
                                        <button class="btn col-sm-6 submit_button" style="padding: 5px 20px; background: #12b76a;color:white; border-radius:25px;margin-right: 5px">Submit</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
    
    <form action="#" id="supplierForm" method="POST">
        <?php echo csrf_field(); ?>
        <?php if (isset($component)) { $__componentOriginalefc5d8f1512157b4f4b5cdc230110e8b = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginalefc5d8f1512157b4f4b5cdc230110e8b = $attributes; } ?>
<?php $component = App\View\Components\AddModal::resolve([] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? (array) $attributes->getIterator() : [])); ?>
<?php $component->withName('add-modal'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag && $constructor = (new ReflectionClass(App\View\Components\AddModal::class))->getConstructor()): ?>
<?php $attributes = $attributes->except(collect($constructor->getParameters())->map->getName()->all()); ?>
<?php endif; ?>
<?php $component->withAttributes(['title' => 'Add Supplier','sizeClass' => 'modal-lg']); ?>
            <?php if (isset($component)) { $__componentOriginal786b6632e4e03cdf0a10e8880993f28a = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginal786b6632e4e03cdf0a10e8880993f28a = $attributes; } ?>
<?php $component = App\View\Components\Input::resolve([] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? (array) $attributes->getIterator() : [])); ?>
<?php $component->withName('input'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag && $constructor = (new ReflectionClass(App\View\Components\Input::class))->getConstructor()): ?>
<?php $attributes = $attributes->except(collect($constructor->getParameters())->map->getName()->all()); ?>
<?php endif; ?>
<?php $component->withAttributes(['label' => 'Supplier Name *','type' => 'text','name' => 'name','placeholder' => 'Enter Supplier Name','required' => true,'md' => '6']); ?>
<?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginal786b6632e4e03cdf0a10e8880993f28a)): ?>
<?php $attributes = $__attributesOriginal786b6632e4e03cdf0a10e8880993f28a; ?>
<?php unset($__attributesOriginal786b6632e4e03cdf0a10e8880993f28a); ?>
<?php endif; ?>
<?php if (isset($__componentOriginal786b6632e4e03cdf0a10e8880993f28a)): ?>
<?php $component = $__componentOriginal786b6632e4e03cdf0a10e8880993f28a; ?>
<?php unset($__componentOriginal786b6632e4e03cdf0a10e8880993f28a); ?>
<?php endif; ?>
            <?php if (isset($component)) { $__componentOriginal786b6632e4e03cdf0a10e8880993f28a = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginal786b6632e4e03cdf0a10e8880993f28a = $attributes; } ?>
<?php $component = App\View\Components\Input::resolve([] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? (array) $attributes->getIterator() : [])); ?>
<?php $component->withName('input'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag && $constructor = (new ReflectionClass(App\View\Components\Input::class))->getConstructor()): ?>
<?php $attributes = $attributes->except(collect($constructor->getParameters())->map->getName()->all()); ?>
<?php endif; ?>
<?php $component->withAttributes(['label' => 'Email','type' => 'email','name' => 'email','placeholder' => 'Enter Email','md' => '6']); ?>
<?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginal786b6632e4e03cdf0a10e8880993f28a)): ?>
<?php $attributes = $__attributesOriginal786b6632e4e03cdf0a10e8880993f28a; ?>
<?php unset($__attributesOriginal786b6632e4e03cdf0a10e8880993f28a); ?>
<?php endif; ?>
<?php if (isset($__componentOriginal786b6632e4e03cdf0a10e8880993f28a)): ?>
<?php $component = $__componentOriginal786b6632e4e03cdf0a10e8880993f28a; ?>
<?php unset($__componentOriginal786b6632e4e03cdf0a10e8880993f28a); ?>
<?php endif; ?>
            <?php if (isset($component)) { $__componentOriginal786b6632e4e03cdf0a10e8880993f28a = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginal786b6632e4e03cdf0a10e8880993f28a = $attributes; } ?>
<?php $component = App\View\Components\Input::resolve([] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? (array) $attributes->getIterator() : [])); ?>
<?php $component->withName('input'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag && $constructor = (new ReflectionClass(App\View\Components\Input::class))->getConstructor()): ?>
<?php $attributes = $attributes->except(collect($constructor->getParameters())->map->getName()->all()); ?>
<?php endif; ?>
<?php $component->withAttributes(['label' => 'Phone *','type' => 'text','name' => 'phone','placeholder' => 'Enter Phone','required' => true,'md' => '6']); ?>
<?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginal786b6632e4e03cdf0a10e8880993f28a)): ?>
<?php $attributes = $__attributesOriginal786b6632e4e03cdf0a10e8880993f28a; ?>
<?php unset($__attributesOriginal786b6632e4e03cdf0a10e8880993f28a); ?>
<?php endif; ?>
<?php if (isset($__componentOriginal786b6632e4e03cdf0a10e8880993f28a)): ?>
<?php $component = $__componentOriginal786b6632e4e03cdf0a10e8880993f28a; ?>
<?php unset($__componentOriginal786b6632e4e03cdf0a10e8880993f28a); ?>
<?php endif; ?>
            <?php if (isset($component)) { $__componentOriginal786b6632e4e03cdf0a10e8880993f28a = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginal786b6632e4e03cdf0a10e8880993f28a = $attributes; } ?>
<?php $component = App\View\Components\Input::resolve([] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? (array) $attributes->getIterator() : [])); ?>
<?php $component->withName('input'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag && $constructor = (new ReflectionClass(App\View\Components\Input::class))->getConstructor()): ?>
<?php $attributes = $attributes->except(collect($constructor->getParameters())->map->getName()->all()); ?>
<?php endif; ?>
<?php $component->withAttributes(['label' => 'Address','type' => 'text','name' => 'address','placeholder' => 'Enter Address','md' => '6']); ?>
<?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginal786b6632e4e03cdf0a10e8880993f28a)): ?>
<?php $attributes = $__attributesOriginal786b6632e4e03cdf0a10e8880993f28a; ?>
<?php unset($__attributesOriginal786b6632e4e03cdf0a10e8880993f28a); ?>
<?php endif; ?>
<?php if (isset($__componentOriginal786b6632e4e03cdf0a10e8880993f28a)): ?>
<?php $component = $__componentOriginal786b6632e4e03cdf0a10e8880993f28a; ?>
<?php unset($__componentOriginal786b6632e4e03cdf0a10e8880993f28a); ?>
<?php endif; ?>
            <?php if (isset($component)) { $__componentOriginal786b6632e4e03cdf0a10e8880993f28a = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginal786b6632e4e03cdf0a10e8880993f28a = $attributes; } ?>
<?php $component = App\View\Components\Input::resolve([] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? (array) $attributes->getIterator() : [])); ?>
<?php $component->withName('input'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag && $constructor = (new ReflectionClass(App\View\Components\Input::class))->getConstructor()): ?>
<?php $attributes = $attributes->except(collect($constructor->getParameters())->map->getName()->all()); ?>
<?php endif; ?>
<?php $component->withAttributes(['label' => 'Opening Receivable','type' => 'text','name' => 'open_receivable','value' => '0','md' => '6']); ?>
<?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginal786b6632e4e03cdf0a10e8880993f28a)): ?>
<?php $attributes = $__attributesOriginal786b6632e4e03cdf0a10e8880993f28a; ?>
<?php unset($__attributesOriginal786b6632e4e03cdf0a10e8880993f28a); ?>
<?php endif; ?>
<?php if (isset($__componentOriginal786b6632e4e03cdf0a10e8880993f28a)): ?>
<?php $component = $__componentOriginal786b6632e4e03cdf0a10e8880993f28a; ?>
<?php unset($__componentOriginal786b6632e4e03cdf0a10e8880993f28a); ?>
<?php endif; ?>
            <?php if (isset($component)) { $__componentOriginal786b6632e4e03cdf0a10e8880993f28a = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginal786b6632e4e03cdf0a10e8880993f28a = $attributes; } ?>
<?php $component = App\View\Components\Input::resolve([] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? (array) $attributes->getIterator() : [])); ?>
<?php $component->withName('input'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag && $constructor = (new ReflectionClass(App\View\Components\Input::class))->getConstructor()): ?>
<?php $attributes = $attributes->except(collect($constructor->getParameters())->map->getName()->all()); ?>
<?php endif; ?>
<?php $component->withAttributes(['label' => 'Opening Payable','type' => 'text','name' => 'open_payable','value' => '0','md' => '6']); ?>
<?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginal786b6632e4e03cdf0a10e8880993f28a)): ?>
<?php $attributes = $__attributesOriginal786b6632e4e03cdf0a10e8880993f28a; ?>
<?php unset($__attributesOriginal786b6632e4e03cdf0a10e8880993f28a); ?>
<?php endif; ?>
<?php if (isset($__componentOriginal786b6632e4e03cdf0a10e8880993f28a)): ?>
<?php $component = $__componentOriginal786b6632e4e03cdf0a10e8880993f28a; ?>
<?php unset($__componentOriginal786b6632e4e03cdf0a10e8880993f28a); ?>
<?php endif; ?>
         <?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginalefc5d8f1512157b4f4b5cdc230110e8b)): ?>
<?php $attributes = $__attributesOriginalefc5d8f1512157b4f4b5cdc230110e8b; ?>
<?php unset($__attributesOriginalefc5d8f1512157b4f4b5cdc230110e8b); ?>
<?php endif; ?>
<?php if (isset($__componentOriginalefc5d8f1512157b4f4b5cdc230110e8b)): ?>
<?php $component = $__componentOriginalefc5d8f1512157b4f4b5cdc230110e8b; ?>
<?php unset($__componentOriginalefc5d8f1512157b4f4b5cdc230110e8b); ?>
<?php endif; ?>
    </form>
<?php $__env->stopSection(); ?>

<?php $__env->startPush('js'); ?>
    <script>
        // Select the input field when the page loads
        window.onload = function() {
            var inputField = document.getElementById('product_search');
            inputField.select();
        };
    </script>
    <script>
        // Page Load
        var empty = '';
        $('body').addClass('toggle-menu');
        $('#product_search').blur();

        var localData = localStorage.getItem('pur-items') ? JSON.parse(localStorage.getItem('pur-items')) : [];

        function showList() {
            if (localData.length <= 0) {
                $("#table_body").html(empty);
            } else {
                console.log('hello');
                localData.forEach((item, index) => {
                    domPrepend(item, index);
                });
            }
        }

        showList();
        // estimatedAmount();

        var cartList = [];


        //category modal ajax code
        $(document).ready(function() {
            $('#supplierForm').on('submit', function(e) {
                e.preventDefault(); // Prevent the default form submission

                $.ajax({
                    url: "<?php echo e(route('supplier.store')); ?>", // Define the route for submission
                    method: 'POST',
                    data: $(this).serialize(), // Serialize form data
                    success: function(response) {
                        // Reload the table data dynamically
                        $('#addModal').modal('hide');
                        // Clear form
                        $('#supplierForm')[0].reset();

                        // Add the new customer to the dropdown without appending manually
                        // Reset and reload the dropdown
                        $('#supplier').load(location.href + ' #supplier>*');

                    },
                    error: function(xhr) {
                        // Handle validation errors or server errors here
                        console.error(xhr.responseText);
                    }
                });
            });
        });
        // Select the input field when the page loads
        window.onload = function() {
            var inputField = document.getElementById('product_search');
            inputField.select();
        };
        var count = 0;
        var db_pid_array;

        $(document).ready(function() {
            $("#product_search").autocomplete({
                source: function(req, res) {
                    let url = "<?php echo e(route('product-search')); ?>";
                    $.get(url, {
                        req: req.term
                    }, (data) => {
                        res($.map(data, function(item) {
                            return {
                                id: item.id,
                                value: item.name + " - " + item.barcode,
                                price: item.selling_price
                            }
                        })); // end res

                    });
                },
                select: function(event, ui) {
                    //check is supplier is selected.
                    if ($("#supplier").val() == '') {
                        iziToast.warning({
                            title: "Please Select Supplier First !",
                            position: "topRight",
                        });
                        return false;
                    }

                    if (db_pid_array && db_pid_array.includes(ui.item.id)) {
                        //SHOW ERROR
                        iziToast.warning({
                            title: "Product already added.",
                            position: "topRight",
                        });
                        return;
                    }

                    count++;
                    $(this).val(ui.item.value);
                    $("#search_product_id").val(ui.item.id);
                    let url = "<?php echo e(route('search-product-id', 'my_id')); ?>".replace('my_id', ui.item.id);
                    $.get(url, (data) => {
                        // console.log(product.unit.name);
                        // product add
                        // var quantity_data = '';
                        // if (data.product.unit.related_unit == null) {
                        //     quantity_data =
                        //         `<input type="text" class="has_sub_unit" hidden value="false">
                    //             <label class="ml-4 mr-2" style="padding-top: 8px;">${data.product.unit.name}:</label>
                    //             <input type="number" value="" class="form-control col main_qty" name="new_main_qty[${data.product.id}]"  onkeydown="return event.keyCode !== 190" min="1">`;
                        // } else {
                        //     quantity_data =
                        //         `<input type="text" class="has_sub_unit" hidden value="true">
                    //             <input type="text" class="conversion" hidden value="${data.product.unit.related_value}">
                    //             <label class="mr-2 ml-4" style="padding-top: 8px;">${data.product.unit.name}:</label>
                    //             <input type="number" value="" class="form-control col main_qty mr-4" name="new_main_qty[${data.product.id}]"  onkeydown="return event.keyCode !== 190" min="1">
                    //             <label class="mr-2" style="padding-top: 8px;">${data.product.unit.related_unit.name}:</label>
                    //             <input type="number" value="0" class="form-control col sub_qty" name="new_sub_qty[${data.product.id}]"  onkeydown="return event.keyCode !== 190" min="1">`;
                        // }
                        // <input type="number" value="1" class="form-control sale_qty" name="qty[]">
                        // let row = `
                    //     <tr>
                    //         <td>${count}</td>
                    //         <td>
                    //         ${data.product.name + " - " + data.product.barcode}
                    //         <input type="hidden" value="${data.product.id}" name="new_product[${data.product.id}]" class="product">
                    //         <input type="hidden" value="${data.product.name}" name="product_name[${data.product.id}]" />
                    //         </td>
                    //         <td >
                    //             <div style="width:100px" class="form-row"> 
                    //                 <input type="text" value="${data.product.purchase_price}" class="form-control rate" name="new_rate[${data.product.id}]">
                    //             </div>
                    //         </td>
                    //         <td class="" >
                    //             <div class="form-row" style="width:300px" >
                    //                 ${quantity_data}
                    //             </div>
                    //         </td>
                    //         <td>
                    //         <strong><span class="sub_total">0</span> Tk</strong>
                    //         <input type="hidden" name="new_subtotal_input[${data.product.id}]" class="subtotal_input" value="0">
                    //         </td>
                    //         <td>
                    //         <a href="#" class="remove">
                    //             <i class="fa fa-trash"></i>
                    //         </a>
                    //         </td>
                    //     </tr>`;

                        // Duplicate check
                        // let tableBody = document.querySelector('#table_body');
                        // let products = tableBody.querySelectorAll('.product');
                        // let isDuplicate = false;
                        // products.forEach(function(item) {
                        //     if (ui.item.id == item.value) {
                        //         isDuplicate = true;
                        //     } else {
                        //         isDuplicate = false;
                        //     }
                        // });

                        if (pExist(data.product.id) == true) {
                            iziToast.warning({
                                title: "Product already added. Increase Quantity.",
                                position: "topRight",
                            });
                            return false;
                        } else {
                            // $("#table_body").append(row);
                            addProductToCard(data);
                        }
                        tFootShowHide();

                    });
                    $(this).val('');
                    return false;
                },
                response: function(event, ui) {
                    if (ui.content.length == 1) {
                        ui.item = ui.content[0];
                        $(this).data('ui-autocomplete')._trigger('select', 'autocompleteselect', ui);
                        $(this).autocomplete('close');

                    }
                },
                minLength: 0
            });
        });

        function pExist(pid) {
            let ldata = localStorage.getItem('pur-items') ? JSON.parse(localStorage.getItem('pur-items')) : [];
            return ldata.some(function(el) {
                return el.product.id === pid
            });
        }

        function storedata(data) {
            if (localStorage.getItem('pur-items') != null) {
                cartList = JSON.parse(localStorage.getItem('pur-items'))
                cartList.push(data);
            } else {
                cartList.push(data);
            }
            localStorage.setItem('pur-items', JSON.stringify(cartList));
        }

        function addProductToCard(data) {
            storedata(data);
            var x = 0;
            domPrepend(data, x++);
            estimatedAmount();
        }

        function domPrepend(data = null, index = null) {
            // var name = data.product.name;
            var quantity_data = '';

            if(data.product.is_service == 0){
                if (data.product.unit.related_unit == null) {
                    quantity_data =
                        `<input type="text" class="has_sub_unit" hidden value="false">
                            <label class="ml-4 mr-2" style="padding-top: 8px;">${data.product.unit.name}:</label>
                            <input type="number" value="" class="form-control col main_qty" name="new_main_qty[${data.product.id}]"  onkeydown="return event.keyCode !== 190" min="1">`;
                } else {
                    quantity_data =
                        `<input type="text" class="has_sub_unit" hidden value="true">
                            <input type="text" class="conversion" hidden value="${data.product.unit.related_value}">
                            <label class="mr-2 ml-4" style="padding-top: 8px;">${data.product.unit.name}:</label>
                            <input type="number" value="" class="form-control col main_qty mr-4" name="new_main_qty[${data.product.id}]"  onkeydown="return event.keyCode !== 190" min="1">
                            <label class="mr-2" style="padding-top: 8px;">${data.product.unit.related_unit.name}:</label>
                            <input type="number" value="0" class="form-control col sub_qty" name="new_sub_qty[${data.product.id}]"  onkeydown="return event.keyCode !== 190" min="1">`;
                }
            }

            let dom = `
                <tr>
                    
                    <td>
                    ${data.product.name + " - " + data.product.barcode}
                    <input type="hidden" value="${data.product.id}" name="new_product[${data.product.id}]" class="product">
                    <input type="hidden" value="${data.product.name}" name="product_name[${data.product.id}]" />
                    </td>
                    <td >
                        <div style="width:100px" class="form-row"> 
                            <input type="text" value="${data.product.purchase_price}" class="form-control rate" name="new_rate[${data.product.id}]">
                        </div>
                    </td>
                    <td class="" >
                        <div class="form-row" style="width:300px" >
                            ${quantity_data}
                        </div>
                    </td>
                    <td>
                    <strong><span class="sub_total">0</span> Tk</strong>
                    <input type="hidden" name="new_subtotal_input[${data.product.id}]" class="subtotal_input" value="0">
                    </td>
                    <td>
                    <a href="#" class="remove">
                        <i class="fa fa-trash"></i>
                    </a>
                    </td>
                </tr>
            `;
            $("#table_body").prepend(dom);
        }

        //calculate total amount with order tax is percentage shipping charge,others charge and discount on keyup and change
        $(document).on(
            "keyup change",
            "input[name='discount_amount']",
            function() {
                totalAmount();
            }
        );

        //paid_amount on keyup and change
        $(document).on("keyup change", "input[name='paid_amount']", function() {
            due_calculation();
        });

        //submit_button
        $(document).on("click", ".submit_button", function() {
            //get all buying price value and check if any value is 0

            var total_price = $(".subtotal_input").val();
            console.log(total_price);

            if (total_price <= 0) {
                iziToast.warning({
                    title: "Buying price can't be 0",
                    position: "topRight",
                });
                return false;
            } else {
                //submit purchaseForm
                $("#purchaseForm").submit();
                localStorage.clear();
            }
        });

        //reset_button
        $(document).on("click", ".reset_button", function() {
            $("tbody").html("");
            tFootShowHide();
        });

        //table footer show hide function
        function tFootShowHide() {
            if ($("tbody tr").length == 0) {
                $(".submitAndReset").hide();
            } else {
                $(".submitAndReset").show();
            }
        }

        function calculate_sub_total(obj) {
            var has_sub_unit = $(obj).parents('tr').find('.has_sub_unit').val();
            var rate = $(obj).parents('tr').find('.rate').val();
            var sub_total = parseFloat($(obj).parents('tr').find('.main_qty').val() * rate);
            if (has_sub_unit == "true") {
                sub_total += parseFloat(($(obj).parents('tr').find('.sub_qty').val() / $(obj).parents('tr').find(
                    '.conversion').val()) * rate);
            } else {

            }
            // $(obj).val() * $(obj).parents('tr').find('.sale_qty').val();
            return sub_total;
        }

        // change rate
        $(document).on('keyup change', '.rate', function() {
            let subTotal = calculate_sub_total($(this));
            $(this).parents('tr').children('td').find('.sub_total').text(subTotal);
            $(this).parents('tr').children('td').find('.subtotal_input').val(subTotal);
            estimatedAmount();
        });

        // change qty
        $(document).on('keyup change', '.main_qty', function() {
            // let rate = $(this).parents('tr').find('.rate').val();
            let subTotal = calculate_sub_total($(this));
            $(this).parents('tr').children('td').find('.sub_total').text(subTotal);
            $(this).parents('tr').children('td').find('.subtotal_input').val(subTotal);
            estimatedAmount();
        });
        $(document).on('keyup change', '.sub_qty', function() {
            // let rate = $(this).parents('tr').find('.rate').val();
            let subTotal = calculate_sub_total($(this));
            $(this).parents('tr').children('td').find('.sub_total').text(subTotal);
            $(this).parents('tr').children('td').find('.subtotal_input').val(subTotal);
            estimatedAmount();
        });

        // Remove DOM
        $(document).on('click', '.remove', function() {
            $(this).parents('tr').remove();
            count--;
            estimatedAmount();
        });


        //estimatedAmount function
        function estimatedAmount() {
            var sum = 0;

            $(".subtotal_input").each(function() {
                var value = $(this).val();
                if (!isNaN(value) && value.length != 0) {
                    sum += parseFloat(value);
                }
            });
            $("input[name='estimated_amount']").val(sum);
            totalAmount();
            due_calculation();
        }

        //due calculation
        function due_calculation() {
            var total_amount = parseFloat($("input[name='total_amount']").val());

            var paid_amount = parseFloat($("input[name='paid_amount']").val());

            var due_amount = $("input[name='due_amount']").val();

            due_amount = total_amount - paid_amount;

            $("input[name='due_amount']").val(due_amount);
        }

        //total amount calculation
        function totalAmount() {
            var discount_amount = parseFloat($("input[name='discount_amount']").val());
            var estimated_amount = parseFloat(
                $("input[name='estimated_amount']").val()
            );

            var total_amount = estimated_amount - discount_amount;

            $("input[name='total_amount']").val(total_amount);
            //set max value for paid amount

            $("input[name='paid_amount']").attr("max", total_amount);
            //set max value for due amount

            $("input[name='due_amount']").attr("max", total_amount);

            var due = $("input[name='due_amount']").val();

            $("input[name='paid_amount']").val(total_amount - due);
        }
    </script>
<?php $__env->stopPush(); ?>

<?php echo $__env->make('backend.layouts.master', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH /home/fastitco/organic-station.fastit.com.bd/resources/views/backend/pages/purchase/create.blade.php ENDPATH**/ ?>