

<?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('wholesale')); ?>" 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="sale_store_form" method="post" enctype="multipart/form-data">
                            <?php echo csrf_field(); ?>
                            <div class="row">

                                <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">Available Qty</th>
                                        <th class="text-center">Qty</th>
                                        <th class="text-right">Net Unit Price</th>
                                        <th class="text-right">Discount</th>
                                        <th class="text-right">Tax</th>
                                        <th class="text-right">Subtotal</th>
                                        <th></th>
                                        </thead>
                                        <tbody>
                                        <?php if(isset($sale_data)): ?>
                                            <?php if(!empty($sale_data['products']) && count($sale_data['products']) > 0): ?>
                                                <?php $__currentLoopData = $sale_data['products']; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $key => $item): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                    <tr>
                                                        <?php
                                                            $tax = DB::table('taxes')
                                                                ->where('rate', $item['tax_rate'])
                                                                ->first();
                                                            $product = DB::table('products')->find($item['id']);
                                                            $units = DB::table('units')
                                                                ->where('base_unit', $product->unit_id)
                                                                ->orWhere('id', $product->unit_id)
                                                                ->get();

                                                            $unit_name = [];
                                                            $unit_operator = [];
                                                            $unit_operation_value = [];

                                                            if ($units) {
                                                                foreach ($units as $unit) {
                                                                    if ($item['sale_unit_id'] == $unit->id) {
                                                                        array_unshift($unit_name, $unit->unit_name);
                                                                        array_unshift($unit_operator, $unit->operator);
                                                                        array_unshift($unit_operation_value, $unit->operation_value);
                                                                    } else {
                                                                        $unit_name[] = $unit->unit_name;
                                                                        $unit_operator[] = $unit->operator;
                                                                        $unit_operation_value[] = $unit->operation_value;
                                                                    }
                                                                }

                                                                if ($product->tax_method == 1) {
                                                                    $product_price = $item['net_unit_price'] + $item['discount'] / $item['qty'];
                                                                } else {
                                                                    $product_price = $item['total'] / $item['qty'] + $item['discount'] / $item['qty'];
                                                                }

                                                                if ($unit_operator[0] == '*') {
                                                                    $product_price = $product_price * $unit_operation_value[0];
                                                                } elseif ($unit_operator[0] == '/') {
                                                                    $product_price = $product_price / $unit_operation_value[0];
                                                                }

                                                                $temp_unit_name = $unit_name = implode(',', $unit_name) . ',';
                                                                $temp_unit_operator = $unit_operator = implode(',', $unit_operator) . ',';
                                                                $temp_unit_operation_value = $unit_operation_value = implode(',', $unit_operation_value) . ',';
                                                            }
                                                        ?>
                                                        <td><?php echo e($item['name']); ?></td>

                                                        <td><?php echo e($item['code']); ?></td>
                                                        <td><input type="text"
                                                                   class="form-control product-serial-no"
                                                                   name="products[<?php echo e($key + 1); ?>][serial_no]"
                                                                   id="products_<?php echo e($key + 1); ?>_serial_no"
                                                                   value="<?php echo e($item['serial_no']); ?>"></td>
                                                        <td class="unit-name"><?php echo e($item['unit_name']); ?></td>
                                                        <td><input type="text"
                                                                   class="stock-qty form-control text-center"
                                                                   name="products[<?php echo e($key + 1); ?>][stock_qty]"
                                                                   value="<?php echo e($item['stock_qty']); ?>" readonly></td>
                                                        <td><input type="text" class="form-control qty text-center"
                                                                   name="products[<?php echo e($key + 1); ?>][qty]"
                                                                   id="products_<?php echo e($key + 1); ?>_qty"
                                                                   value="<?php echo e($item['qty']); ?>"></td>

                                                        <td><input type="text"
                                                                   class="net_unit_price form-control text-right"
                                                                   name="products[<?php echo e($key + 1); ?>][net_unit_price]"
                                                                   value="<?php echo e($item['net_unit_price']); ?>"></td>
                                                        <td class="discount text-right">
                                                            <?php echo e(number_format($item['discount'])); ?></td>
                                                        <td class="tax text-right">
                                                            <?php echo e(number_format((float) $item['tax'], 2, '.', '')); ?></td>
                                                        <td class="sub-total text-right">
                                                            <?php echo e(number_format((float) $item['total'], 2, '.', '')); ?>

                                                        </td>
                                                        <td class="text-center  d-flex">
                                                            <button type="button"
                                                                    class="edit-product btn btn-sm btn-primary mr-2"
                                                                    data-toggle="modal" data-target="#editModal"><i
                                                                    class="fas fa-edit"></i></button>
                                                            <button type="button"
                                                                    class="btn btn-danger btn-sm remove-product"><i
                                                                    class="fas fa-trash"></i></button>
                                                        </td>
                                                        <input type="hidden" class="product-id"
                                                               name="products[<?php echo e($key + 1); ?>][id]"
                                                               value="<?php echo e($item['id']); ?>">
                                                        <input type="hidden" class="product-variant-id"
                                                               name="products[<?php echo e($key + 1); ?>][variant_id]"
                                                               value="<?php echo e($item['variant_id']); ?>">
                                                        <input type="hidden"
                                                               name="products[<?php echo e($key + 1); ?>][name]"
                                                               value="<?php echo e($item['name']); ?>">
                                                        <input type="hidden" class="product-code"
                                                               name="products[<?php echo e($key + 1); ?>][code]"
                                                               value="<?php echo e($item['code']); ?>">

                                                        <input type="hidden" class="product-price"
                                                               name="products[<?php echo e($key + 1); ?>][price]"
                                                               value="<?php echo e($product_price); ?>">
                                                        <input type="hidden" class="sale-unit"
                                                               name="products[<?php echo e($key + 1); ?>][unit]"
                                                               value="<?php echo e($unit_name); ?>">
                                                        <input type="hidden" class="sale-unit-operator"
                                                               value="<?php echo e($unit_operator); ?>">
                                                        <input type="hidden" class="sale-unit-operation-value"
                                                               value="<?php echo e($unit_operation_value); ?>">

                                                        <input type="hidden" class="discount-value"
                                                               name="products[<?php echo e($key + 1); ?>][discount]"
                                                               value="<?php echo e($item['discount']); ?>">
                                                        <input type="hidden" class="tax-rate"
                                                               name="products[<?php echo e($key + 1); ?>][tax_rate]"
                                                               value="<?php echo e($item['tax_rate']); ?>">
                                                        <?php if($tax): ?>
                                                            <input type="hidden" class="tax-name"
                                                                   value="<?php echo e($tax->name); ?>">
                                                        <?php else: ?>
                                                            <input type="hidden" class="tax-name" value="No Tax">
                                                        <?php endif; ?>
                                                        <input type="hidden" class="tax-method"
                                                               value="<?php echo e($product->tax_method); ?>">
                                                        <input type="hidden" class="tax-value"
                                                               name="products[<?php echo e($key + 1); ?>][tax]"
                                                               value="<?php echo e($item['tax']); ?>">
                                                        <input type="hidden" class="subtotal-value"
                                                               name="products[<?php echo e($key + 1); ?>][subtotal]"
                                                               value="<?php echo e($item['total']); ?>">

                                                    </tr>
                                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                            <?php endif; ?>
                                        <?php endif; ?>
                                        </tbody>
                                        <tfoot class="bg-primary">
                                        <th colspan="3" class="font-weight-bolder">Total</th>
                                        <th id="total-qty" class="text-center font-weight-bolder">
                                            <?php echo e(isset($sale_data) ? $sale_data['sale']['total_qty'] : '0'); ?></th>
                                        <th></th>
                                        <th id="total-discount" class="text-right font-weight-bolder">
                                            <?php echo e(isset($sale_data) ? $sale_data['sale']['total_discount'] : '0.00'); ?>

                                        </th>
                                        <th id="total-tax" class="text-right font-weight-bolder">
                                            <?php echo e(isset($sale_data) ? $sale_data['sale']['total_tax'] : '0.00'); ?></th>
                                        <th id="total" class="text-right font-weight-bolder">
                                            <?php echo e(isset($sale_data) ? $sale_data['sale']['total_price'] : '0.00'); ?></th>
                                        <th></th>
                                        </tfoot>
                                    </table>
                                </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 or Sku">
                                    </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="form-group col-md-12" style="background: #ADD8E6;padding-top: 8px;">
                                    <h3 style="font-weight: 700;">Customer Details</h3>
                                </div>


                                <input type="hidden" name="sale_id" id="sale_id">
                                <div class="form-group col-md-3 required">
                                    <label for="memo_no">Invoice No.</label>
                                    <input type="text" class="form-control" name="invoice_no" id="invoice_no"
                                           value="<?php echo e(isset($sale_data) ? $sale_data['sale']['invoice_no'] : $invoice_no); ?>"/>
                                </div>


                                <div class="form-group col-md-3">
                                    <?php if(Auth::user()->showroom_id): ?>

                                        <?php if (isset($component)) { $__componentOriginalc254754b9d5db91d5165876f9d051922ca0066f4 = $component; } ?>
<?php $component = $__env->getContainer()->make(Illuminate\View\AnonymousComponent::class, ['view' => 'components.form.selectbox','data' => ['labelName' => 'Showroom','name' => 'showroom_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' => 'Showroom','name' => 'showroom_id','required' => 'required','col' => 'col-md-12','class' => 'selectpicker']); ?>
                                            <?php if(!$showrooms->isEmpty()): ?>
                                                <?php $__currentLoopData = $showrooms; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $value): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                    <option value="<?php echo e($value->id); ?>"
                                                        <?php echo e(Auth::user()->showroom_id == $value->id ? 'selected' : ''); ?>>
                                                        <?php echo e($value->name); ?></option>
                                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                            <?php endif; ?>
                                         <?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__componentOriginalc254754b9d5db91d5165876f9d051922ca0066f4)): ?>
<?php $component = $__componentOriginalc254754b9d5db91d5165876f9d051922ca0066f4; ?>
<?php unset($__componentOriginalc254754b9d5db91d5165876f9d051922ca0066f4); ?>
<?php endif; ?>
                                    <?php else: ?>
                                        <?php if (isset($component)) { $__componentOriginalc254754b9d5db91d5165876f9d051922ca0066f4 = $component; } ?>
<?php $component = $__env->getContainer()->make(Illuminate\View\AnonymousComponent::class, ['view' => 'components.form.selectbox','data' => ['labelName' => 'Showroom','name' => 'showroom_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' => 'Showroom','name' => 'showroom_id','required' => 'required','col' => 'col-md-12','class' => 'selectpicker']); ?>
                                            <?php if(!$showrooms->isEmpty()): ?>
                                                <?php $__currentLoopData = $showrooms; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $value): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                    <option value="<?php echo e($value->id); ?>"
                                                        <?php echo e(Auth::user()->showroom_id == $value->id ? 'selected' : ''); ?>>
                                                        <?php echo e($value->name); ?></option>
                                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                            <?php endif; ?>
                                         <?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="customer_id">Customer</label>
                                    <table class="table table-borderless customer">
                                        <tr>
                                            <td width="<?php echo e(permission('customer-add') ? '80%' : '100%'); ?>">
                                                <select class="form-control selectpicker" name="customer_id"
                                                        id="customer_id" data-live-search="true"></select>
                                            </td>
                                            <?php if(permission('customer-add')): ?>
                                                <td width="20%" class="text-right">
                                                    <button type="button"
                                                            class="btn btn-sm btn-primary"
                                                            onclick="showFormModal('Add New Customer','Save')"><i
                                                            class="fas fa-plus-square"></i></button>
                                                </td>
                                            <?php endif; ?>
                                        </tr>
                                    </table>
                                </div>
                                <div class="form-group col-md-3 required">
                                    <label for="sale_date">Sale Date</label>
                                    <input type="date" class="form-control" name="sale_date" id="sale_date"
                                           value="<?php echo e(isset($sale_data) ? $sale_data['sale']['sale_date'] : date('Y-m-d')); ?>"/>
                                </div>
                                <div class="form-group col-md-3">
                                    <label for="document">Attach Document</label>
                                    <input type="file" class="form-control" name="document" id="document">
                                </div>

                                <div class="form-group col-md-6 required">
                                    <label for="memo_no">Shipping Address.</label>
                                    <input type="text" class="form-control" name="shipping_address" id="shipping_address" value=""/>
                                </div>

                                <div class="form-group col-md-4">
                                    <?php if (isset($component)) { $__componentOriginalc254754b9d5db91d5165876f9d051922ca0066f4 = $component; } ?>
<?php $component = $__env->getContainer()->make(Illuminate\View\AnonymousComponent::class, ['view' => 'components.form.selectbox','data' => ['labelName' => 'Old Invoice','name' => 'old_invoice','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' => 'Old Invoice','name' => 'old_invoice','col' => 'col-md-12','class' => 'selectpicker']); ?>
                                        <?php if(!$old_invoice->isEmpty()): ?>
                                            <?php $__currentLoopData = $old_invoice; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $value): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                <option value="<?php echo e($value->grand_total); ?>">
                                                    <?php echo e($value->invoice_no); ?></option>
                                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                        <?php endif; ?>
                                     <?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__componentOriginalc254754b9d5db91d5165876f9d051922ca0066f4)): ?>
<?php $component = $__componentOriginalc254754b9d5db91d5165876f9d051922ca0066f4; ?>
<?php unset($__componentOriginalc254754b9d5db91d5165876f9d051922ca0066f4); ?>
<?php endif; ?>
                                </div>
                                <div class="form-group col-md-4">
                                    <label for="memo_no">Adjustment Balance</label>
                                    <input type="text" class="form-control" name="adjustment_balance" id="adjustment_balance" value="0" readonly/>
                                </div>


                                <?php if (isset($component)) { $__componentOriginalc254754b9d5db91d5165876f9d051922ca0066f4 = $component; } ?>
<?php $component = $__env->getContainer()->make(Illuminate\View\AnonymousComponent::class, ['view' => 'components.form.selectbox','data' => ['labelName' => 'Order Tax','name' => 'order_tax_rate','col' => 'col-md-3','class' => 'selectpicker']]); ?>
<?php $component->withName('form.selectbox'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php $component->withAttributes(['labelName' => 'Order Tax','name' => 'order_tax_rate','col' => 'col-md-3','class' => 'selectpicker']); ?>
                                    <option value="0" selected>No Tax</option>
                                    <?php if(!$taxes->isEmpty()): ?>
                                        <?php $__currentLoopData = $taxes; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $tax): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                            <option value="<?php echo e($tax->rate); ?>"
                                            <?php if(isset($sale_data)): ?>
                                                <?php echo e($sale_data['sale']['order_tax_rate'] == $tax->rate ? 'selected' : ''); ?>

                                                <?php endif; ?>>
                                                <?php echo e($tax->name); ?></option>
                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                    <?php endif; ?>
                                 <?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__componentOriginalc254754b9d5db91d5165876f9d051922ca0066f4)): ?>
<?php $component = $__componentOriginalc254754b9d5db91d5165876f9d051922ca0066f4; ?>
<?php unset($__componentOriginalc254754b9d5db91d5165876f9d051922ca0066f4); ?>
<?php endif; ?>

                                <div class="form-group col-md-3">
                                    <label for="order_discount">Order Discount</label>
                                    <input type="text" class="form-control" name="order_discount" id="order_discount"
                                           value="<?php echo e(isset($sale_data) ? $sale_data['sale']['order_discount'] : ''); ?>">
                                </div>
                                <div class="form-group col-md-3">
                                    <label for="shipping_cost">Shipping Cost</label>
                                    <input type="text" class="form-control" name="shipping_cost" id="shipping_cost"
                                           value="<?php echo e(isset($sale_data) ? $sale_data['sale']['shipping_cost'] : ''); ?>">
                                </div>

                                <?php if (isset($component)) { $__componentOriginalc254754b9d5db91d5165876f9d051922ca0066f4 = $component; } ?>
<?php $component = $__env->getContainer()->make(Illuminate\View\AnonymousComponent::class, ['view' => 'components.form.selectbox','data' => ['labelName' => 'Payment Status','name' => 'payment_status','required' => 'required','col' => 'col-md-3','class' => 'selectpicker']]); ?>
<?php $component->withName('form.selectbox'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php $component->withAttributes(['labelName' => 'Payment Status','name' => 'payment_status','required' => 'required','col' => 'col-md-3','class' => 'selectpicker']); ?>
                                    <?php $__currentLoopData = PAYMENT_STATUS; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $key => $value): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                        <option value="<?php echo e($key); ?>"
                                        <?php if(isset($sale_data)): ?>
                                            <?php echo e($sale_data['sale']['payment_status'] == $key ? 'selected' : ''); ?>

                                            <?php endif; ?>>
                                            <?php echo e($value); ?></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; ?>
                                <div class="payment col-md-12 d-none" id="payment_method">
                                    <div class="row">
                                        <div class="row col-md-12" id="payment_method_tr_0">
                                            <div class="form-group col-md-3">
                                                <label>Payment Method</label>
                                                <select class="form-control selectpicker"
                                                        name="payment[0][payment_method]"
                                                        id="payment_0_payment_method"
                                                        onchange="account_list(this.value,0)"
                                                        data-live-search="true"
                                                        data-live-search-placeholder="Search">
                                                    <option value="">Select Please</option>
                                                    <?php $__currentLoopData = SALE_PAYMENT_METHOD; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $key => $value): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                        <option value="<?php echo e($key); ?>"
                                                                data-reference_id="0"><?php echo e($value); ?></option>
                                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                                </select>
                                            </div>

                                            <div class="form-group col-md-3">
                                                <label>Account</label>
                                                <select class="form-control selectpicker"
                                                        name="payment[0][account_id]"
                                                        id="payment_0_account_id"
                                                        data-live-search="true"
                                                        data-live-search-placeholder="Search">
                                                    <option value="">Select Please</option>
                                                </select>
                                            </div>

                                            <div class="form-group col-md-3 d-none  reference_no_0">
                                                <label for="reference_no">Reference No</label>
                                                <input type="text" class="fcs form-control"
                                                       name="payment[0][reference_no]"
                                                       
                                                       id="payment_0_reference_no"
                                                >
                                            </div>

                                            <div class="form-group col-md-2">
                                                <label for="reference_no">Amount</label>
                                                <input type="number" class="fcs form-control payment_amounts"
                                                       oninput="calculatePaymentAmount(this.value)" value="0"
                                                       name="payment[0][payment_amount]"
                                                       
                                                       id="payment_0_payment_amount">
                                            </div>

                                            <div
                                                class=" d-flex flex-column justify-content-center align-items-center">
                                                <button type="button"
                                                        class="btn btn-success btn-sm"
                                                        onclick="addTableRow('payment_method',0)">
                                                    <i class="fas fa-plus"></i>
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="form-group col-md-12">
                                    <label for="shipping_cost">Note</label>
                                    <textarea class="form-control" name="note" id="note" cols="30"
                                              rows="3"><?php echo e(isset($sale_data) ? $sale_data['sale']['note'] : ''); ?></textarea>
                                </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"><?php echo e(isset($sale_data) ? $sale_data['sale']['item'] . '(' . $sale_data['sale']['total_qty'] . ')' : '0.00'); ?></span>
                                        </th>
                                        <th><strong>Total</strong><span class="float-right"
                                                                        id="subtotal"><?php echo e(isset($sale_data) ? $sale_data['sale']['total_price'] : '0.00'); ?></span>
                                        </th>
                                        <th><strong>Order Tax</strong><span class="float-right"
                                                                            id="order_total_tax"><?php echo e(isset($sale_data) ? $sale_data['sale']['order_tax'] : '0.00'); ?></span>
                                        </th>
                                        <th><strong>Order Discount</strong><span class="float-right"
                                                                                 id="order_total_discount"><?php echo e(isset($sale_data) ? $sale_data['sale']['total_discount'] : '0.00'); ?></span>
                                        </th>
                                        <th><strong>Shipping Cost</strong><span class="float-right"
                                                                                id="shipping_total_cost"><?php echo e(isset($sale_data) ? $sale_data['sale']['shipping_cost'] : '0.00'); ?></span>
                                        </th>
                                        <th><strong>Grand Total</strong><span class="float-right"
                                                                              id="grand_total"><?php echo e(isset($sale_data) ? $sale_data['sale']['grand_total'] : '0.00'); ?></span>
                                        </th>
                                        </thead>
                                    </table>
                                </div>
                                <div class="col-md-12">
                                    <input type="hidden" name="total_qty"
                                           value="<?php echo e(isset($sale_data) ? $sale_data['sale']['total_qty'] : ''); ?>">
                                    <input type="hidden" name="total_discount"
                                           value="<?php echo e(isset($sale_data) ? $sale_data['sale']['total_discount'] : ''); ?>">
                                    <input type="hidden" name="total_tax"
                                           value="<?php echo e(isset($sale_data) ? $sale_data['sale']['total_tax'] : ''); ?>">
                                    <input type="hidden" name="total_price"
                                           value="<?php echo e(isset($sale_data) ? $sale_data['sale']['total_price'] : ''); ?>">
                                    <input type="hidden" name="item"
                                           value="<?php echo e(isset($sale_data) ? $sale_data['sale']['item'] : ''); ?>">
                                    <input type="hidden" name="order_tax"
                                           value="<?php echo e(isset($sale_data) ? $sale_data['sale']['order_tax'] : ''); ?>">
                                    <input type="hidden" name="grand_total"
                                           value="<?php echo e(isset($sale_data) ? $sale_data['sale']['grand_total'] : ''); ?>">
                                </div>

                                <div
                                    class="payment col-md-12 <?php if(isset($sale_data)): ?> <?php echo e($sale_data['sale']['payment_status'] == 3 ? 'd-none' : ''); ?> <?php else: ?> <?php echo e('d-none'); ?> <?php endif; ?> ">
                                    <div class="row">
                                        <div class="form-group col-md-4 required" style="display: none">
                                            <label for="previous_due">Previous Due</label>
                                            <input type="text" class="form-control" name="previous_due" id="previous_due" value="0" readonly>
                                        </div>
                                        <div class="form-group col-md-4 required">
                                            <label for="net_total">Net Total</label>
                                            <input type="text" class="form-control" name="net_total" id="net_total"
                                                   value="<?php echo e(isset($sale_data) ? $sale_data['sale']['previous_due'] + $sale_data['sale']['grand_total'] : '0.00'); ?>"
                                                   readonly>
                                        </div>
                                        <div class="form-group col-md-4 required">
                                            <label for="paid_amount">Paid Amount</label>
                                            <input type="text" class="form-control" name="paid_amount"
                                                   id="paid_amount"
                                                   value="<?php echo e(isset($sale_data) ? $sale_data['sale']['paid_amount'] : '0.00'); ?>">
                                        </div>
                                        <div class="form-group col-md-4">
                                            <label for="due_amount">Due Amount</label>
                                            <input type="text" class="form-control" name="due_amount" id="due_amount"
                                                   value="<?php echo e(isset($sale_data) ? $sale_data['sale']['due_amount'] : '0.00'); ?>"
                                                   readonly>
                                        </div>

                                    </div>
                                </div>

                                <div class="form-grou 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>
    <!-- Start :: Edit Modal -->
    <div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="model-1" aria-hidden="true">
        <div class="modal-dialog" role="document">

            <!-- Modal Content -->
            <div class="modal-content">
                <!-- Modal Header -->
                <div class="modal-header bg-primary">
                    <h3 class="modal-title text-white" id="model-title"></h3>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <i aria-hidden="true" class="ki ki-close text-white"></i>
                    </button>
                </div>
                <!-- /modal header -->
                <form id="edit_form" method="post">
                    <?php echo csrf_field(); ?>
                    <!-- Modal Body -->
                    <div class="modal-body">
                        <div class="row">
                            <?php if (isset($component)) { $__componentOriginalc254754b9d5db91d5165876f9d051922ca0066f4 = $component; } ?>
<?php $component = $__env->getContainer()->make(Illuminate\View\AnonymousComponent::class, ['view' => 'components.form.textbox','data' => ['labelName' => 'Quantity','name' => 'edit_qty','required' => 'required','col' => 'col-md-12']]); ?>
<?php $component->withName('form.textbox'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php $component->withAttributes(['labelName' => 'Quantity','name' => 'edit_qty','required' => 'required','col' => 'col-md-12']); ?>
<?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__componentOriginalc254754b9d5db91d5165876f9d051922ca0066f4)): ?>
<?php $component = $__componentOriginalc254754b9d5db91d5165876f9d051922ca0066f4; ?>
<?php unset($__componentOriginalc254754b9d5db91d5165876f9d051922ca0066f4); ?>
<?php endif; ?>
                            <?php if (isset($component)) { $__componentOriginalc254754b9d5db91d5165876f9d051922ca0066f4 = $component; } ?>
<?php $component = $__env->getContainer()->make(Illuminate\View\AnonymousComponent::class, ['view' => 'components.form.textbox','data' => ['labelName' => 'Unit Discount','name' => 'edit_discount','col' => 'col-md-12']]); ?>
<?php $component->withName('form.textbox'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php $component->withAttributes(['labelName' => 'Unit Discount','name' => 'edit_discount','col' => 'col-md-12']); ?>
<?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__componentOriginalc254754b9d5db91d5165876f9d051922ca0066f4)): ?>
<?php $component = $__componentOriginalc254754b9d5db91d5165876f9d051922ca0066f4; ?>
<?php unset($__componentOriginalc254754b9d5db91d5165876f9d051922ca0066f4); ?>
<?php endif; ?>
                            <?php if (isset($component)) { $__componentOriginalc254754b9d5db91d5165876f9d051922ca0066f4 = $component; } ?>
<?php $component = $__env->getContainer()->make(Illuminate\View\AnonymousComponent::class, ['view' => 'components.form.textbox','data' => ['labelName' => 'Unit Price','name' => 'edit_unit_price','col' => 'col-md-12','readonly' => true]]); ?>
<?php $component->withName('form.textbox'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php $component->withAttributes(['labelName' => 'Unit Price','name' => 'edit_unit_price','col' => 'col-md-12','readonly' => true]); ?>
<?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__componentOriginalc254754b9d5db91d5165876f9d051922ca0066f4)): ?>
<?php $component = $__componentOriginalc254754b9d5db91d5165876f9d051922ca0066f4; ?>
<?php unset($__componentOriginalc254754b9d5db91d5165876f9d051922ca0066f4); ?>
<?php endif; ?>
                            <?php
                                $tax_name_all[] = 'No Tax';
                                $tax_rate_all[] = 0;
                                foreach ($taxes as $tax) {
                                    $tax_name_all[] = $tax->name;
                                    $tax_rate_all[] = $tax->rate;
                                }
                            ?>
                            <div class="form-group col-md-12">
                                <label for="edit_tax_rate">Tax Rate</label>
                                <select name="edit_tax_rate" id="edit_tax_rate" class="form-control selectpicker">
                                    <?php $__currentLoopData = $tax_name_all; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $key => $value): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                        <option value="<?php echo e($key); ?>"><?php echo e($value); ?></option>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </select>
                            </div>
                            <div class="form-group col-md-12">
                                <label for="edit_unit">Product Unit</label>
                                <select name="edit_unit" id="edit_unit" class="form-control selectpicker"></select>
                            </div>
                        </div>
                    </div>
                    <!-- /modal body -->

                    <!-- Modal Footer -->
                    <div class="modal-footer">
                        <button type="button" class="btn btn-danger btn-sm" data-dismiss="modal">Close</button>
                        <button type="button" class="btn btn-primary btn-sm" id="update-btn">Update</button>
                    </div>
                    <!-- /modal footer -->
                </form>
            </div>
            <!-- /modal content -->

        </div>
    </div>
    <!-- End :: Edit Modal -->
    <?php echo $__env->make('customer::modal', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
<?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 tax_rate = [];
            var tax_name = [];
            var tax_method = [];
            var unit_name = [];
            var unit_operator = [];
            var unit_operation_value = [];

            //temporary array
            var temp_unit_name = [];
            var temp_unit_operator = [];
            var temp_unit_operation_value = [];

            var rowindex;
            var customer_group_rate;
            var row_product_price;
            <?php if(isset($sale_data)): ?>
            <?php if(!empty($sale_data['products']) && count($sale_data['products']) > 0): ?>
            var rownumber = $('#product_table tbody tr:last').index();

            for (rowindex = 0; rowindex <= rownumber; rowindex++) {
                product_price.push(parseFloat($('#product_table tbody tr:nth-child(' + (rowindex + 1) + ')')
                    .find('.product-price').val()));
                var total_discount = parseFloat($('#product_table tbody tr:nth-child(' + (rowindex + 1) +
                    ')').find('td:nth-child(7)').text())
                var quantity = parseFloat($('#product_table tbody tr:nth-child(' + (rowindex + 1) + ')')
                    .find('.qty').val())
                product_discount.push((total_discount / quantity).toFixed(2));
                product_qty.push(parseFloat($('#product_table tbody tr:nth-child(' + (rowindex + 1) + ')')
                    .find('.stock-qty').val()));
                tax_rate.push(parseFloat($('#product_table tbody tr:nth-child(' + (rowindex + 1) + ')')
                    .find('.tax-rate').val()));
                tax_name.push($('#product_table tbody tr:nth-child(' + (rowindex + 1) + ')').find(
                    '.tax-name').val());
                tax_method.push($('#product_table tbody tr:nth-child(' + (rowindex + 1) + ')').find(
                    '.tax-method').val());
                temp_unit_name = $('#product_table tbody tr:nth-child(' + (rowindex + 1) + ')').find(
                    '.sale-unit').val().split(',');
                unit_name.push($('#product_table tbody tr:nth-child(' + (rowindex + 1) + ')').find(
                    '.sale-unit').val());
                unit_operator.push($('#product_table tbody tr:nth-child(' + (rowindex + 1) + ')').find(
                    '.sale-unit-operator').val());
                unit_operation_value.push($('#product_table tbody tr:nth-child(' + (rowindex + 1) + ')')
                    .find('.sale-unit-operation-value').val());
                $('#product_table tbody tr:nth-child(' + (rowindex + 1) + ')').find('.sale-unit').val(
                    temp_unit_name[0]);
                $('#product_table tbody tr:nth-child(' + (rowindex + 1) + ')').find('.unit-name').text(
                    temp_unit_name[0]);
            }
            <?php endif; ?>
            <?php endif; ?>

            <?php if(isset($sale_data)): ?>
            <?php if(!empty($sale_data['sale']['customer_id'])): ?>
            $.get('<?php echo e(url('customer/group-data')); ?>/' + "<?php echo e($sale_data['sale']['customer_id']); ?>",
                function (data) {
                    customer_group_rate = (data / 100);
                });
            <?php endif; ?>
            <?php endif; ?>

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

            $('#product_code_name').autocomplete({
                // source: "<?php echo e(url('finish-goods-autocomplete-search')); ?>",
                source: function (request, response) {
                    // Fetch data
                    $.ajax({
                        url: "<?php echo e(url('showroom-stock-transfer-product-search')); ?>",
                        type: 'post',
                        dataType: "json",
                        data: {
                            _token: _token,
                            search: request.term,
                            showroom_id: $('#showroom_id option:selected').val()
                        },
                        success: function (data) {
                            response(data);
                        }
                    });
                },
                // minLength: 3,
                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 customer_id = $('#customer_id option:selected').val();
                var showroom_id = $('#showroom_id option:selected').val();
                var temp_data = $('#product_sku').val();
                if (!customer_id) {
                    $('#product_sku').val(temp_data.substring(0, temp_data.length - 1));
                    notification('error', 'Please select customer');
                }
                if (!showroom_id) {
                    $('#product_sku').val(temp_data.substring(0, temp_data.length - 1));
                    notification('error', 'Please select showroom');
                }
            });

            $('#old_invoice').on('change', function () {
                var selectedInvoice = $(this).val();
                if(selectedInvoice) {
                    $('#adjustment_balance').val(selectedInvoice);
                    calculateGrandTotal();
                } else {
                    $('#adjustment_balance').val('0');
                }
            });

            $('#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,
                            showroom_id: $('#showroom_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);
            };

            //Edit Product
            $('#product_table').on('click', '.edit-product', function () {
                rowindex = $(this).closest('tr').index();
                edit();
            });

            //Update Edit Product Data
            $('#update-btn').on('click', function () {
                var edit_discount = $('#edit_discount').val();
                var edit_qty = $('#edit_qty').val();
                var edit_unit_price = $('#edit_unit_price').val();

                if (parseFloat(edit_discount) > parseFloat(edit_unit_price)) {
                    notification('error', 'Invalid discount input');
                    return;
                }

                if (edit_qty < 1) {
                    $('#edit_qty').val(1);
                    edit_qty = 1;
                    notification('error', 'Quantity can\'t be less than 1');
                }

                var row_unit_operator = unit_operator[rowindex].slice(0, unit_operator[rowindex].indexOf(
                    ','));
                var row_unit_operation_value = unit_operation_value[rowindex].slice(0, unit_operation_value[
                    rowindex].indexOf(','));
                row_unit_operation_value = parseFloat(row_unit_operation_value);
                var tax_rate_all = <?php echo json_encode($tax_rate_all); ?>;

                tax_rate[rowindex] = parseFloat(tax_rate_all[$('#edit_tax_rate option:selected').val()]);
                tax_name[rowindex] = $('#edit_tax_rate option:selected').text();

                if (row_unit_operator == '*') {
                    product_price[rowindex] = $('#edit_unit_price').val() / row_unit_operation_value;
                } else {
                    product_price[rowindex] = $('#edit_unit_price').val() * row_unit_operation_value;
                }

                product_discount[rowindex] = $('#edit_discount').val();
                var position = $('#edit_unit').val();
                var temp_operator = temp_unit_operator[position];
                var temp_operation_value = temp_unit_operation_value[position];
                $('#product_table tbody tr:nth-child(' + (rowindex + 1) + ')').find('.purchase-unit').val(
                    temp_unit_name[position]);
                temp_unit_name.splice(position, 1);
                temp_unit_operator.splice(position, 1);
                temp_unit_operation_value.splice(position, 1);

                temp_unit_name.unshift($('#edit_unit option:selected').text());
                temp_unit_operator.unshift(temp_operator);
                temp_unit_operation_value.unshift(temp_operation_value);

                unit_name[rowindex] = temp_unit_name.toString() + ',';
                unit_operator[rowindex] = temp_unit_operator.toString() + ',';
                unit_operation_value[rowindex] = temp_unit_operation_value.toString() + ',';
                checkQuantity(edit_qty, false);
            });

            $('#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);
                tax_rate.splice(rowindex, 1);
                tax_name.splice(rowindex, 1);
                tax_method.splice(rowindex, 1);
                unit_name.splice(rowindex, 1);
                unit_operator.splice(rowindex, 1);
                unit_operation_value.splice(rowindex, 1);
                $(this).closest('tr').remove();
                calculateTotal();
                notification('success', 'Product Removed Successfully');
            });

            <?php if(isset($sale_data)): ?>
            <?php if(!empty($sale_data['products']) && count($sale_data['products']) > 0): ?>
            var count = "<?php echo e(count($sale_data['products'])); ?>";
            <?php else: ?>
            var count = 1;
            <?php endif; ?>
            <?php else: ?>
            var count = 1;
            <?php endif; ?>
            function product_barcode_search(product_id, hasVariant, code, variant_id, variation) {
                $.ajax({
                    url: "<?php echo e(route('get.showroom.product')); ?>",
                    type: 'POST',
                    data: {
                        code: code,
                        _token: _token,
                        showroom_id: $('#showroom_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) {
                                temp_unit_name = data.unit_name.split(',');
                                var newRow = $('<tr>');
                                var cols = '';
                                cols += `<td>` + data.name + `<input type="hidden" name="products[` +
                                    count + `][name]" value="` + data.name + `"></td>`;

                                cols += `<td><input type="text" class="form-control bg-primary text-white" name="products[` +
                                    count + `][code]" value="` + data.sku + ' - ' + data.code + `" readonly></td>`;

                                cols += `<td><input type="text" class="form-control text-center stock-qty" name="products[` +
                                    count + `][stock_qty]"  value="` + data.qty + `" readonly></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="discount text-right"></td>`;
                                cols += `<td class="tax text-right"></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-variant-id" name="products[` + count + `][variant_id]"  value="` + data.variant_id + `">`;
                                cols += `<input type="hidden" class="product-code" name="products[` + count + `][code]" value="` + data.code + `">`;
                                cols += `<input type="hidden" class="product-unit" name="products[` + count + `][unit]" value="` + temp_unit_name[0] + `">`;
                                cols += `<input type="hidden" class="discount-value" name="products[` + count + `][discount]">`;
                                cols += `<input type="hidden" class="discount-rate" name="products[` + count + `][discount_rate]" value="${data.discount_rate}">`;
                                cols += `<input type="hidden" class="tax-rate" name="products[` + count + `][tax_rate]" value="` + data.tax_rate + `">`;
                                cols += `<input type="hidden" class="tax-value" name="products[` + count + `][tax]">`;
                                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_price.push(parseFloat(data.price) + parseFloat(data.price *
                                //     customer_group_rate));
                                product_qty.push(data.qty);
                                product_discount.push('0.00');
                                tax_rate.push(parseFloat(data.tax_rate));
                                tax_name.push(data.tax_name);
                                tax_method.push(data.tax_method);
                                unit_name.push(data.unit_name);
                                unit_operator.push(data.unit_operator);
                                unit_operation_value.push(data.unit_operation_value);
                                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('get.showroom.sku.product')); ?>",
                    type: 'POST',
                    data: {
                        sku: sku,
                        _token: _token,
                        showroom_id: $('#showroom_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) {
                                    temp_unit_name = data.unit_name.split(',');
                                    var newRow = $('<tr>');
                                    var cols = '';
                                    cols += `<td>` + data.name + `<input type="hidden" name="products[` +
                                        count + `][name]" value="` + data.name + `"></td>`;
                                    cols += `<td><input type="text" class="form-control bg-primary text-white" name="products[` +
                                        count + `][code]" value="` + data.sku + ' - ' + data.code + `" readonly></td>`;
                                    // cols += `<td class="text-center">` + data.code + `</td>`;
                                    // cols += `<td class="unit-name text-center"></td>`;
                                    cols +=
                                        `<td><input type="text" class="form-control text-center stock-qty" name="products[` +
                                        count + `][stock_qty]"  value="` + data.qty + `" readonly></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="discount text-right"></td>`;
                                    cols += `<td class="tax text-right"></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-variant-id" name="products[` +
                                        count + `][variant_id]"  value="` + data.variant_id + `">`;
                                    cols += `<input type="hidden" class="product-code" name="products[` +
                                        count + `][code]" value="` + data.code + `">`;
                                    cols += `<input type="hidden" class="product-unit" name="products[` +
                                        count + `][unit]" value="` + temp_unit_name[0] + `">`;
                                    cols += `<input type="hidden" class="discount-value" name="products[` +
                                        count + `][discount]">`;
                                    cols += `<input type="hidden" class="discount-rate" name="products[` +
                                        count +
                                        `][discount_rate]" value="${data.discount_rate}">`;
                                    cols += `<input type="hidden" class="tax-rate" name="products[` +
                                        count +
                                        `][tax_rate]" value="` + data.tax_rate + `">`;
                                    cols += `<input type="hidden" class="tax-value" name="products[` +
                                        count +
                                        `][tax]">`;
                                    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);
                                    product_discount.push('0.00');
                                    tax_rate.push(parseFloat(data.tax_rate));
                                    tax_name.push(data.tax_name);
                                    tax_method.push(data.tax_method);
                                    unit_name.push(data.unit_name);
                                    unit_operator.push(data.unit_operator);
                                    unit_operation_value.push(data.unit_operation_value);
                                    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(sale_qty, flag, input = 2) {
                // var row_product_code = $('#product_table tbody tr:nth-child('+(rowindex + 1)+')').find('td:nth-child(2)').text();
                // var pos = product_code.indexOf(row_product_code);
                var operator = unit_operator[rowindex].split(',');
                var operation_value = unit_operation_value[rowindex].split(',');

                if (operator[0] == '*') {
                    total_qty = sale_qty * operation_value[0];
                } else if (operator[0] == '/') {
                    total_qty = sale_qty / operation_value[0];
                }
                if (total_qty > parseFloat(product_qty[rowindex])) {
                    notification('error', 'Quantity exceed stock quantity');
                    if (flag) {
                        //alert('1');
                        sale_qty = sale_qty.substring(0, sale_qty.length - 1);
                        if (sale_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(
                                sale_qty);
                        }
                    } else {
                        $('#product_table tbody tr:nth-child(' + (rowindex + 1) + ')').find('.qty').val("0");
                        edit();
                        return;
                    }
                }

                if (!flag) {
                    $('#editModal').modal('hide');
                    $('#product_table tbody tr:nth-child(' + (rowindex + 1) + ')').find('.qty').val(sale_qty);
                }
                calculateProductData(sale_qty, input);

            }

            function edit() {
                var row_product_name = $('#product_table tbody tr:nth-child(' + (rowindex + 1) + ')').find(
                    'td:nth-child(1)').text();
                var row_product_code = $('#product_table tbody tr:nth-child(' + (rowindex + 1) + ')').find(
                    'td:nth-child(2)').text();
                $('#model-title').text(row_product_name + '(' + row_product_code + ')');

                var qty = $('#product_table tbody tr:nth-child(' + (rowindex + 1) + ')').find('.qty').val();
                $('#edit_qty').val(qty);
                $('#edit_discount').val(parseFloat(product_discount[rowindex]).toFixed(2));

                unitConversion();
                $('#edit_unit_price').val(row_product_price.toFixed(2));

                var tax_name_all = <?php echo json_encode($tax_name_all); ?>;
                var pos = tax_name_all.indexOf(tax_name[rowindex]);
                $('#edit_tax_rate').val(pos);

                temp_unit_name = (unit_name[rowindex]).split(',');
                temp_unit_name.pop();
                temp_unit_operator = (unit_operator[rowindex]).split(',');
                temp_unit_operator.pop();
                temp_unit_operation_value = (unit_operation_value[rowindex]).split(',');
                temp_unit_operation_value.pop();

                $('#edit_unit').empty();

                $.each(temp_unit_name, function (key, value) {
                    $('#edit_unit').append('<option value="' + key + '">' + value + '</option>');
                });
                $('.selectpicker').selectpicker('refresh');
            }

            function calculateProductData(quantity, input = 2) {
                unitConversion();

                $('#product_table tbody tr:nth-child(' + (rowindex + 1) + ')').find('td:nth-child(6)').text((
                    product_discount[rowindex] * quantity).toFixed(2));
                $('#product_table tbody tr:nth-child(' + (rowindex + 1) + ')').find('.discount-value').val((
                    product_discount[rowindex] * quantity).toFixed(2));
                $('#product_table tbody tr:nth-child(' + (rowindex + 1) + ')').find('.tax-rate').val(tax_rate[
                    rowindex].toFixed(2));
                $('#product_table tbody tr:nth-child(' + (rowindex + 1) + ')').find('.unit-name').text(unit_name[
                    rowindex].slice(0, unit_name[rowindex].indexOf(",")));

                if (tax_method[rowindex] == 1) {
                    var net_unit_price = row_product_price - product_discount[rowindex];
                    var tax = net_unit_price * quantity * (tax_rate[rowindex] / 100);
                    var sub_total = (net_unit_price * quantity) + tax;
                } else {
                    // var sub_total_unit = row_product_price - product_discount[rowindex];
                    // var net_unit_price = (100 / (100 + tax_rate[rowindex])) * sub_total_unit;
                    // var tax = (sub_total_unit - net_unit_price) * quantity;
                    // var sub_total = sub_total_unit * quantity;
                    var net_unit_price = row_product_price - product_discount[rowindex];
                    var tax = net_unit_price * quantity * (tax_rate[rowindex] / 100);
                    var sub_total = (net_unit_price * quantity) + tax;
                }

                // $('#product_table tbody tr:nth-child('+(rowindex + 1)+')').find('td:nth-child(5)').text(net_unit_price.toFixed(2));
                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(7)').text(tax
                    .toFixed(2));
                $('#product_table tbody tr:nth-child(' + (rowindex + 1) + ')').find('.tax-value').val(tax.toFixed(
                    2));
                $('#product_table tbody tr:nth-child(' + (rowindex + 1) + ')').find('td:nth-child(8)').text(
                    sub_total.toFixed(2));
                $('#product_table tbody tr:nth-child(' + (rowindex + 1) + ')').find('.subtotal-value').val(sub_total
                    .toFixed(2));

                calculateTotal();
            }

            function unitConversion() {
                var row_unit_operator = unit_operator[rowindex].slice(0, unit_operator[rowindex].indexOf(','));
                var row_unit_operation_value = unit_operation_value[rowindex].slice(0, unit_operation_value[
                    rowindex].indexOf(','));
                row_unit_operation_value = parseFloat(row_unit_operation_value);
                if (row_unit_operator == '*') {
                    row_product_price = product_price[rowindex] * row_unit_operation_value;
                } else {
                    row_product_price = product_price[rowindex] / row_unit_operation_value;
                }
            }

            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 discount
                var total_discount = 0;
                $('.discount').each(function () {
                    total_discount += parseFloat($(this).text());
                });
                $('#total-discount').text(total_discount.toFixed(2));
                $('input[name="total_discount"]').val(total_discount.toFixed(2));

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

                //sum of subtotal
                var total = 0;
                $('.sub-total').each(function () {
                    total += parseFloat($(this).text());
                });
                $('#total').text(total.toFixed(2));
                $('input[name="total_price"]').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());
                var order_tax = parseFloat($('select[name="order_tax_rate"]').val());
                var order_discount = parseFloat($('#order_discount').val());
                var shipping_cost = parseFloat($('#shipping_cost').val());
                // var labor_cost     = parseFloat($('#labor_cost').val());

                if (!order_discount) {
                    order_discount = 0.00;
                }
                if (!shipping_cost) {
                    shipping_cost = 0.00;
                }
                // if(!labor_cost){
                //     labor_cost = 0.00;
                // }

                var old_invoice_balance = parseFloat($('#adjustment_balance').val());
                console.log(old_invoice_balance);
                item = ++item + '(' + total_qty + ')';
                order_tax = (subtotal - order_discount) * (order_tax / 100);
                var grand_total = (subtotal + order_tax + shipping_cost) - order_discount - old_invoice_balance;
                var previous_due = parseFloat($('#previous_due').val());
                var net_total = grand_total + previous_due;

                $('#item').text(item);
                $('input[name="item"]').val($('#product_table tbody tr:last').index() + 1);
                $('#subtotal').text(subtotal.toFixed(2));
                $('#order_total_tax').text(order_tax.toFixed(2));
                $('input[name="order_tax"]').val(order_tax.toFixed(2));
                $('#order_total_discount').text(order_discount.toFixed(2));
                $('#shipping_total_cost').text(shipping_cost.toFixed(2));
                // $('#labor_total_cost').text(labor_cost.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));
                if ($('#payment_status option:selected').val() == 1) {
                    $('#paid_amount').val(net_total.toFixed(2));
                    $('#due_amount').val(parseFloat(0).toFixed(2));
                } else if ($('#payment_status option:selected').val() == 2) {
                    var paid_amount = $('#paid_amount').val();
                    $('#due_amount').val(parseFloat(net_total - paid_amount).toFixed(2));
                } else {
                    $('#due_amount').val(parseFloat(net_total).toFixed(2));
                }
            }

            $('input[name="order_discount"]').on('input', function () {
                if (parseFloat($(this).val()) > parseFloat($('input[name="grand_total"]').val())) {
                    notification('error', 'Order discount can\'t exceed grand total amount');
                    $('input[name="order_discount"]').val(parseFloat(0));
                }
                calculateGrandTotal();

            });
            $('input[name="shipping_cost"]').on('input', function () {
                calculateGrandTotal();
            });
            // $('input[name="labor_cost"]').on('input',function(){
            //     calculateGrandTotal();
            // });
            $('select[name="order_tax_rate"]').on('change', function () {
                calculateGrandTotal();
            });

            $('#payment_status').on('change', function () {
                if ($(this).val() != 3) {
                    $('.payment').removeClass('d-none');
                    // $('#paid_amount').val($('input[name="net_total"]').val());
                    $('#due_amount').val(parseFloat(0).toFixed(2));
                    $('#paid_amount').val(0);
                } else {
                    $('#paid_amount').val(0);
                    $('#due_amount').val(parseFloat($('input[name="net_total"]').val()).toFixed(2));
                    $('.payment').addClass('d-none');
                }
            });

            $('#paid_amount').on('input', function () {
                var payable_amount = parseFloat($('input[name="net_total"]').val());
                var paid_amount = parseFloat($(this).val());

                if (paid_amount > payable_amount) {
                    $('#paid_amount').val(payable_amount.toFixed(2));
                    notification('error', 'Paid amount cannot be bigger than net total amount');
                }
                $('#due_amount').val((payable_amount - parseFloat($('#paid_amount').val())).toFixed(2));

            });

            //Customer Form Data Save Code
            $(document).on('click', '#store_or_update_modal #save-btn', function () {
                let form = document.getElementById('store_or_update_form');
                let formData = new FormData(form);
                console.log('i am here');
                $.ajax({
                    url: "<?php echo e(route('customer.wholesale.store.or.update')); ?>",
                    type: "POST",
                    data: formData,
                    dataType: "JSON",
                    contentType: false,
                    processData: false,
                    cache: false,
                    beforeSend: function () {
                        $('#customer-save-btn').addClass('spinner spinner-white spinner-right');
                    },
                    complete: function () {
                        $('#customer-save-btn').removeClass(
                            'spinner spinner-white spinner-right');
                    },
                    success: function (data) {
                        $('#store_or_update_form').find('.is-invalid').removeClass(
                            'is-invalid');
                        $('#store_or_update_form').find('.error').remove();
                        if (data.status == false) {
                            $.each(data.errors, function (key, value) {
                                var key = key.split('.').join('_');
                                $('#store_or_update_form input#' + key).addClass(
                                    'is-invalid');
                                $('#store_or_update_form textarea#' + key).addClass(
                                    'is-invalid');
                                $('#store_or_update_form select#' + key).parent()
                                    .addClass('is-invalid');
                                $('#store_or_update_form #' + key).parent().append(
                                    '<small class="error text-danger">' + value +
                                    '</small>');
                            });
                        } else {
                            notification(data.status, data.message);
                            if (data.status == 'success') {
                                $('#store_or_update_modal').modal('hide');
                                customer_list(data.id);
                            }
                        }

                    },
                    error: function (xhr, ajaxOption, thrownError) {
                        console.log(thrownError + '\r\n' + xhr.statusText + '\r\n' + xhr
                            .responseText);
                    }
                });
            });
        });
        <?php if(isset($sale_data)): ?>
        <?php if(!empty($sale_data['sale']['payment_method'])): ?>
        account_list("<?php echo e($sale_data['sale']['payment_method']); ?>", "<?php echo e($sale_data['sale']['account_id']); ?>");
        <?php endif; ?>
        <?php endif; ?>
        function account_list(payment_method, idx) {
            $.ajax({
                url: "<?php echo e(route('account.list')); ?>",
                type: "POST",
                data: {
                    payment_method: payment_method,
                    _token: _token
                },
                success: function (data) {

                    $('#sale_store_form #payment_' + idx + '_account_id').empty().html(data);
                    $('#sale_store_form #payment_' + idx + '_account_id').selectpicker('refresh');


                    if (payment_method != 1) {

                        $(`.reference_no_${idx}`).removeClass('d-none').addClass('pt-1'); // You can change 'pt-4' to your desired padding class
                    } else {


                        $(`.reference_no_${idx}`).addClass('d-none');
                    }


                },
                error: function (xhr, ajaxOption, thrownError) {
                    console.log(thrownError + '\r\n' + xhr.statusText + '\r\n' + xhr.responseText);
                }
            });
        }

        <?php if(isset($sale_data) && !empty($sale_data['sale']['customer_id'])): ?>
        customer_list("<?php echo e($sale_data['sale']['customer_id']); ?>");
        <?php else: ?>
        customer_list();
        <?php endif; ?>
        function customer_list(customer_id = '') {
            $.ajax({
                url: "<?php echo e(route('wholesale.customer.list')); ?>",
                type: "POST",
                data: {
                    _token: _token
                },
                success: function (data) {
                    $('#sale_store_form #customer_id').html('');
                    $('#sale_store_form #customer_id').html(data);
                    $('#sale_store_form #customer_id.selectpicker').selectpicker('refresh');
                    if (customer_id) {
                        $('#sale_store_form #customer_id').val(customer_id);
                        $('#sale_store_form #customer_id.selectpicker').selectpicker('refresh');
                    }
                },
                error: function (xhr, ajaxOption, thrownError) {
                    console.log(thrownError + '\r\n' + xhr.statusText + '\r\n' + xhr.responseText);
                }
            });
        }

        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('sale_store_form');
                let formData = new FormData(form);
                let url = "<?php echo e(route('sale.saleStore')); ?>";
                $.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('_');
                                $('#sale_store_form input#' + key).addClass('is-invalid');
                                $('#sale_store_form textarea#' + key).addClass('is-invalid');
                                $('#sale_store_form select#' + key).parent().addClass('is-invalid');
                                $('#sale_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(url('sale/customer-copy')); ?>/" + data.id);
                            }
                        }

                    },
                    error: function (xhr, ajaxOption, thrownError) {
                        console.log(thrownError + '\r\n' + xhr.statusText + '\r\n' + xhr.responseText);
                    }
                });
            }

        }

        function hold_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('sale_store_form');
                let formData = new FormData(form);
                let url = "<?php echo e(route('sale.hold')); ?>";
                $.ajax({
                    url: url,
                    type: "POST",
                    data: formData,
                    dataType: "JSON",
                    contentType: false,
                    processData: false,
                    cache: false,
                    beforeSend: function () {
                        $('#hold-btn').addClass('spinner spinner-white spinner-right');
                    },
                    complete: function () {
                        $('#hold-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();
                        notification(data.status, data.message);
                    },
                    error: function (xhr, ajaxOption, thrownError) {
                        console.log(thrownError + '\r\n' + xhr.statusText + '\r\n' + xhr.responseText);
                    }
                });
            }
        }

        $('.payment_amounts').on('input', function () {

            var value = $(this).val();

            if ((value !== '') && (value.indexOf('.') === -1)) {
                let payable_amount = parseFloat($('input[name="net_total"]').val());

                let paid_amount = $('#paid_amount').val() ? parseFloat($('#paid_amount').val()) : 0;

                let ongoing = (payable_amount - paid_amount).toFixed(2);


                if (value > payable_amount || value < 0) {
                    notification('error', 'The Payment Can not grater than payable amount');
                }

            }
        });

        function calculatePaymentAmount(value = 0) {
            // return;
            let totals = 0;
            $(".payment_amounts").each(function () {
                var inputValue = $(this).val() > 0 ? $(this).val() : 0;

                if (!isNaN(inputValue)) {
                    totals += parseFloat(inputValue);
                }
            });

            if (!isNaN(totals)) {

                var payable_amount = parseFloat($('input[name="net_total"]').val());
                let dues = (payable_amount - totals).toFixed(2);

                if (dues >= 0) {
                    $('#paid_amount').val(totals);
                    $('#due_amount').val(dues);
                }


            }
        }

        let table_row = 0;

        function removeRow(element, idx) {
            $('#' + element + idx).closest('div').remove();
            table_row--;
            calculatePaymentAmount();
            // calculateTotalCredit();
        }

        function addTableRow(tableId, idx) {
            console.log('lol222');

            table_row = idx;
            ++table_row;


            // Assuming PAYMENT_STATUS is a JavaScript array or object
            let paymentOptions = [
                    <?php $__currentLoopData = SALE_PAYMENT_METHOD; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $key => $value): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                {
                    key: '<?php echo e($key); ?>', value: '<?php echo e($value); ?>'
                },
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
            ];


            let selectOptions = '';
            paymentOptions.forEach(option => {
                selectOptions += `<option value="${option.key}" data-reference_id="${table_row}" >${option.value}</option>`;
            });


            let html = `
               <div class="row col-md-12" id="payment_method_tr_${table_row}">
        <div class="form-group col-md-3">
            <label>Payment Method</label>
            <select class="form-control selectpicker"
                data-live-search="true"
                id="payment_${table_row}_payment_method"
                 name="payment[${table_row}][payment_method]"
                onchange="account_list(this.value,${table_row})"
                 data-reference_id="${table_row}"
                data-live-search-placeholder="Search">
                <option value="">Select Please</option>
                ${selectOptions}
            </select>
        </div>
            <div class="form-group col-md-3">
                    <label>Account</label>
                    <select class="form-control  selectpicker"
                         id="payment_${table_row}_account_id"
                                data-live-search="true"
                     name="payment[${table_row}][account_id]"
                                 data-live-search-placeholder="Search">
                        <option value="">Select Please</option>
                    </select>
                </div>
                <div class="form-group col-md-3  d-none reference_no_${table_row}"
                    <label for="reference_no">Reference No</label>
                    <input type="text" class="fcs form-control"
                       name="payment[${table_row}][reference_no]"
                       id="payment_${table_row}_reference_no">
                </div>


                <div class="form-group col-md-2 ">
                <label for="payment_amounts">Amount</label>
                <input type="number" class="fcs form-control payment_amounts"
                        oninput="calculatePaymentAmount(this.value)" value="0"
                       name="payment[${table_row}][payment_amount]"
                       id="payment_${table_row}_payment_amount">
                </div>

            <div
            class="mb-2 d-flex flex-column justify-content-center align-items-center">
            <button type="button" class="btn btn-danger btn-sm"
            onclick="removeRow('payment_method_tr_','${table_row}')">
            <i class="fas fa-minus"></i>
            </button>
            <button type="button" class="btn btn-success btn-sm"
            onclick="addTableRow('payment_method','${table_row}')">
            <i class="fas fa-plus"></i>
            </button>
            </div>
            </div>
    `;

            // Append the new row to the table or container with the specified ID
            $('#' + tableId).append(html);

            // Refresh the selectpicker to apply Bootstrap-select styling
            $('#' + tableId + ' .selectpicker').selectpicker('refresh');
        }
    </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/Sale/Resources/views/create.blade.php ENDPATH**/ ?>