

<?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;
        }

        table td {
            vertical-align: middle !important;

        }

        #pos_edit_table td {
            max-width: 70px;
        }

        .button-text-select {
            -webkit-user-select: text;
            -moz-user-select: text;
            -ms-user-select: text;
            user-select: text;
            width: 100px;
        }


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

<?php $__env->startSection('content'); ?>
    <div class="d-flex flex-column-fluid">
        <div class="container-fluid">

            <!--begin::Card-->
            <div class="card card-custom" style="background: none !important;">
                <div class="card-body p-0">
                    <div class="row">

                        <div class="col-md-4">
                            <div class="card card-custom card-border" style="background: none;">
                                <div class="card-body px-0" style="min-height:100vh;">
                                    <div class="col-md-12 px-0">
                                        <div class="row">
                                            <div class="form-group col-md-6 px-1">
                                                <label for="brand_id">Brand</label>
                                                <select class="form-control selectpicker" name="brand_id" id="brand_id"
                                                        onchange="load_products()" data-live-search="true">
                                                    <option value="0">Select Brand</option>
                                                    <?php if(!$brands->isEmpty()): ?>
                                                        <?php $__currentLoopData = $brands; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $brand): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                            <option value="<?php echo e($brand->id); ?>"><?php echo e($brand->name); ?></option>
                                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                                    <?php endif; ?>
                                                </select>
                                            </div>

                                            <div class="form-group col-md-6 px-1">
                                                <label for="category_id">Category</label>
                                                <select class="form-control selectpicker" name="category_id"
                                                        id="category_id" onchange="load_products()"
                                                        data-live-search="true">
                                                    <option value="0">Select Category</option>
                                                    <?php if(!$categories->isEmpty()): ?>
                                                        <?php $__currentLoopData = $categories; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $category): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                            <option value="<?php echo e($category->id); ?>"><?php echo e($category->name); ?>

                                                            </option>
                                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                                    <?php endif; ?>
                                                </select>
                                            </div>

                                            <div class="form-group col-md-12 px-1">
                                                
                                                <input type="text" class="form-control" name="sku_name"
                                                       id="sku_name" oninput="load_products()"
                                                       placeholder="Search SKU"/>
                                            </div>
                                        </div>
                                        <div class="row" id="product-section" style="position: relative;">
                                            <table class="table table-bordered product-table bg-white"
                                                   id="pos_edit_table">
                                                <tbody>
                                                <?php echo $__env->make('sale::ecommerce-pos.pos-product-list', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
                                                </tbody>
                                            </table>
                                            <div id="product_loading" class="col-md-12 d-none"
                                                 style="height: 100%;background: white;position: absolute;top:0;left:0;">
                                                <div class="col-md-12  text-center" style="padding-top: 45%;">
                                                    <i class="fa fa-spinner fa-spin fa-3x fa-fw text-primary"
                                                       aria-hidden="true" style="font-size: 80px;"></i>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-8">
                            <form action="" id="sale_store_form" method="post" enctype="multipart/form-data">
                                <?php echo csrf_field(); ?>
                                <input type="hidden" name="sale_id" id="sale_id" value="<?php echo e($sale->id); ?>">
                                <input type="hidden" class="form-control date" name="sale_date" id="sale_date"
                                       value="<?php echo e($sale->sale_date); ?>" readonly/>
                                <input type="hidden" class="form-control" name="invoice_no" id="invoice_no"
                                       value="<?php echo e($sale->invoice_no); ?>" readonly/>

                                <div class="card card-custom card-border">
                                    <div class="card-body" style="padding: 2rem 10px !important;min-height:100vh;">
                                        <div class="row">
                                            <input type="hidden" name="update_id" value="<?php echo e($sale->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-6','class' => 'selectpicker','disabled' => true]]); ?>
<?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-6','class' => 'selectpicker','disabled' => true]); ?>
                                                <?php if($sale->showroom): ?>

                                                    <option value="<?php echo e($sale->showroom_id); ?>"
                                                            <?php if($sale->showroom_id): ?> selected <?php endif; ?> ><?php echo e($sale->showroom->name); ?></option>
                                                <?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-6">
                                                <label for="customer_id" style="width: 100%;margin-bottom: 0.1rem;">
                                                    <span class="float-left">Customer<b class="text-danger">*</b></span>
                                                </label>

                                                <select class="form-control selectpicker" name="customer_id"
                                                        id="customer_id" data-live-search="true" disabled>
                                                    <?php if($sale->customer): ?>
                                                        <option value="<?php echo e($sale->customer_id); ?>"
                                                                <?php if($sale->customer_id): ?> selected <?php endif; ?> ><?php echo e($sale->customer->name); ?></option>
                                                    <?php endif; ?>
                                                </select>

                                            </div>
                                            <div class="form-group col-md-12 required">
                                                <label for="memo_no">Shipping Address.</label>
                                                <input type="text" class="form-control" name="shipping_address" id="shipping_address" value="<?php echo e($sale->shipping_address); ?>"/>
                                            </div>
                                            <div class="form-group col-md-12">
                                                <div class="input-group mb-3">
                                                    <div class="input-group-prepend">
                                                        <span class="input-group-text bg-primary" id="basic-addon1"><i
                                                                class="fas fa-barcode text-white"></i></span>
                                                    </div>

                                                    <input type="text" class="form-control" name="product_code_name"
                                                           id="product_code_name"
                                                           placeholder="Scan/Search by product code">
                                                </div>
                                            </div>
                                        </div>

                                        <div class="col-md-12 px-0">
                                            <table class="table table-bordered" id="product_table">
                                                <thead class="bg-primary">
                                                <th colspan="" style="width: 30%">Name</th>
                                                <th class="text-center" style="width: 10%">Qty</th>
                                                <th class="text-center" style="width: 10%">Price</th>
                                                <th class="text-center">Discount</th>
                                                <th class="text-center">Tax</th>
                                                <th class="text-center">Subtotal</th>
                                                <th></th>
                                                </thead>
                                                <tbody>
                                                <?php if(!$sale->products->isEmpty()): ?>
                                                    <?php $__currentLoopData = $sale->products; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $key => $sale_product): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                        <tr>
                                                            <?php
                                                                $tax = DB::table('taxes')
                                                                    ->where('rate', $sale_product->pivot->tax_rate)
                                                                    ->first();

                                                                $units = DB::table('units')
                                                                    ->where('base_unit', $sale_product->unit_id)
                                                                    ->orWhere('id', $sale_product->unit_id)
                                                                    ->get();
                                                                  $warehouse_product = DB::table('showroom_products')
                                                                    ->where([
                                                                        'showroom_id' => $sale->showroom_id,
                                                                        'product_id' => $sale_product->id,
                                                                        'product_code' => $sale_product->pivot->product_code,
                                                                    ])
                                                                    ->first();

                                                                $stock_qty =   ($warehouse_product ? $warehouse_product->qty : 0);


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

                                                                if ($units) {
                                                                    foreach ($units as $unit) {
                                                                        if ($sale_product->pivot->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 ($sale_product->tax_method == 1) {
                                                                        $product_price = $sale_product->pivot->net_unit_price + $sale_product->pivot->discount / $sale_product->pivot->qty;
                                                                    } else {
                                                                        $product_price = $sale_product->pivot->total / $sale_product->pivot->qty + $sale_product->pivot->discount / $sale_product->pivot->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) . ',';
                                                                }
                                                            ?>

                                                            <?php
                                                                $thisProductCode = $sale_product->product_code;
                                                                $variantName = '';
                                                                $thisVariantId = null;
                                                                   if (!empty($sale_product->pivot->variant_id)) {
                                                                    $variant = DB::table('product_variants as pv')
                                                                        ->where('pv.product_id', $sale_product->id)
                                                                        ->where('pv.product_code', $sale_product->pivot->product_code)
                                                                        ->first();


                                                                    $color = '';
                                                                    if (!empty($variant->color_id)) {
                                                                        $colorObj = DB::table('colors')
                                                                            ->where('id', $variant->color_id)
                                                                            ->first('name');
                                                                        $color = $colorObj->name . '-';
                                                                    }

                                                                    $attributes = '';
                                                                    $thisVariantId = $variant->id;
                                                                    if (!empty($variant->variant_id)) {
                                                                        $attributeArr = array_filter(explode('-', $variant->variant_id));

                                                                        foreach ($attributeArr as $attributeKey => $attributeValue) {
                                                                            $variantValue = DB::table('attribute_values')
                                                                                ->where('id', $attributeValue)
                                                                                ->first('value');


                                                                            if ($variantValue) {
                                                                                if ($attributeKey != 0) {
                                                                                    $attributes .= '-' . $variantValue->value;
                                                                                } else {
                                                                                    $attributes = $variantValue->value;
                                                                                }
                                                                            }
                                                                        }
                                                                    }
                                                                    $variantName = $color . '' . $attributes;
                                                                    $thisProductCode = $variant->product_code;
                                                                }
                                                            ?>
                                                            <td><span class="edit-product text-primary mb-0"
                                                                      data-toggle="modal" data-target="#editModal"
                                                                      style="cursor:pointer;"><?php echo $sale_product->product_name; ?></span>
                                                                &nbsp;
                                                                <?php echo e($variantName); ?><br><b><?php echo e($thisProductCode); ?><br>Stock
                                                                    Qty:</b><?php echo e($stock_qty); ?></td>

                                                            <td><input type="text"
                                                                       class="form-control qty text-center"
                                                                       data-stock="<?php echo e($stock_qty); ?>"
                                                                       name="products[<?php echo e($key + 1); ?>][qty]"
                                                                       id="products_<?php echo e($key + 1); ?>_qty"
                                                                       value="<?php echo e($sale_product->pivot->qty); ?>">
                                                            </td>

                                                            <td><input type="text"
                                                                       class="net_unit_price form-control text-center"
                                                                       name="products[<?php echo e($key + 1); ?>][net_unit_price]"
                                                                       id="products_<?php echo e($key + 1); ?>_net_unit_price"
                                                                       value="<?php echo e($sale_product->pivot->net_unit_price); ?>">
                                                            </td>
                                                            <td class="discount text-center">
                                                                <?php echo e(number_format((float) $sale_product->pivot->discount, 2, '.', '')); ?>

                                                            </td>
                                                            <td class="tax text-center">
                                                                <?php echo e(number_format((float) $sale_product->pivot->tax, 2, '.', '')); ?>

                                                            </td>
                                                            <td class="sub-total text-center">
                                                                <?php echo e(number_format((float) $sale_product->pivot->total, 2, '.', '')); ?>

                                                            </td>
                                                            <td class="text-center"><i
                                                                    class="fas fa-trash remove-product text-danger"
                                                                    style="cursor:pointer;"></i></td>
                                                            <input type="hidden" class="product-id"
                                                                   name="products[<?php echo e($key + 1); ?>][id]"
                                                                   value="<?php echo e($sale_product->id); ?>">

                                                            <input type="hidden" class="product-code"
                                                                   name="products[<?php echo e($key + 1); ?>][code]"
                                                                   value="<?php echo e($thisProductCode); ?>">
                                                            <input type="hidden" class="stock-qty"
                                                                   name="products[<?php echo e($key + 1); ?>][stock_qty]"
                                                                   value="<?php echo e($stock_qty); ?>">
                                                            <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($sale_product->pivot->discount); ?>">
                                                            <input type="hidden" class="discount-rate"
                                                                   name="products[<?php echo e($key + 1); ?>][discount_rate]"
                                                                   value="<?php echo e($sale_product->pivot->discount_rate); ?>">
                                                            <input type="hidden" class="tax-rate"
                                                                   name="products[<?php echo e($key + 1); ?>][tax_rate]"
                                                                   value="<?php echo e($sale_product->pivot->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($sale_product->tax_method); ?>">
                                                            <input type="hidden" class="tax-value"
                                                                   name="products[<?php echo e($key + 1); ?>][tax]"
                                                                   value="<?php echo e($sale_product->pivot->tax); ?>">
                                                            <input type="hidden" class="subtotal-value"
                                                                   name="products[<?php echo e($key + 1); ?>][subtotal]"
                                                                   value="<?php echo e($sale_product->pivot->total); ?>">

                                                            <input type="hidden" class=""
                                                                   name="products[<?php echo e($key + 1); ?>][variant_id]"
                                                                   value="<?php echo e($thisVariantId); ?>">
                                                        </tr>
                                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                                <?php endif; ?>
                                                </tbody>
                                                <tfoot>
                                                <tr class="bg-primary">
                                                    <th colspan="" class="font-weight-bolder">Total</th>
                                                    <th id="total-qty" class="text-center font-weight-bolder">
                                                        <?php echo e($sale->total_qty); ?></th>
                                                    <th></th>
                                                    <th id="total-discount" class="text-right font-weight-bolder">
                                                        <?php echo e(number_format($sale->total_discount, 2, '.', ',')); ?></th>
                                                    <th id="total-tax" class="text-right font-weight-bolder">
                                                        <?php echo e(number_format($sale->total_tax, 2, '.', ',')); ?></th>
                                                    <th id="total" class="text-right font-weight-bolder">
                                                        <?php echo e(number_format($sale->total_price, 2, '.', ',')); ?></th>
                                                    <th></th>
                                                </tr>
                                                <tr>
                                                    <td colspan="5"
                                                        style="color: #000 !important;border: none;padding-top: 20px !important;"
                                                        class="text-right font-weight-bolder pt-5">
                                                        <div class="form-group row mb-0">
                                                            <label for="inputPassword"
                                                                   class="col-md-8 col-form-label font-weight-bolder">Order
                                                                Tax: </label>
                                                            <div class="col-md-4">
                                                                <select name="order_tax_rate" id="order_tax_rate"
                                                                        class="form-control 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 echo e($sale->order_tax_rate == $tax->rate ? 'selected' : ''); ?>>
                                                                                <?php echo e($tax->name); ?></option>
                                                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                                                    <?php endif; ?>
                                                                </select>
                                                            </div>
                                                        </div>
                                                    </td>
                                                    <td colspan="2" style="padding-top: 20px !important;">
                                                        <input type="text"
                                                               class="form-control text-right bg-secondary"
                                                               name="order_tax" value="<?php echo e($sale->order_tax); ?>"
                                                               id="order_tax" placeholder="0.00" readonly>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td colspan="5" style="color: #000 !important;border: none;"
                                                        class="text-right font-weight-bolder">Order Discount: <input
                                                            placeholder="%" name="order_discount_per"
                                                            id="order_discount_per" type="checkbox"
                                                            <?php echo e($sale->order_discount_per == 2 ? 'checked' : ''); ?> /><label
                                                            for="order_discount_per">%</label></td>
                                                    <td colspan="2">
                                                        <input type="text" class="form-control text-right"
                                                               name="order_discount" id="order_discount"
                                                               value="<?php echo e($sale->order_discount); ?>" placeholder="0.00">
                                                    </td>
                                                </tr>
                                                
                                                
                                                
                                                
                                                
                                                
                                                
                                                
                                                
                                                <tr>
                                                    <td colspan="5" style="color: #000 !important;border: none;"
                                                        class="text-right font-weight-bolder">Available Point:
                                                    </td>
                                                    <td colspan="2">
                                                        <input type="hidden" class="form-control text-right"
                                                               name="t_point" id="t_point">
                                                        <input type="hidden" class="form-control text-right"
                                                               name="edit_t_point" id="edit_t_point"
                                                               value="<?php echo e($sale->point); ?>">
                                                        <input type="text"
                                                               class="form-control text-right bg-secondary"
                                                               name="point" id="point"
                                                               value="<?php echo e($sale->point); ?>" readonly>
                                                        <input type="hidden"
                                                               class="form-control text-right bg-secondary"
                                                               name="point_money" id="point_money"
                                                               value="<?php echo e($get_point->money); ?>">
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td colspan="5" style="color: #000 !important;border: none;"
                                                        class="text-right font-weight-bolder">Use Point:
                                                    </td>
                                                    <td colspan="2">
                                                        <input type="text" class="form-control text-right"
                                                               name="edit_use_point" id="edit_use_point"
                                                               value="<?php echo e($sale->use_point); ?>">
                                                        
                                                        
                                                        
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td colspan="5" style="color: #000 !important;border: none;"
                                                        class="text-right font-weight-bolder">Net Total:
                                                    </td>
                                                    <td colspan="2">
                                                        <input type="text"
                                                               class="form-control text-right bg-secondary"
                                                               name="net_total" id="net_total"
                                                               value="<?php echo e($sale->net_total); ?>" placeholder="0.00"
                                                               readonly>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td colspan="5" style="color: #000 !important;border: none;"
                                                        class="text-right font-weight-bolder">Adjustment: <input
                                                            placeholder="-" name="adjustment_per" id="adjustment_per"
                                                            <?php echo e($sale->adjustment_per == 2 ? 'checked' : ''); ?>

                                                            type="checkbox"/><label for="adjustment_per">(-)</label>
                                                    </td>
                                                    <td colspan="2">
                                                        <input type="text" class="form-control text-right"
                                                               name="adjustment" id="adjustment"
                                                               value="<?php echo e($sale->adjustment); ?>" placeholder="0.00">
                                                    </td>
                                                </tr>


                                                <tr>
                                                    <td colspan="5" style="color: #000 !important;border: none;"
                                                        class="text-right font-weight-bolder">
                                                    </td>
                                                    <td colspan="2">

                                                        <?php $__currentLoopData = $delivery_changes; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $key => $value): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                            <div class="form-check form-check-lg">
                                                                <input class="form-check-input form-check-input-lg"
                                                                       type="radio"
                                                                       onchange="setDeliveryCharge(this.value, <?php echo e($value->value); ?>)"
                                                                       data-price="<?php echo e($value->value); ?>"
                                                                       name="delivery_charge_id"
                                                                       value="<?php echo e($value->id); ?>"
                                                                       <?php if($value->id == $sale->delivery_charge_id): ?> checked <?php endif; ?> >
                                                                <label class="form-check-label" for="delivery_charge">
                                                                    <?php echo e($value->name); ?>

                                                                </label>
                                                            </div>
                                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>

                                                    </td>

                                                </tr>
                                                <tr>
                                                    <td colspan="5" style="color: #000 !important;border: none;"
                                                        class="text-right font-weight-bolder">Delivery Charge:
                                                    </td>
                                                    <td colspan="2">
                                                        <input type="number" oninput="calculateTotal()"
                                                               class="form-control text-right"
                                                               value="<?php echo e($sale->delivery_charge); ?>"
                                                               name="delivery_charge" id="delivery_charge"
                                                               placeholder="0.00">
                                                    </td>
                                                </tr>

                                                <tr>
                                                    <td colspan="5" style="color: #000 !important;border: none;"
                                                        class="text-right font-weight-bolder">Grand Total:
                                                    </td>
                                                    <td colspan="2">
                                                        <input type="text"
                                                               class="form-control text-right bg-secondary"
                                                               name="grand_total" id="grand_total"
                                                               value="<?php echo e($sale->grand_total); ?>" placeholder="0.00"
                                                               readonly>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td colspan="5" style="color: #000 !important;border: none;"
                                                        class="text-right font-weight-bolder">Paid Amount:
                                                    </td>
                                                    <td colspan="2">
                                                        <input type="text" class="form-control text-right"
                                                               name="paid_amount" id="paid_amount"
                                                               value="<?php echo e($sale->paid_amount); ?>" placeholder="0.00">
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td colspan="5" style="color: #000 !important;border: none;"
                                                        class="text-right font-weight-bolder">Due Amount:
                                                    </td>
                                                    <td colspan="2">
                                                        <input type="text"
                                                               class="form-control text-right bg-secondary"
                                                               name="due_amount" id="due_amount"
                                                               value="<?php echo e($sale->due_amount); ?>" placeholder="0.00"
                                                               readonly>

                                                    </td>
                                                </tr>

                                                <tr>
                                                    <td colspan="5" style="color: #000 !important;border: none;"
                                                        class="text-right font-weight-bolder">Order From:
                                                    </td>
                                                    <td colspan="2">
                                                        <select class="form-control selectpicker" name="order_source"
                                                                id="order_source"
                                                                data-live-search="true"
                                                                data-live-search-placeholder="Search">
                                                            <option value="">Select Please</option>
                                                            <?php $__currentLoopData = POS_ORDER_FROM; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $key => $value): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                                <option value="<?php echo e($key); ?>"
                                                                        <?php if($key == $sale->order_source): ?> selected <?php endif; ?> ><?php echo e($value); ?></option>
                                                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                                        </select>

                                                    </td>

                                                </tr>

                                                <tr>
                                                    <td colspan="5" style="color: #000 !important;border: none;"
                                                        class="text-right font-weight-bolder">Payment Status:
                                                    </td>
                                                    <td colspan="2">
                                                        <select class="form-control selectpicker"
                                                                data-live-search="true" name="payment_status"
                                                                id="payment_status"
                                                                data-live-search-placeholder="Search">
                                                            <option value="">Select Please</option>
                                                            <?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($key  == $sale->payment_status ): ?> selected <?php endif; ?> ><?php echo e($value); ?></option>
                                                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                                        </select>


                                                    </td>

                                                </tr>


                                                </tfoot>
                                            </table>
                                        </div>
                                        <div class="col-md-12">

                                            <div class="row col-md-12 pt-15 d-none" id="payment_method">


                                                <?php $__empty_1 = true; $__currentLoopData = $sale->payments; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $pay_key => $pay_item): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>

                                                    <div class="row col-md-12"
                                                         id="payment_method_tr_<?php echo e($pay_key); ?>">

                                                        <div class="form-group col-md-3">
                                                            <label>Payment Method</label>
                                                            <select class="form-control selectpicker"
                                                                    name="payment[<?php echo e($pay_key); ?>][payment_method]"
                                                                    onchange="account_list(this.value,<?php echo e($pay_key); ?>,<?php echo e($pay_item->account_id); ?>)"
                                                                    id="payment_<?php echo e($pay_key); ?>_payment_method">
                                                                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); ?>"
                                                                            <?php if($pay_item->payment_method == $key): ?> selected
                                                                            <?php endif; ?>  data-reference_id="<?php echo e($pay_key); ?>"><?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[<?php echo e($pay_key); ?>][account_id]"
                                                                    id="payment_<?php echo e($pay_key); ?>_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_<?php echo e($pay_key); ?>">
                                                            <label for="reference_no">Reference No</label>
                                                            <input type="text" class="fcs form-control"
                                                                   name="payment[<?php echo e($pay_key); ?>][reference_no]"
                                                                   value="<?php echo e($pay_item->reference_no); ?>"
                                                                   id="payment_<?php echo e($pay_key); ?>_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="<?php echo e($pay_item->paid_amount); ?>"
                                                                   name="payment[<?php echo e($pay_key); ?>][payment_amount]"
                                                                   id="payment_<?php echo e($pay_key); ?>_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',<?php echo e($pay_key); ?>)">
                                                                <i class="fas fa-plus"></i>
                                                            </button>
                                                        </div>

                                                    </div>
                                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>

                                                    <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]"
                                                                    onchange="account_list(this.value,0)"
                                                                    id="payment_0_payment_method"
                                                                    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)"
                                                                   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>

                                                <?php endif; ?>

                                            </div>

                                            <div class="row">


                                                <div class="form-group col-md-12 text-center pt-5">
                                                    <label class="text-center"><b>Notes</b></label>
                                                    <textarea col="8" class="form-control" name="notes"><?php echo e($sale->notes); ?></textarea>
                                                </div>
                                            </div>

                                            <div class="row">


                                                <div class="col-md-12">
                                                    <input type="hidden" name="total_qty">
                                                    <input type="hidden" name="total_discount">
                                                    <input type="hidden" name="total_tax">
                                                    <input type="hidden" name="total_price">
                                                    <input type="hidden" name="item">
                                                </div>

                                                <div class="form-group col-md-12 text-center pt-5">
                                                    
                                                    <button type="button" class="btn btn-primary btn-sm mr-3"
                                                            id="pos-save-btn" onclick="store_data()"><i
                                                            class="fas fa-save"></i> Save
                                                    </button>
                                                    
                                                    
                                                    
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                </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">
                        
                    </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>
        var count = 1;
        //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;

        $(document).ready(function () {

            var jsArray = <?php echo $sale->payments; ?>;

            $.each(jsArray, function (index, value) {

                $('select[name="payment[' + index + '][payment_method]"]').trigger('change');

            });


            $('#payment_status').on('change', function () {

                if ($(this).val() != 3) {
                    $('#payment_method *').prop('disabled', false);
                    $(`#payment_method`).removeClass('d-none');
                } else {
                    $('#payment_method *').prop('disabled', true);
                    $(`#payment_method`).addClass('d-none');
                }
            });

            $('#payment_status').trigger('change');


            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(4)').text())
                var quantity = parseFloat($('#product_table tbody tr:nth-child(' + (rowindex + 1) + ')').find(
                    '.qty').val())
                product_discount.push((total_discount / quantity).toFixed(2));

                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]);
            }


            $("#kt_body").addClass("aside-minimize");
            //Ajax Pagination Data
            $(document).on('click', '.pagination a', function (event) {
                event.preventDefault();
                var page = $(this).attr('href').split('page=')[1];
                $('#hidden_page').val(page);
                $('li').removeClass('active');
                $(this).parent().addClass('active');
                load_products(page);
            });

            // customer_list("<?php echo e($sale->customer_id); ?>");
            $('#product_code_name').on('input', function () {
                var warehouse_id = $('#showroom_id option:selected').val();
                var customer_id = $('#customer_id option:selected').val();
                var temp_data = $('#product_code_name').val();
                // if (!warehouse_id) {
                //     $('#product_code_name').val(temp_data.substring(0, temp_data.length - 1));
                //     multiple_notification('error', 'Please select showroom');
                // } else if (!customer_id) {
                //     $('#product_code_name').val(temp_data.substring(0, temp_data.length - 1));
                //     multiple_notification('error', 'Please select customer');
                // }
            });


            $('#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('sale/product-autocomplete-search')); ?>",
                        type: 'post',
                        dataType: "json",
                        data: {
                            _token: _token,
                            search: request.term,
                            warehouse_id: $('#showroom_id option:selected').val()
                        },
                        success: function (data) {
                            response(data);
                        }
                    });
                },
                // minLength: 3,
                response: function (event, ui) {
                    console.log(ui);
                    if (ui.content.length == 1) {
                        let code = ui.content[0].code;
                        let qty = ui.content[0].product_qty;
                        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");

                        if (qty == 0) {
                            multiple_notification('error', 'No stock Available');
                            return;
                        }


                        product_barcode_search(productId, hasVariant, code, variant_id, variation);
                        multiple_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);
            };

            //Edit Product
            $(document).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)) {
                    multiple_notification('error', 'Invalid discount input');
                    return;
                }

                if (edit_qty < 1) {
                    $('#edit_qty').val(1);
                    edit_qty = 1;
                    multiple_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();

                let p_qty = $('#product_table tbody tr:nth-child(' + (rowindex + 1) + ') .qty').data('stock');

                if ($(this).val() > p_qty) {
                    $('#product_table tbody tr:nth-child(' + (rowindex + 1) + ') .qty').val(p_qty);
                    multiple_notification('error', 'Qunatity can\'t be greater than ' + p_qty);
                }

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

            // $('.qty').trigger('keyup');


            $('#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);
                    multiple_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();
                if (rowindex == 0) {
                    $('#change_amount,#paid_amount,#net_total,#grand_total,#shipping_cost,#adjustment,#order_discount,#order_tax')
                        .val((0).toFixed(2));
                    $('#order_tax_rate').val(0);
                    $('#order_tax_rate.selectpicker').selectpicker('refresh');
                    $('#order_discount_per,#adjustment_per').prop('checked', false);
                }
                product_price.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();
                multiple_notification('success', 'Successfully Removed From Cart');

            });

            $('input[name="order_discount"]').on('input', function () {
                if (parseFloat($(this).val()) > parseFloat($('input[name="grand_total"]').val())) {
                    multiple_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="use_point"]').on('input', function () {
                calculateGrandTotal();
            });
            $('input[name="adjustment"]').on('input', function () {
                calculateGrandTotal();
            });
            $('input[name="adjustment_per"]').on('input', function () {
                calculateGrandTotal();
            });
            $('input[name="order_discount_per"]').on('input', function () {

                //var order_discount_per = parseFloat($(this).val());

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

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

                if (paid_amount > payable_amount) {
                    $('#change_amount').val((paid_amount - payable_amount).toFixed(2));
                    //     $('#paid_amount').val(payable_amount.toFixed(2));
                    //     multiple_notification('error', 'Paid amount cannot be less than payable amount');
                } else {
                    $('#change_amount').val((0).toFixed(2));
                }


            });
            //Customer Form Data Save Code
            $(document).on('click', '#save-btn', function () {
                let form = document.getElementById('store_or_update_form');
                let formData = new FormData(form);
                $.ajax({
                    url: "<?php echo e(route('customer.store.or.update')); ?>",
                    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) {
                        $('#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 {
                            multiple_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);
                    }
                });
            });

            $('#payment_method').on('change', function () {
                if ($(this).val() != 1) {
                    $('.reference_no').removeClass('d-none');
                } else {
                    $('.reference_no').addClass('d-none');
                }
            });

        });

        function product_search_click(el) {
            var warehouse_id = $('#warehouse_id option:selected').val();
            var customer_id = $('#customer_id option:selected').val();
            // if (!warehouse_id) {
            //     multiple_notification('error', 'Please select showroom');
            // } else if (!customer_id) {
            //     multiple_notification('error', 'Please select customer');
            // } else {
            //     product_search(el);
            // }
            product_search(el);
        }

        <?php if(!$sale->products->isEmpty()): ?>
            count = "<?php echo e(count($sale->products) + 1); ?>";
        <?php endif; ?>
        function product_search(el) {
            let product_id = $(el).attr('data-product_id');
            let hasVariant = $(el).attr('data-variant');
            let code = $(el).attr('data-product_code');
            let variation = '';
            let variant_id = $(el).attr('data-variant_id');
            let p_qty = $(el).attr('data-product_qty');

            if (p_qty == 0 || p_qty == '') {
                multiple_notification('error', 'No stock Available');
                return;
            }


            if (hasVariant != 0) {
                variation = $(`#cart_${product_id}_variation`).find(':selected').text();
            }
            $.ajax({
                url: "<?php echo e(route('sale.product.search')); ?>",
                type: 'POST',
                beforeSend: function () {
                    $(`#cart_${product_id}_btn`).addClass('spinner spinner-white spinner-right');
                },
                complete: function () {
                    $(`#cart_${product_id}_btn`).removeClass('spinner spinner-white spinner-right');
                },
                data: {
                    code: code,
                    _token: _token,
                    warehouse_id: $('#warehouse_id option:selected').val(),
                    product_id: product_id,
                    hasVariant: hasVariant
                },
                success: function (data) {

                    if (data.qty == 0) {
                        multiple_notification('error', 'No Stock Available');
                        return;
                    }


                    multiple_notification('success', 'Successfully Added To Cart');

                    // 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) {
                        console.log(count);
                        temp_unit_name = data.unit_name.split(',');
                        var newRow = $('<tr>');
                        var cols = '';
                        cols += `<td><span class="edit-product text-primary mb-0" data-toggle="modal"
                        data-target="#editModal" style="cursor:pointer;">` + data.name +
                            `</span> &nbsp; ${variation}<br><b>${data.code}</b><br><b>In Stock: </b> ${data.qty}<input type="hidden" name="products[` +
                            count + `][name]" value="` + data.name + `"></td>`;


                        cols +=
                            `<td style="width: 10%"><input type="text" data-stock="` + data.qty + `"  class="form-control qty text-center" name="products[` +
                            count + `][qty]"
                        id="products_` + count + `_qty" value="1"></td>`;
                        cols +=
                            `<td style="width: 12%"><input type="text" class="form-control text-center net_unit_price" name="products[` +
                            count + `][net_unit_price]" id="products_` + count + `_net_unit_price"></td>`;
                        cols += `<td class="discount text-center"></td>`;
                        cols += `<td class="tax text-center"></td>`;
                        cols += `<td class="sub-total text-center"></td>`;
                        cols +=
                            `<td class="text-center"><i class="fas fa-trash remove-product text-danger" style="cursor:pointer;"></i></td>`;
                        cols += `<input type="hidden" class="product-id" name="products[` + count +
                            `][id]"  value="` + data.id + `">`;
                        cols += `<input type="hidden" class="product-name" name="products[` + count +
                            `][name]" value="` + data.name + `">`;
                        cols += `<input type="hidden" class="product-code" name="products[` + count +
                            `][code]" value="` + data.code + `">`;
                        cols += `<input type="hidden" class="stock-qty" name="products[` + count +
                            `][stock_qty]" value="` + data.qty + `">`;
                        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]">`;

                        //newly added code for variant
                        cols += `<input type="hidden" class="" name="products[` + count +
                            `][variant_id]" value="${variant_id}">`;

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

                        product_price.push(parseFloat(data.price));
                        product_qty.push(data.qty);
                        product_discount.push(data.discount);
                        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('');
                    //     multiple_notification('error', 'This product is out of stock!');
                    // }
                }
            });
        }


        function product_barcode_search(product_id, hasVariant, code, variant_id, variation) {
            $.ajax({
                url: "<?php echo e(route('sale.product.search')); ?>",
                type: 'POST',
                data: {
                    code: code,
                    _token: _token,
                    warehouse_id: $('#warehouse_id option:selected').val(),
                    product_id: product_id,
                    hasVariant: hasVariant
                },
                success: function (data) {
                    // if (data.qty > 0) {
                    var flag = 1;
                    $('.product-code').each(function (i) {

                        if ($(this).val() == data.code) {
                            rowindex = i;
                            var qty = parseFloat($('#product_table tbody tr:nth-child(' + (
                                rowindex + 1) + ') .qty').val()) + 1;
                            $('#product_table tbody tr:nth-child(' + (rowindex + 1) + ') .qty').val(
                                qty);
                            checkQuantity(String(qty), true, input = 2);
                            flag = 0;
                        }
                    });
                    $('#product_code_name').val('');
                    if (flag) {
                        temp_unit_name = data.unit_name.split(',');
                        var newRow = $('<tr>');
                        var cols = '';
                        cols += `<td><span class="edit-product text-primary mb-0" data-toggle="modal"
                        data-target="#editModal" style="cursor:pointer;">` + data.name +
                            `</span> &nbsp; ${variation}<br><b>${data.code}</b><br><b>In Stock: </b> ${data.qty}<input type="hidden" name="products[` +
                            count + `][name]" value="` + data.name + `"></td>`;


                        cols +=
                            `<td style="width: 10%"><input type="text" data-stock="` + data.qty + `"  class="form-control qty text-center" name="products[` +
                            count + `][qty]"
                        id="products_` + count + `_qty" value="1"></td>`;
                        cols +=
                            `<td style="width: 10%"><input type="text" class="form-control text-center net_unit_price" name="products[` +
                            count + `][net_unit_price]" id="products_` + count + `_net_unit_price"></td>`;
                        cols += `<td class="discount text-center"></td>`;
                        cols += `<td class="tax text-center"></td>`;
                        cols += `<td class="sub-total text-center"></td>`;
                        cols +=
                            `<td class="text-center"><i class="fas fa-trash remove-product text-danger" style="cursor:pointer;"></i></td>`;
                        cols += `<input type="hidden" class="product-id" name="products[` + count +
                            `][id]"  value="` + data.id + `">`;
                        cols += `<input type="hidden" class="product-name" name="products[` + count +
                            `][name]" value="` + data.name + `">`;
                        cols += `<input type="hidden" class="product-code" name="products[` + count +
                            `][code]" value="` + data.code + `">`;
                        cols += `<input type="hidden" class="stock-qty" name="products[` + count +
                            `][stock_qty]" value="` + data.qty + `">`;
                        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]">`;

                        //newly added code for variant
                        cols += `<input type="hidden" class="" name="products[` + count +
                            `][variant_id]" value="${variant_id}">`;

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

                        product_price.push(parseFloat(data.price));
                        product_qty.push(data.qty);
                        product_discount.push(data.discount);
                        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('');
                    //     multiple_notification('error', 'This product is out of stock!');
                    // }
                }
            });
        }

        function checkQuantity(sale_qty, flag, input = 2) {
            var operator = unit_operator[rowindex].split(',');
            var operation_value = unit_operation_value[rowindex].split(',');

            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('.product-name')
                .val();
            // var row_product_code = $('#product_table tbody tr:nth-child(' + (rowindex + 1) + ')').find('td:nth-child(2)').text();
            $('#model-title').text(row_product_name);

            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(4)').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 net_unit_price = ((sub_total_unit * tax_rate[rowindex]) / 100);
            //     console.log(`new net_unit_price ${net_unit_price}`);
            //     var tax = net_unit_price * quantity;
            //     var sub_total = (sub_total_unit + tax) * (quantity);
            //
            // }

            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 net_unit_price = ((sub_total_unit * tax_rate[rowindex]) / 100);
                // console.log(`new net_unit_price ${net_unit_price}`);
                var tax = net_unit_price * quantity;
                var sub_total = (sub_total_unit + tax) * (quantity);

            }

            // $('#product_table tbody tr:nth-child(' + (rowindex + 1) + ')').find('td:nth-child(4)').text(net_unit_price.toFixed(2));

            if (input == 2) {
                $('#product_table tbody tr:nth-child(' + (rowindex + 1) + ')').find('.net_unit_price').val(row_product_price
                    .toFixed(2));
            }

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

            calculateTotal();
        }

        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 total_discount = 0.00;
            var total_adjustment = 0.00;
            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 order_discount_per = $('#order_discount_per').is(":checked");
            var adjustment = parseFloat($('#adjustment').val());
            var adjustment_per = $('#adjustment_per').is(":checked");

            var total_point = parseFloat($('#point').val()) || 0;
            var t_point = parseFloat($('#t_point').val()) || 0;
            var use_point = parseFloat($('#use_point').val()) || 0;
            var point_money = parseFloat($('#point_money').val()) || 0;

            if (!order_discount) {
                order_discount = 0.00;
            }
            if (!shipping_cost) {
                shipping_cost = 0.00;
            }
            if (!order_discount_per) {
                total_discount = order_discount;
                $('#order_discount_per').val(1);
            } else {
                total_discount = (subtotal * order_discount) / 100;
                $('#order_discount_per').val(2);
            }
            if (!adjustment) {
                adjustment = 0.00;
            }
            if (!adjustment_per) {
                total_adjustment = adjustment;
                $('#adjustment_per').val(1);
            } else {
                total_adjustment = -(adjustment);
                $('#adjustment_per').val(2);
            }

            //console.log(total_adjustment+' '+subtotal);
            var total_p = t_point - use_point;
            var total_p_money = use_point * point_money;
            item = ++item + '(' + total_qty + ')';
            order_tax = (subtotal - total_discount) * (order_tax / 100);
            var net_total = (subtotal + order_tax + shipping_cost - total_p_money) - total_discount;

            let delivery_charge = parseFloat($('#delivery_charge').val());
            var grand_total = net_total + total_adjustment + delivery_charge;

            $('#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(total_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));

            $('input[name="point"]').val(total_p.toFixed(2));
            if (total_point < use_point) {
                $('#use_point').val(0);
                $('#point').val(t_point);
                multiple_notification('error', '<?php echo e(__('Use Point cannot be bigger than Available Point')); ?>');
            }
            // alert(toral_p);

            // $('input[name="paid_amount"]').val($('input[name="net_total"]').val());
            var paid_amount = $('#paid_amount').val() ? parseFloat($('#paid_amount').val()) : 0;

            let due_ongoing = (grand_total - paid_amount).toFixed(2);
            if (paid_amount < grand_total) {
                $('input[name="due_amount"]').val(due_ongoing);

                // $('#change_amount').val((paid_amount - net_total).toFixed(2));
            } else {
                $('input[name="due_amount"]').val(due_ongoing);

                // $('#change_amount').val((0).toFixed(2));
            }
        }

        function customer_list(customer_id = '') {
            $.ajax({
                url: "<?php echo e(route('customer.list')); ?>",
                type: "POST",
                data: {
                    warehouse_id: document.getElementById('warehouse_id').value,
                    _token: _token
                },
                success: function (data) {
                    console.log(data);
                    $('#sale_store_form #customer_id').empty().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);
                }
            });
        }

        //now debugging
        // account_list("<?php echo e($sale->payment_method); ?>", "<?php echo e($sale->account_id); ?>");


        function account_list(payment_method, idx, account_idx = null) {

            $.ajax({
                url: "<?php echo e(route('account.list')); ?>",
                type: "POST",
                data: {
                    payment_method: payment_method,
                    account_id: account_idx,
                    _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);
                }
            });
        }


        function load_products(page = 1) {
            var brand_id = $('#brand_id option:selected').val();
            var category_id = $('#category_id option:selected').val();
            var sku_name = $('#sku_name').val();

            $.ajax({
                url: "<?php echo e(url('pos-product-list')); ?>",
                type: "POST",
                data: {
                    page: page,
                    brand_id: brand_id,
                    category_id: category_id,
                    sku_name: sku_name,
                    _token: _token
                },
                beforeSend: function () {
                    $('.product-table tbody').html('');
                    $('#product_loading').removeClass('d-none');
                },
                complete: function () {
                    $('#product_loading').addClass('d-none');
                },
                success: function (data) {
                    $('.product-table tbody').html(data);
                    $('.product-table tbody .selectpicker').selectpicker('refresh');
                },
                error: function (xhr, ajaxOptions, 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) {
                multiple_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('ecommerce_sale.pos.update')); ?>";
                $.ajax({
                    url: url,
                    type: "POST",
                    data: formData,
                    dataType: "JSON",
                    contentType: false,
                    processData: false,
                    cache: false,
                    beforeSend: function () {
                        $('#pos-save-btn').addClass('spinner spinner-white spinner-right');
                    },
                    complete: function () {
                        $('#pos-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 {
                            multiple_notification(data.status, data.message);
                            if (data.status == 'success') {
                                window.location.replace("<?php echo e(url('ecommerce_sale/view-invoice')); ?>/" + data.id);
                            }
                        }

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

        function hold_data() {

        }

        $('#customer_id').on('change', function () {
            let customerId = $(this).find('option:selected').val();

            $.get('<?php echo e(url('customer-point')); ?>/' + customerId, function (data) {
                $('#point').val(parseFloat(data).toFixed(2));
            });
            $.get('<?php echo e(url('customer-point')); ?>/' + customerId, function (data) {
                $('#t_point').val(parseFloat(data).toFixed(2));
            });
        });

        function setProductPriceStock(productId, idx) {
            let variantId = $(idx).val();

            let data = {
                'qty': $(idx).find(':selected').data('stock'),
                'sale_price': $(idx).find(':selected').data('price'),
                'product_code': $(idx).find(':selected').data('product_code')
            }

            if (variantId != '') {
                $(`#cart_${productId}_stock`).val(data.qty);
                $(`#cart_${productId}_price`).val(data.sale_price);
                $('#cart_' + productId + '_btn').attr('data-product_code', data.product_code);
                $('#cart_' + productId + '_btn').attr('data-product_qty', data.qty);
            } else {
                multiple_notification('error', 'No Variant selected');
            }
        }


        let table_row = 0;

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


        function addTableRow(tableId, idx) {

            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"
    name="payment[${table_row}][payment_method]"
     id="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_amount">Amount</label>
   <input type="number" class="fcs form-control payment_amounts"
           oninput="calculatePaymentAmount(this.value)"
          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');
        }


        $('.payment_amounts').on('input', function () {
            var value = $(this).val();
            if ((value !== '') && (value.indexOf('.') === -1)) {
                let payable_amount = parseFloat($('input[name="grand_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) {
                    multiple_notification('error', 'The Payment Can not grater than payable amount');
                }
            }
        });

        function calculatePaymentAmount(value) {
            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="grand_total"]').val());
                let dues = (payable_amount - totals).toFixed(2);

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

        function setDeliveryCharge(input_value, price) {

            $('#delivery_charge').val(price);
            calculateTotal();
        }
    </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/ecommerce-pos/posedit.blade.php ENDPATH**/ ?>