@extends('layouts.app')
@section('title', __('lang_v1.omni_channel_services'))
@section('css')
<style>
    .text-center {
        text-align: center !important;
    }

    .btn-amazon {
        display: inline-block !important;
        font-weight: 400 !important;
        text-align: center !important;
        vertical-align: middle !important;
        user-select: none !important;
        border: 1px solid transparent !important;
        padding: 0.375rem 0.75rem !important;
        font-size: 1rem !important;
        line-height: 1.5 !important;
        border-radius: 0.375rem !important;
        transition: all 0.15s ease-in-out !important;
    }

    .btn-primary-amazon {
        color: #fff !important;
        background-color: #007bff !important;
        /* Default blue color */
        border-color: #007bff !important;
    }

    .btn-primary-amazon:hover {
        background-color: #0056b3 !important;
        border-color: #004085 !important;
    }

    .btn-lg-amazon {
        padding: 0.5rem 1rem !important;
        font-size: 1.25rem !important;
        border-radius: 0.3rem !important;
    }

    .table-container {
        width: 100%;
        max-height: 600px;
        /* Adjust as needed */
        overflow-y: auto;
        /* overflow-x: auto; */
        border: 1px solid #ddd;
    }

    .fixed-table {
        width: 100%;
        border-collapse: collapse;
    }

    .fixed-table th {
        position: sticky;
        top: 0;
        background: #fff;
        z-index: 2;
        text-align: left;
        border-bottom: 2px solid #ddd;
        padding: 8px;
    }

    .fixed-table td {
        border-bottom: 1px solid #ddd;
        padding: 8px;
    }

    .dropdown-menu {
        background-color: #add8e6 !important;
    }

    @keyframes progress-bar-stripes {
        0% {
            background-position: 1rem 0;
        }
        100% {
            background-position: 0 0;
        }
    }

    .progress-bar-animated {
        animation: progress-bar-stripes 1s linear infinite;
    }

    .progress {
        background-color: #89ddf1 !important;
    }
</style>
@endsection
@section('content')

<!-- Content Header (Page header) -->
<section class="content-header">
    <h1>@lang('lang_v1.omni_channel_services')</h1>
    <br>
    {{-- @include('layouts.partials.search_settings') --}}
    <h1 id="progressBarTitle" style="display: none"></h1>
    <div class="progress" id="progressBarHead" style="display: none">
        <div id="progressBar" 
            class="progress-bar progress-bar-striped progress-bar-animated" 
            role="progressbar" 
            style="width: 0%; transition: width 0.6s ease;" 
            aria-valuenow="0" 
            aria-valuemin="0" 
            aria-valuemax="100">
            0%
        </div>
    </div>
</section>

<!-- Main content -->
<section class="content">
    {!! Form::open(['url' => action([\App\Http\Controllers\OmniChannelServicesController::class, 'postMarketplaceOmni']), 'method' => 'post', 'id' => 'omni_edit_form',
    'files' => true ]) !!}
    <h3 style="margin: 0">@lang('lang_v1.marketplaces')</h3>
    <div class="row">
        <div class="col-xs-12">
            <!--  <pos-tab-container> -->
            <div class="col-xs-12 pos-tab-container">
                <div class="col-lg-2 col-md-2 col-sm-2 col-xs-2 pos-tab-menu">
                    <div class="list-group">
                        <!-- <a href="#" class="list-group-item text-center" onclick="table_hide('etsy')">@lang('lang_v1.etsy')</a> -->
                        <!-- <a href="#" class="list-group-item text-center active" onclick="table_hide('walmart')">@lang('lang_v1.walmart')</a> -->
                        <a href="#" class="list-group-item text-center active" onclick="table_hide('amazon')">@lang('lang_v1.amazon')</a>
                        {{-- <a href="#" class="list-group-item text-center">@lang('lang_v1.ebay')</a> --}}
                    </div>
                </div>
                <div class="col-lg-10 col-md-10 col-sm-10 col-xs-10 pos-tab">
                    <!-- tab 1 start -->
                    <!-- @include('business.partials.settings_etsy') -->
                    <!-- tab 1 end -->
                    <!-- tab 2 start -->
                    <!-- @include('business.partials.settings_walmart') -->
                    <!-- tab 2 end -->
                    <!-- tab 3 start -->
                    @include('business.partials.settings_amazon')
                    <div id="collapseFilterAmazon" class="panel-collapse collapse " aria-expanded="true">
                        <div class="box-body">
                            <div class="col-sm-12">
                                <div class="form-group">
                                    {!! Form::label('checkmarks_amazon', __('business.sync_items') . ':') !!}
                                    <div class="checkbox row">
                                        <label for="">
                                            @if($reference_checkmarks)
                                            @foreach ($reference_checkmarks as $k => $item)
                                            <div class="col-sm-6 mr-2">
                                                @if ($amazon_checkbox)
                                                @php
                                                $checked = '';
                                                @endphp
                                                @foreach ($amazon_checkbox as $iw)
                                                @if (in_array($item->reference_column, (array)$iw))
                                                @php
                                                $checked = 'checked';
                                                @endphp
                                                @endif
                                                @endforeach
                                                <input type="checkbox" name="checkmarks_amazon[]" class="input-checkbox" value="{{ $item->reference_column }}" id="checkmarks_amazon{{$k+1}}" {{$checked}}>{{$item->name}}
                                                @else
                                                <input type="checkbox" name="checkmarks_amazon[]" class="input-checkbox" value="{{ $item->reference_column }}" id="checkmarks_amazon{{$k+1}}">{{$item->name}}
                                                @endif
                                            </div>
                                            @endforeach
                                            @endif
                                        </label>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <div class="box box-primary" id="accordion">
                                        <div class="box-header with-border">
                                            <h3 class="box-title">
                                                <input type="radio" id="option_marketplace_amazon_1" name="option_marketplace_amazon_1" value="1" onclick="getOptionAmazon(1, this.value, 1)"
                                                    @if ($marketplace_option_amazon)
                                                    @if(property_exists($marketplace_option_amazon, 'first_option' ))
                                                    @if (count($marketplace_option_amazon->first_option) > 0)
                                                checked
                                                @endif
                                                @endif
                                                @endif>
                                                <label for="">Yes</label>
                                                <input type="radio" id="option_marketplace_amazon_1" name="option_marketplace_amazon_1" value="0" onclick="getOptionAmazon(1, this.value, 1)"
                                                    @if ($marketplace_option_amazon)
                                                    @if(property_exists($marketplace_option_amazon, 'first_option' ))
                                                    @if (count($marketplace_option_amazon->first_option) == 0)
                                                checked
                                                @endif
                                                @else
                                                checked
                                                @endif
                                                @else
                                                checked
                                                @endif>
                                                <label for="">No</label>
                                                - @lang('messages.marketplace_option', ['marketplace' => 'Amazon'])
                                            </h3>
                                        </div>
                                        <div id="option_marketplace_collapse_amazon_1" class="panel-collapse collapse"
                                            @if ($marketplace_option_amazon)
                                            @if(property_exists($marketplace_option_amazon, 'first_option' ))
                                            @if (count($marketplace_option_amazon->first_option) > 0)
                                            style="display: block;"
                                            @else
                                            style="display: none;"
                                            @endif
                                            @endif
                                            @endif aria-expanded="true">
                                            <div class="box-body">
                                                @php
                                                $checked11 = null;
                                                $checked12 = null;
                                                $checked13 = null;
                                                $checked14 = null;
                                                @endphp
                                                @if ($marketplace_option_amazon)
                                                @if (property_exists($marketplace_option_amazon, 'first_option'))
                                                @foreach ($marketplace_option_amazon->first_option as $item)
                                                @if ($item == 11)
                                                @php
                                                $checked11 = 'checked';
                                                @endphp
                                                @endif
                                                @if ($item == 12)
                                                @php
                                                $checked12 = 'checked';
                                                @endphp
                                                @endif
                                                @if ($item == 13)
                                                @php
                                                $checked13 = 'checked';
                                                @endphp
                                                @endif
                                                @if ($item == 14)
                                                @php
                                                $checked14 = 'checked';
                                                @endphp
                                                @endif
                                                @endforeach
                                                @endif
                                                @endif
                                                <input type="checkbox" name="value_marketplace_amazon[first_option][]" class="input-checkbox" value="11" id="checkmarks_marketplace_amazon_11" {{$checked11}}>&nbsp;Create a product on my other marketplaces when I create a product on Amazon
                                                <br>
                                                <input type="checkbox" name="value_marketplace_amazon[first_option][]" class="input-checkbox" value="12" id="checkmarks_marketplace_amazon_12" {{$checked12}}>&nbsp;Create a product on Amazon if I create a product on my any other marketplace
                                                <br>
                                                <input type="checkbox" name="value_marketplace_amazon[first_option][]" class="input-checkbox" value="13" id="checkmarks_marketplace_amazon_13" {{$checked13}}>&nbsp;Update Amazon products if there is a change on my any marketplace product
                                                <br>
                                                <input type="checkbox" name="value_marketplace_amazon[first_option][]" class="input-checkbox" value="14" id="checkmarks_marketplace_amazon_14" {{$checked14}}>&nbsp;Update other market place products if there is a change on Amazon product
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <div class="box box-primary" id="accordion">
                                        <div class="box-header with-border">
                                            <h3 class="box-title">
                                                <input type="radio" id="option_marketplace_amazon_2" name="option_marketplace_amazon_2" value="1" onclick="getOptionAmazon(2, this.value, 1)"
                                                    @if ($marketplace_option_amazon)
                                                    @if(property_exists($marketplace_option_amazon, 'second_option' ))
                                                    @if (count($marketplace_option_amazon->second_option) > 0)
                                                checked
                                                @endif
                                                @endif
                                                @endif>
                                                <label for="">Yes</label>
                                                <input type="radio" id="option_marketplace_amazon_2" name="option_marketplace_amazon_2" value="0" onclick="getOptionAmazon(2, this.value, 2)"
                                                    @if ($marketplace_option_amazon)
                                                    @if(property_exists($marketplace_option_amazon, 'second_option' ))
                                                    @if (count($marketplace_option_amazon->second_option) == 0)
                                                checked
                                                @endif
                                                @else
                                                checked
                                                @endif
                                                @else
                                                checked
                                                @endif>
                                                <label for="">No</label>
                                                - @lang('messages.marketplace_option2', ['marketplace' => 'Amazon'])
                                            </h3>
                                        </div>
                                        <div id="option_marketplace_collapse_amazon_2" class="panel-collapse collapse"
                                            @if ($marketplace_option_amazon)
                                            @if(property_exists($marketplace_option_amazon, 'second_option' ))
                                            @if (count($marketplace_option_amazon->second_option) > 0)
                                            style="display: block;"
                                            @else
                                            style="display: none;"
                                            @endif
                                            @endif
                                            @endif
                                            aria-expanded="true">
                                            <div class="box-body">
                                                @php
                                                $checked21 = null;
                                                $checked22 = null;
                                                $checked23 = null;
                                                $checked24 = null;
                                                @endphp
                                                @if ($marketplace_option_amazon)
                                                @if (property_exists($marketplace_option_amazon, 'second_option'))
                                                @foreach ($marketplace_option_amazon->second_option as $item)
                                                @if ($item == 21)
                                                @php
                                                $checked21 = 'checked';
                                                @endphp
                                                @endif
                                                @if ($item == 22)
                                                @php
                                                $checked22 = 'checked';
                                                @endphp
                                                @endif
                                                @if ($item == 23)
                                                @php
                                                $checked23 = 'checked';
                                                @endphp
                                                @endif
                                                @if ($item == 24)
                                                @php
                                                $checked24 = 'checked';
                                                @endphp
                                                @endif
                                                @endforeach
                                                @endif
                                                @endif
                                                <input type="checkbox" name="value_marketplace_amazon[second_option][]" class="input-checkbox" value="21" id="checkmarks_marketplace_amazon_21" {{$checked21}}>&nbsp;Create a product on my active ecommerce store when i create a product on Amazon
                                                <br>
                                                <input type="checkbox" name="value_marketplace_amazon[second_option][]" class="input-checkbox" value="22" id="checkmarks_marketplace_amazon_22" {{$checked22}} disabled>&nbsp;Create a product on Amazon if I create a product on my active ecommerce store
                                                <br>
                                                <input type="checkbox" name="value_marketplace_amazon[second_option][]" class="input-checkbox" value="23" id="checkmarks_marketplace_amazon_23" {{$checked23}} disabled>&nbsp;Update Amazon products if there is a change on active ecommerce side
                                                <br>
                                                <input type="checkbox" name="value_marketplace_amazon[second_option][]" class="input-checkbox" value="24" id="checkmarks_marketplace_amazon_24" {{$checked24}}>&nbsp;Update active ecommerce products if there is a change on Amazon side
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="form-group">
                                    {{-- <div class="col-sm-6">
                                        <div class="col-sm-8">
                                            <div class="form-group">
                                            {!! Form::label('name', __( 'product.file_to_import' ) . ':') !!}
                                            {!! Form::file('amazon_file', ['accept'=> '.xls, .xlsx, .csv', 'required' => 'required']); !!}
                                            </div>
                                        </div> --}}
                                    {{-- <div class="col-sm-4">
                                    <br>
                                        <button type="button" class="btn btn-primary" id="btn_sumbit_import_product" onclick="importFile(event)">@lang('messages.proses_queue')</button>
                                    </div> --}}
                                </div>
                            </div>
                            @if ($amazon_sellers)
                            <button class="btn btn-danger pull-right" type="button" onclick="startSync()">@lang('business.start_sync')</button>
                            <button class="btn btn-danger pull-right" type="button" onclick="syncTest()">@lang('business.start_test')</button>
                            <button class="btn btn-danger pull-right" type="submit">@lang('business.update_settings')</button>
                            <button type="button" class="btn btn-primary btn-flat pull-right btn-sync hide" onclick="sync_amazon()" id="amazon_test_btn">@lang('lang_v1.sync_amazon_data')</button>
                            @endif
                        </div>
                    </div>
                    <!-- tab 3 end -->
                    <!-- tab 4 start -->
                    {{-- @include('business.partials.settings_ebay') --}}
                    <!-- tab 4 end -->
                </div>
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-sm-12">
            <!-- <button type="button" class="btn btn-primary btn-flat pull-right btn-sync hide" id="etsy_test_btn" onclick="sync_etsy()">@lang('lang_v1.sync_etsy_data')</button> -->
            <!-- <button type="button" class="btn btn-primary btn-flat pull-right btn-sync hide" id="walmart_test_btn">@lang('lang_v1.sync_walmart_data')</button> -->

        </div>
    </div>
    <div class="row" style="margin-top: 20px;">



        <!-- <div class="col-sm-12 table_hide etsy_table">
            <table class="table table-bordered table-striped hide-footer" id="etsy_table" style="width: 100%;">
                <thead>
                    <tr>
                        <th><input type="checkbox" id="select-all-row" data-table-id="etsy_table"></th>
                        <th>&nbsp;</th>
                        <th>@lang('messages.action')</th>
                        <th>@lang('sale.product')</th>
                        <th>@lang('business.business_location') @show_tooltip(__('lang_v1.product_business_location_tooltip'))</th>
                        @can('access_default_selling_price')
                        <th>@lang('lang_v1.selling_price')</th>
                        @endcan
                        <th>@lang('report.total_stock')</th>
                        <th>@lang('product.category')</th>
                        <th>@lang('product.brand')</th>
                        <th>@lang('product.sku')</th>
                    </tr>
                </thead>
                <tfoot>
                    <tr>
                        <td colspan="10">
                            <div style="display: flex; width: 100%;">
                                @can('product.delete')
                                <form></form>
                                {!! Form::open(['url' => action([\App\Http\Controllers\ProductController::class, 'massDestroy']), 'method' => 'post', 'id' => 'mass_delete_form_walmart' ]); !!}
                                {!! Form::hidden('selected_rows', null, ['id' => 'selected_rows_walmart']); !!}
                                {!! Form::submit(__('lang_v1.delete_selected'), array('class' => 'btn btn-xs btn-danger', 'id' => 'delete-selected-walmart')); !!}
                                {!! Form::close(); !!} @show_tooltip(__('lang_v1.deactive_product_tooltip'))
                                @endcan


                                @can('product.update')

                                @if(config('constants.enable_product_bulk_edit'))
                                &nbsp;
                                {!! Form::open(['url' => action([\App\Http\Controllers\ProductController::class, 'bulkEdit']), 'method' => 'post', 'id' => 'bulk_edit_form' ]) !!}
                                {!! Form::hidden('selected_products', null, ['id' => 'selected_products_for_edit']); !!}
                                <button type="submit" class="btn btn-xs btn-primary" id="edit-selected"> <i class="fa fa-edit"></i>{{__('lang_v1.bulk_edit')}}</button>
                                {!! Form::close() !!}
                                @endif
                                &nbsp;
                                <button type="button" class="btn btn-xs btn-success update_product_location" data-type="add">@lang('lang_v1.add_to_location')</button>
                                &nbsp;
                                <button type="button" class="btn btn-xs bg-navy update_product_location" data-type="remove">@lang('lang_v1.remove_from_location')</button>
                                @endcan

                                &nbsp;
                                {!! Form::open(['url' => action([\App\Http\Controllers\ProductController::class, 'massDeactivate']), 'method' => 'post', 'id' => 'mass_deactivate_form' ]); !!}
                                {!! Form::hidden('selected_products', null, ['id' => 'selected_products']); !!}
                                {!! Form::submit(__('lang_v1.deactivate_selected'), array('class' => 'btn btn-xs btn-warning', 'id' => 'deactivate-selected')); !!}
                                {!! Form::close(); !!} @show_tooltip(__('lang_v1.deactive_product_tooltip'))
                            </div>
                        </td>
                    </tr>
                </tfoot>
            </table>
        </div> -->





        <!-- <div class="col-sm-12 table_hide walmart_table">
            <table class="table table-bordered table-striped hide-footer" id="walmart_table" style="width: 100%;">
                <thead>
                    <tr>
                        <th><input type="checkbox" id="select-all-row" data-table-id="walmart_table"></th>
                        <th>&nbsp;</th>
                        <th>@lang('messages.action')</th>
                        <th>@lang('sale.product')</th>
                        <th>@lang('business.business_location') @show_tooltip(__('lang_v1.product_business_location_tooltip'))</th>
                        @can('access_default_selling_price')
                        <th>@lang('lang_v1.selling_price')</th>
                        @endcan
                        <th>@lang('report.total_stock')</th>
                        <th>@lang('product.category')</th>
                        <th>@lang('product.brand')</th>
                        <th>@lang('product.sku')</th>
                    </tr>
                </thead>
                <tfoot>
                    <tr>
                        <td colspan="10">
                            <div style="display: flex; width: 100%;">
                                @can('product.delete')
                                <form></form>
                                {!! Form::open(['url' => action([\App\Http\Controllers\ProductController::class, 'massDestroy']), 'method' => 'post', 'id' => 'mass_delete_form_walmart' ]); !!}
                                {!! Form::hidden('selected_rows', null, ['id' => 'selected_rows_walmart']); !!}
                                {!! Form::submit(__('lang_v1.delete_selected'), array('class' => 'btn btn-xs btn-danger', 'id' => 'delete-selected-walmart')); !!}
                                {!! Form::close(); !!} @show_tooltip(__('lang_v1.deactive_product_tooltip'))
                                @endcan


                                @can('product.update')

                                @if(config('constants.enable_product_bulk_edit'))
                                &nbsp;
                                {!! Form::open(['url' => action([\App\Http\Controllers\ProductController::class, 'bulkEdit']), 'method' => 'post', 'id' => 'bulk_edit_form' ]) !!}
                                {!! Form::hidden('selected_products', null, ['id' => 'selected_products_for_edit']); !!}
                                <button type="submit" class="btn btn-xs btn-primary" id="edit-selected"> <i class="fa fa-edit"></i>{{__('lang_v1.bulk_edit')}}</button>
                                {!! Form::close() !!}
                                @endif
                                &nbsp;
                                <button type="button" class="btn btn-xs btn-success update_product_location" data-type="add">@lang('lang_v1.add_to_location')</button>
                                &nbsp;
                                <button type="button" class="btn btn-xs bg-navy update_product_location" data-type="remove">@lang('lang_v1.remove_from_location')</button>
                                @endcan

                                &nbsp;
                                {!! Form::open(['url' => action([\App\Http\Controllers\ProductController::class, 'massDeactivate']), 'method' => 'post', 'id' => 'mass_deactivate_form' ]); !!}
                                {!! Form::hidden('selected_products', null, ['id' => 'selected_products']); !!}
                                {!! Form::submit(__('lang_v1.deactivate_selected'), array('class' => 'btn btn-xs btn-warning', 'id' => 'deactivate-selected')); !!}
                                {!! Form::close(); !!} @show_tooltip(__('lang_v1.deactive_product_tooltip'))
                            </div>
                        </td>
                    </tr>
                </tfoot>
            </table>
        </div> -->
        <div class="col-sm-12 amazon_table">
            <input type="hidden" id="amazon_sellers" value="{{ json_encode($amazon_sellers) }}">
            <div style="display: inline-flex; width: 100%;">
                <h3 style="width: 91%">@lang('lang_v1.stores')</h3>                
                @can('product.create')                            
                    <a class="btn btn-primary pull-right" href="{{action([\App\Http\Controllers\AmazonController::class, 'createAmazonProduct'])}}" style="margin-top: 21px;">
                         <i class="fa fa-plus"></i> @lang('product.add_product')</a>
                    <br><br>
                @endcan
            </div>
            @if ($amazon_sellers)
            <div class="nav-tabs-custom">
                <ul class="nav nav-tabs">                    
                    @foreach ($amazon_sellers as $key => $item)
                    <li @if($key == 0) class="active" @endif>
                        <a href="#tab{{ $key+1 }}" data-toggle="tab" aria-expanded="true"><i class="fa fa-cubes" aria-hidden="true"></i> {{ $item->seller_name }}</a>
                    </li>
                    @endforeach
                    <li>
                        <a href="#tabAll" data-toggle="tab" aria-expanded="true"><i class="fa fa-cubes" aria-hidden="true"></i> All</a>
                    </li>
                    {{-- <li class="active">
                        <a href="#tab1" data-toggle="tab" aria-expanded="true"><i class="fa fa-cubes" aria-hidden="true"></i> USED BOOK DEPOT</a>
                    </li>
                    <li>
                        <a href="#tab2" data-toggle="tab" aria-expanded="true"><i class="fa fas fa-arrow-circle-up" aria-hidden="true"></i> The Art of Savings</a>
                    </li>
                    <li>
                        <a href="#tab3" data-toggle="tab" aria-expanded="true"><i class="fa fa-envelope-open" aria-hidden="true"></i> Pharos Bookstore</a>
                    </li> --}}
                </ul>

                <div class="tab-content">                    
                    @foreach ($amazon_sellers as $key => $amazonseller)
                    <div class="tab-pane @if($key == 0) active @endif" id="tab{{ $key+1 }}">
                        {{-- <div class="col-md-12">
                                @component('components.filters', ['title' => __('report.filters')])
                                    <div class="col-md-3">
                                        <div class="form-group">
                                            {!! Form::label('type', __('lang_v1.transaction_type') . ':') !!}
                                            {!! Form::select('type', $transaction_type, null, ['class' => 'filtervh', 'style' => 'width:100%', 'id' => 'transaction_type_qb', 'placeholder' => __('lang_v1.all')]); !!}
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="form-group">
                                            {!! Form::label('date_qb', __('lang_v1.date') . ':') !!}
                                            {!! Form::text('date_qb', null, ['placeholder' => __('lang_v1.select_a_date_range'), 'class' => 'form-control', 'readonly', 'id' => 'date_qb']); !!}
                                        </div>
                                    </div>
                            
                                    <div class="col-md-3">
                                        <div class="form-group">
                                            {!! Form::label('payee_qb', __('lang_v1.payee') . ':') !!}
                                            {!! Form::select('payee_qb', $payee, null, ['class' => 'filtervh', 'style' => 'width:100%', 'id' => 'payee_qb', 'placeholder' => __('lang_v1.all')]); !!}
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="form-group">
                                            {!! Form::label('category_qb', __('lang_v1.category') . ':') !!}
                                            {!! Form::select('category_qb', $category, null, ['class' => 'filtervh', 'style' => 'width:100%', 'id' => 'category_qb', 'placeholder' => __('lang_v1.all')]); !!}
                                        </div>
                                    </div>                                         
                                @endcomponent
                            </div> --}}
                        <div class="row">
                            <div class="col-md-12">
                                <!-- @component('components.filters', ['title' => __('report.filters')]) -->
                                <div class="box @if(!empty($class)) {{$class}} @else box-solid @endif" id="accordion">
                                    <div class="box-header with-border" style="cursor: pointer;">
                                        <h3 class="box-title">
                                            <a data-toggle="collapse" data-parent="#accordion" href="#collapseFilter{{$key+1}}">
                                                @php $title= __('report.filters') . " (click here to open/close filters)"; @endphp
                                                @if(!empty($icon)) {!! $icon !!} @else <i class="fa fa-filter" aria-hidden="true"></i> @endif {{$title ?? ''}}
                                            </a>
                                        </h3>
                                    </div>
                                    @php
                                    //if(isMobile()) { //PALIGU
                                    $closed = true;
                                    //}
                                    @endphp
                                    <div id="collapseFilter{{$key+1}}" class="panel-collapse active collapse @if(empty($closed)) in @endif" aria-expanded="true">
                                        <div class="box-body">
                                            <div class="col-md-3">
                                                <div class="form-group">
                                                    <label for="">@lang('product.category') :</label>
                                                    <select class="filtervh" id="amazon_list_filter_category_table{{ $key+1 }}" style="width:100%" placeholder="@lang('lang_v1.all')">
                                                        <option value="">@lang('lang_v1.all')</option>
                                                        @if(!empty($marketplace_categories))
                                                        @foreach ($marketplace_categories as $item)
                                                        <option value="{{ $item->category }}">{{ $item->category }}</option>
                                                        @endforeach
                                                        @endif
                                                    </select>
                                                </div>
                                            </div>
                                            <div class="col-md-3">
                                                <div class="form-group">
                                                    <label for="">@lang('product.synced') :</label>
                                                    <select class="filtervh" id="amazon_list_filter_sync{{$key+1}}" style="width:100%" placeholder="@lang('lang_v1.all')">
                                                        <option value="">@lang('lang_v1.all')</option>
                                                        <option value="1">YES</option>
                                                        <option value="0">NO</option>
                                                    </select>
                                                </div>
                                            </div>
                                            <div class="col-md-3">
                                                <div class="form-group">
                                                    <label for="">@lang('product.status') :</label>
                                                    <select class="filtervh" id="amazon_list_filter_status{{$key+1}}" style="width:100%" placeholder="@lang('lang_v1.all')">
                                                        <option value="">@lang('lang_v1.all')</option>
                                                        <option value="Active">Active</option>
                                                        <option value="Inactive">Inactive</option>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <!-- @endcomponent -->
                            </div>
                        </div>
                        <table class="table table-bordered table-striped hide-footer ajax_view" id="amazon_table_{{$key+1}}" style="width: 100%;">
                            <thead>
                                <tr>
                                    <th><input type="checkbox" id="select-all-row" data-table-id="amazon_table_{{$key+1}}"></th>
                                    <th style="width: 10px" ;>&nbsp;</th>
                                    <th style="width: 20px" ;>@lang('messages.action')</th>
                                    <th style="width: 20px" ;>@lang('lang_v1.image')</th>
                                    <!-- <th>@lang('lang_v1.amazon_store')</th> -->
                                    <th>@lang('product.asin')</th>
                                    <th>@lang('product.sku')</th>
                                    <th>@lang('product.isbn13')</th>
                                    <th>@lang('product.item_condition')</th>
                                    <th>@lang('sale.product')</th>
                                    <!-- <th>@lang('product.brand')</th> -->
                                    <th>@lang('lang_v1.category')</th>
                                    <!-- <th>@lang('lang_v1.manufacturer')</th> -->
                                    <!-- <th>@lang('lang_v1.product_group')</th> -->
                                    <!-- <th>@lang('product.type')</th> -->
                                    <!-- <th>@lang('lang_v1.material')</th> -->
                                    <th>@lang('product.price')</th>
                                    <th>@lang('barcode.label_price')</th>
                                    <th>@lang('product.qty')</th>
                                    <!-- <th>@lang('product.status')</th> -->
                                    <th>@lang('product.synced')</th>
                                </tr>
                            </thead>
                            <tfoot>
                                <tr>
                                    <td colspan="10">
                                        <button type="button" style="display: none" class="btn btn-xs btn-primary" id="label-queue{{$amazonseller->seller_id}}" onclick="popupPrintLabelsQueue(event, '{{$amazonseller->seller_id}}')"> <i class="fa fa-barcode"></i> {{__('barcode.print_queue_items')}} <span id="total_label_queue{{$amazonseller->seller_id}}"></span></button>
                                        <button type="button" class="btn btn-xs btn-primary" id="label-selected" onclick="printLabelMultiple(event, '{{$amazonseller->seller_id}}')"> <i class="fa fa-barcode"></i> {{__('barcode.print_labels')}}</button>
                                        <button type="button" class="btn btn-xs btn-primary" id="qty-selected" onclick="popupSelectedItems('{{$amazonseller->seller_id}}')"> <i class="fa fa-database"></i> {{__('product.update_products')}}</button>                                        
                                        <!-- <button type="button" class="btn btn-xs btn-primary" id="price-selected" onclick="popupSelectedItems('{{$amazonseller->seller_id}}')"> <i class="fa fa-database"></i> {{__('business.update_listing_price')}}</button>                                         -->
                                    </td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>
                    @endforeach
                    <div class="tab-pane" id="tabAll">
                        {{-- <div class="col-md-12">
                                @component('components.filters', ['title' => __('report.filters')])
                                    <div class="col-md-3">
                                        <div class="form-group">
                                            {!! Form::label('type', __('lang_v1.transaction_type') . ':') !!}
                                            {!! Form::select('type', $transaction_type, null, ['class' => 'filtervh', 'style' => 'width:100%', 'id' => 'transaction_type_qb', 'placeholder' => __('lang_v1.all')]); !!}
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="form-group">
                                            {!! Form::label('date_qb', __('lang_v1.date') . ':') !!}
                                            {!! Form::text('date_qb', null, ['placeholder' => __('lang_v1.select_a_date_range'), 'class' => 'form-control', 'readonly', 'id' => 'date_qb']); !!}
                                        </div>
                                    </div>
                            
                                    <div class="col-md-3">
                                        <div class="form-group">
                                            {!! Form::label('payee_qb', __('lang_v1.payee') . ':') !!}
                                            {!! Form::select('payee_qb', $payee, null, ['class' => 'filtervh', 'style' => 'width:100%', 'id' => 'payee_qb', 'placeholder' => __('lang_v1.all')]); !!}
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="form-group">
                                            {!! Form::label('category_qb', __('lang_v1.category') . ':') !!}
                                            {!! Form::select('category_qb', $category, null, ['class' => 'filtervh', 'style' => 'width:100%', 'id' => 'category_qb', 'placeholder' => __('lang_v1.all')]); !!}
                                        </div>
                                    </div>                                         
                                @endcomponent
                            </div> --}}
                        <div class="row">
                            <div class="col-md-12">
                                <!-- @component('components.filters', ['title' => __('report.filters')]) -->
                                <div class="box @if(!empty($class)) {{$class}} @else box-solid @endif" id="accordion">
                                    <div class="box-header with-border" style="cursor: pointer;">
                                        <h3 class="box-title">
                                            <a data-toggle="collapse" data-parent="#accordion" href="#collapseFilter{{$key+1}}">
                                                @php $title= __('report.filters') . " (click here to open/close filters)"; @endphp
                                                @if(!empty($icon)) {!! $icon !!} @else <i class="fa fa-filter" aria-hidden="true"></i> @endif {{$title ?? ''}}
                                            </a>
                                        </h3>
                                    </div>
                                    @php
                                    //if(isMobile()) { //PALIGU
                                    $closed = true;
                                    //}
                                    @endphp
                                    <div id="collapseFilter{{$key+1}}" class="panel-collapse active collapse @if(empty($closed)) in @endif" aria-expanded="true">
                                        <div class="box-body">
                                            <div class="col-md-3">
                                                <div class="form-group">
                                                    <label for="">@lang('product.category') :</label>
                                                    <select class="filtervh" id="amazon_list_filter_category_table{{ $key+1 }}" style="width:100%" placeholder="@lang('lang_v1.all')">
                                                        <option value="">@lang('lang_v1.all')</option>
                                                        @if(!empty($marketplace_categories))
                                                        @foreach ($marketplace_categories as $item)
                                                        <option value="{{ $item->category }}">{{ $item->category }}</option>
                                                        @endforeach
                                                        @endif
                                                    </select>
                                                </div>
                                            </div>
                                            <div class="col-md-3">
                                                <div class="form-group">
                                                    <label for="">@lang('product.synced') :</label>
                                                    <select class="filtervh" id="amazon_list_filter_sync{{$key+1}}" style="width:100%" placeholder="@lang('lang_v1.all')">
                                                        <option value="">@lang('lang_v1.all')</option>
                                                        <option value="1">YES</option>
                                                        <option value="0">NO</option>
                                                    </select>
                                                </div>
                                            </div>
                                            <div class="col-md-3">
                                                <div class="form-group">
                                                    <label for="">@lang('product.status') :</label>
                                                    <select class="filtervh" id="amazon_list_filter_status{{$key+1}}" style="width:100%" placeholder="@lang('lang_v1.all')">
                                                        <option value="">@lang('lang_v1.all')</option>
                                                        <option value="Active">Active</option>
                                                        <option value="Inactive">Inactive</option>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <!-- @endcomponent -->
                            </div>
                        </div>
                        <table class="table table-bordered table-striped hide-footer ajax_view" id="amazon_table_all" style="width: 100%;">
                            <thead>
                                <tr>
                                    <th><input type="checkbox" id="select-all-row" data-table-id="amazon_table_all"></th>
                                    <th style="width: 10px" ;>&nbsp;</th>
                                    <th style="width: 20px" ;>@lang('messages.action')</th>
                                    <th style="width: 20px" ;>@lang('lang_v1.image')</th>
                                    <!-- <th>@lang('lang_v1.amazon_store')</th> -->
                                    <th>@lang('product.asin')</th>
                                    <th>@lang('product.sku')</th>
                                    <th>@lang('product.isbn13')</th>
                                    <th>@lang('product.item_condition')</th>
                                    <th>@lang('sale.product')</th>
                                    <!-- <th>@lang('product.brand')</th> -->
                                    <th>@lang('lang_v1.category')</th>
                                    <!-- <th>@lang('lang_v1.manufacturer')</th> -->
                                    <!-- <th>@lang('lang_v1.product_group')</th> -->
                                    <!-- <th>@lang('product.type')</th> -->
                                    <!-- <th>@lang('lang_v1.material')</th> -->
                                    <th>@lang('product.price')</th>
                                    <th>@lang('barcode.label_price')</th>
                                    <th>@lang('product.qty')</th>
                                    <!-- <th>@lang('product.status')</th> -->
                                    <th>@lang('product.synced')</th>
                                </tr>
                            </thead>
                            <tfoot>
                                <tr>
                                    <td colspan="10">
                                        <button type="button" style="display: none" class="btn btn-xs btn-primary" id="label-queueall" onclick="popupPrintLabelsQueue(event, 'all')"> <i class="fa fa-barcode"></i> {{__('barcode.print_queue_items')}} <span id="total_label_queueall"></span></button>
                                        <button type="button" class="btn btn-xs btn-primary" id="label-selected" onclick="printLabelMultiple(event, 'all')"> <i class="fa fa-barcode"></i> {{__('barcode.print_labels')}}</button>
                                        <button type="button" class="btn btn-xs btn-primary" id="qty-selected" onclick="popupSelectedItems('all')"> <i class="fa fa-database"></i> {{__('product.update_products')}}</button>
                                    </td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>
                </div>
            @endif
        </div>
    </div>
    </div>
    </div>
    </div>
    {!! Form::close() !!}
</section>
<!-- /.content -->
@stop
@section('javascript')
<script type="text/javascript">
    var etsy_table,
        walmart_table,
        detailRows = [],
        tables = {},
        element_modal_detail_choosen,
        total_queue_table = 0;
        amazon_sellers = JSON.parse($('#amazon_sellers').val());
        let pollProgress = null; // declared globally,    
    const baseUrl = window.location.origin;
    if (amazon_sellers.length > 0) {
        $.each(amazon_sellers, function(k, v) {
            $(document).on('change', '#amazon_list_filter_category_table' + (k + 1), function() {
                tables['amazon_table_' + (k + 1)].ajax.reload();
            });
            $(document).on('change', '#amazon_list_filter_sync' + (k + 1), function() {
                tables['amazon_table_' + (k + 1)].ajax.reload();
            });
            $(document).on('change', '#amazon_list_filter_status' + (k + 1), function() {
                tables['amazon_table_' + (k + 1)].ajax.reload();
            });
            var total_queue = localStorage.getItem('total_queue' + v.seller_id);
            if(total_queue > 0) {
                $('#label-queue' + v.seller_id).css('display', 'inline-block');
                $('#total_label_queue' + v.seller_id).html('(' + total_queue + ')');
                $('#label-queueall').css('display', 'inline-block');
                $('#total_label_queueall').html('(' + total_queue + ')');
            } else {
                $('#label-queue' + v.seller_id).css('display', 'none');
                $('#total_label_queue' + v.seller_id).html('(0)');
                $('#label-queueall').css('display', 'none');
                $('#total_label_queueall').html('(0)');
            }
        })        
    }
    $(document).ready(function() {

        //PALIGU
        //We will detect when users use barcode scanner
        //Start: barcode detection
        let inputString = '';
        let lastInputTime = 0;
        
        // Below is the code to detect barcode scanner input
        // Commented out because we need to improve the function. When Search textbox is active, system shouldn't detect barcode scanner input.
        // document.addEventListener('keydown', function(event) {
        //     const currentTime = new Date().getTime();
        //     const timeDiff = currentTime - lastInputTime;

        //     if (event.key === 'Enter' && inputString.length > 3) {
        //         event.preventDefault();
        //         swal({
        //             title: 'Barcode Scan Detected!',
        //             text: "Do you want to search on Amazon for this product?",
        //             icon: 'info',
        //             buttons: {
        //                 cancel: "No, cancel",
        //                 confirm: "Yes, search it!"
        //             },
        //         }).then((confirmed) => {
        //             if (confirmed) {
        //                 var amazonLocation = $('#select2-product_locations_amazon-container').text();
        //                 getAmazonProductData(inputString, amazonLocation);
        //                 inputString = '';
        //             }
        //         });


        //     } else {
        //         if (timeDiff < 100) {
        //             inputString += event.key;
        //         } else {
        //             inputString = event.key;
        //         }
        //         lastInputTime = currentTime;
        //     }
        // });

        if (amazon_sellers.length > 0) {
            getSellerPerformanceReport(amazon_sellers[0].seller_id);
            getSalesTrafficReport(amazon_sellers[0].seller_id); // I commented this because it drains API limits. Please check Trello card for more info.            \
            startPollingProgress();           
            getPrintQueueCountByUser(); 
        }


        //End: barcode detection        

        /* var bigenable = $("input[type='radio'][name='etsy_enable']:checked").val()        
        var amazonenable = $("input[type='radio'][name='amazon_enable']:checked").val()        
        var walmartenable = $("input[type='radio'][name='walmart_enable']:checked").val()        
        var ebayenable = $("input[type='radio'][name='ebay_enable']:checked").val()       

        if(bigenable == '1') {
            // bigcommerce
            $('#etsy_api_url').css('display', 'block')
            $('#etsy_api_access_token').css('display', 'block')
            $('#etsy_api_key').css('display', 'block')
            $('#etsy_api_secret').css('display', 'block')
            $('#etsy_space').addClass('col-sm-3')
        } else {
            // big commerce
            $('#etsy_api_url').css('display', 'none')
            $('#etsy_api_access_token').css('display', 'none')
            $('#etsy_api_key').css('display', 'none')
            $('#etsy_api_secret').css('display', 'none')
            $('#etsy_space').removeClass('col-sm-3')
        }

        if(amazonenable == '1') {
            // amazon
            $('#amazon_api_url').css('display', 'block')
            $('#amazon_api_access_token').css('display', 'block')
            $('#amazon_api_key').css('display', 'block')
            $('#amazon_api_secret').css('display', 'block')
            $('#amazon_space').addClass('col-sm-3')
        } else {
            // amazon
            $('#amazon_api_url').css('display', 'none')
            $('#amazon_api_access_token').css('display', 'none')
            $('#amazon_api_key').css('display', 'none')
            $('#amazon_api_secret').css('display', 'none')
            $('#amazon_space').removeClass('col-sm-3')
        }

        if(walmartenable == '1') {
            // woo commerce
            $('#walmart_api_url').css('display', 'block')
            $('#walmart_api_access_token').css('display', 'block')
            $('#walmart_api_key').css('display', 'block')
            $('#walmart_api_secret').css('display', 'block')
            $('#walmart_space').addClass('col-sm-3')
        } else {
            // woo commerce
            $('#walmart_api_url').css('display', 'none')
            $('#walmart_api_access_token').css('display', 'none')
            $('#walmart_api_key').css('display', 'none')
            $('#walmart_api_secret').css('display', 'none')
            $('#walmart_space').removeClass('col-sm-3')
        }
           
        if(ebayenable == '1') {
            // ebay
            $('#ebay_api_url').css('display', 'block')
            $('#ebay_api_access_token').css('display', 'block')
            $('#ebay_api_key').css('display', 'block')
            $('#ebay_api_secret').css('display', 'block')
            $('#ebay_space').addClass('col-sm-3')
        } else {                                    
            // ebay
            $('#ebay_api_url').css('display', 'none')
            $('#ebay_api_access_token').css('display', 'none')
            $('#ebay_api_key').css('display', 'none')
            $('#ebay_api_secret').css('display', 'none')
            $('#ebay_space').addClass('col-sm-3')
        } */

        /* etsy_table = $('#etsy_table').DataTable({
            processing: true,
            serverSide: true,
            aaSorting: [
                [1, 'asc']
            ],
            // scrollY: "75vh",
            // scrollX: true,
            // scrollCollapse: true                    
            "ajax": {
                "url": "/products?vhomni_type=walmart",
            },
            columnDefs: [{
                "targets": [0, 1, 2],
                "orderable": false,
                "searchable": false
            }],
            columns: [{
                    data: 'mass_delete',
                    orderable: false,
                    searchable: false
                },
                {
                    data: 'image_vhomni',
                    name: 'products.image_vhomni',
                    orderable: false,
                    searchable: false
                },
                {
                    data: 'action',
                    name: 'action',
                    orderable: false,
                    searchable: false
                },
                {
                    data: 'product',
                    name: 'products.name'
                },
                {
                    data: 'product_locations',
                    name: 'product_locations'
                },
                {
                    data: 'selling_price',
                    name: 'max_price',
                    searchable: false
                },
                {
                    data: 'current_stock',
                    searchable: false
                },
                {
                    data: 'category',
                    name: 'c1.name'
                },
                {
                    data: 'brand',
                    name: 'brands.name'
                },
                {
                    data: 'sku',
                    name: 'products.sku'
                },
            ],
        })

        walmart_table = $('#walmart_table').DataTable({
            processing: true,
            serverSide: true,
            aaSorting: [
                [1, 'asc']
            ],
            // scrollY: "75vh",
            // scrollX: true,
            // scrollCollapse: true                    
            "ajax": {
                "url": "/products?vhomni_type=walmart",
            },
            columnDefs: [{
                "targets": [0, 1, 2],
                "orderable": false,
                "searchable": false
            }],
            columns: [{
                    data: 'mass_delete',
                    orderable: false,
                    searchable: false
                },
                {
                    data: 'image_vhomni',
                    name: 'products.image_vhomni',
                    orderable: false,
                    searchable: false,
                    width: '10px'
                },
                {
                    data: 'action',
                    name: 'action',
                    orderable: false,
                    searchable: false
                },
                {
                    data: 'product',
                    name: 'products.name'
                },
                {
                    data: 'product_locations',
                    name: 'product_locations'
                },
                {
                    data: 'selling_price',
                    name: 'max_price',
                    searchable: false
                },
                {
                    data: 'current_stock',
                    searchable: false
                },
                {
                    data: 'category',
                    name: 'c1.name'
                },
                {
                    data: 'brand',
                    name: 'brands.name'
                },
                {
                    data: 'sku',
                    name: 'products.sku'
                },
            ],
        }); */

        // PALIGU
        // amazon_table1 = $('#amazon_table_1').DataTable({
        //     processing: true,
        //     serverSide: true,
        //     paging: true,
        //     pageLength: 25,
        //     language: {
        //         info: "Showing _START_ to _END_ of _TOTAL_ entries"
        //     },
        //     ajax: {
        //         url: "/keepa/product/A2NODI4BBRA1B1",
        //         data: function(d) {
        //             d.category = $('#amazon_list_filter_category').val()
        //         },
        //         dataSrc: function(json) {
        //             return json.data || [];
        //         },
        //         error: function(xhr, error, thrown) {
        //             console.log("AJAX Error: ", xhr.responseText);
        //         }
        //     },
        //     columns: [{
        //             data: null,
        //             orderable: false,
        //             searchable: false,
        //             width: '10px',
        //             render: function(data) {
        //                 return '<i style="margin:auto; font-size: 2vh;" class="fa fa-plus-circle text-success cursor-pointer no-print rack-details dt-control selectable_td" title="' + LANG.details + '"></i>';
        //             }
        //         },
        //         {
        //             data: null,
        //             orderable: false,
        //             searchable: false,
        //             width: '20px',
        //             render: function(data) {
        //                 return `<div class="btn-group"><button type="button" class="btn btn-info dropdown-toggle btn-xs" data-toggle="dropdown" aria-expanded="false"><i class="fa fa-cog"> </i><span class="caret"></span><span class="sr-only">Toggle Dropdown</span></button><ul class="dropdown-menu dropdown-menu-left" role="menu">
        //                     <li><a href="${baseUrl + '/keepa/labels/show/' + data.id}" data-toggle="tooltip" title="${LANG.label_help}"><i class="fa fa-barcode"></i> ${LANG.labels}</a></li>    
        //                 </ul></div>`;
        //             }
        //         },
        //         {
        //             data: 'image',
        //             name: 'image',
        //             render: function(data, type, row) {
        //                 //console.log('Image data:', data);
        //                 //return data || 'N/A';
        //                 var image = data ? 'https://m.media-amazon.com/images/I/' + data + '' : "{{ asset('img/no_img.png') }} "
        //                 return '<div style="display: flex;"><img src="' + image + '" alt="Product image" class="product-thumbnail-small"></div>';
        //             }
        //         },
        //         {
        //             data: 'asin',
        //             name: 'asin',
        //             render: function(data, type, row) {
        //                 //console.log('ASIN data:', data);
        //                 return '<section style="font-size: 1.4vh;">' + data + '</section>' || 'N/A';
        //             }
        //         },
        //         {
        //             data: 'title',
        //             name: 'title',
        //             render: function(data, type, row) {
        //                 //console.log('Title data:', data);
        //                 return '<section style="font-size: 1.4vh;">' + data + '</section>' || 'N/A';
        //             }
        //         },
        //         // { 
        //         //     data: 'brand',
        //         //     name: 'brand',
        //         //     render: function(data, type, row) {
        //         //         //console.log('brand data:', data);
        //         //         return data || 'N/A';
        //         //     }
        //         // },
        //         {
        //             data: 'category',
        //             name: 'category',
        //             render: function(data, type, row) {
        //                 //console.log('category data:', data);
        //                 return '<section style="font-size: 1.4vh;">' + data + '</section>' || 'N/A';
        //             }
        //         },
        //         // { 
        //         //     data: 'manufacturer',
        //         //     name: 'manufacturer',
        //         //     render: function(data, type, row) {
        //         //         //console.log('manufacturer data:', data);
        //         //         return data || 'N/A';
        //         //     }
        //         // },
        //         // { 
        //         //     data: 'productGroup',
        //         //     name: 'productGroup',
        //         //     render: function(data, type, row) {
        //         //         //console.log('productGroup data:', data);
        //         //         return data || 'N/A';
        //         //     }
        //         // },
        //         // { 
        //         //     data: 'type',
        //         //     name: 'type',
        //         //     render: function(data, type, row) {
        //         //         //console.log('type data:', data);
        //         //         return data || 'N/A';
        //         //     }
        //         // },
        //         // { 
        //         //     data: 'binding',
        //         //     name: 'binding',
        //         //     render: function(data, type, row) {
        //         //         //console.log('binding data:', data);
        //         //         return data || 'N/A';
        //         //     }
        //         // },
        //         {
        //             data: 'current_price',
        //             name: 'current_price',
        //             render: function(data, type, row) {
        //                 //console.log('Price data:', data);
        //                 return '<section style="font-size: 1.4vh;">' + data + '</section>' || 'N/A';
        //             }
        //         },
        //         {
        //             data: 'current_qty',
        //             name: 'current_qty',
        //             render: function(data, type, row) {
        //                 //console.log('Price data:', data);
        //                 return '<section style="font-size: 1.4vh;">' + data + '</section>' || 'N/A';
        //             }
        //         },
        //     ],
        //     createdRow: function(row, data, dataIndex) {
        //         $(row).attr('data-href', baseUrl + '/keepa/product/preview/modal/' + data.id); // Menambahkan atribut data-id
        //     },
        //     order: [
        //         [1, 'asc']
        //     ]
        // });

        // $('#amazon_table_1 tbody').on('click', 'tr i.rack-details', function() {
        //     var i = $(this);
        //     var tr = $(this).closest('tr');
        //     var row = amazon_table1.row(tr);
        //     var idx = $.inArray(tr.attr('id'), detailRows);

        //     if (row.child.isShown()) {
        //         i.addClass('fa-plus-circle text-success');
        //         i.removeClass('fa-minus-circle text-danger');

        //         row.child.hide();

        //         // Remove from the 'open' array
        //         detailRows.splice(idx, 1);
        //     } else {
        //         i.removeClass('fa-plus-circle text-success');
        //         i.addClass('fa-minus-circle text-danger');

        //         row.child(format_amazon_table1(row.data())).show();

        //         // Add to the 'open' array
        //         if (idx === -1) {
        //             detailRows.push(tr.attr('id'));
        //         }
        //     }
        // });

        // function format_amazon_table1(d) {
        //     return `
        //         <div class="row">
        //             <div class="col-md-10 col-md-offset-1 col-xs-12">
        //                 <div class="table-responsive">
        //                     <table class="table table-condensed bg-gray">
        //                         <tbody>
        //                             <tr>
        //                                 <th style="font-size: 1.4vh;">@lang('product.brand')</th>
        //                                 <th style="font-size: 1.4vh;">@lang('lang_v1.manufacturer')</th>
        //                                 <th style="font-size: 1.4vh;">@lang('lang_v1.product_group')</th>
        //                                 <th style="font-size: 1.4vh;">@lang('product.type')</th>
        //                                 <th style="font-size: 1.4vh;">@lang('lang_v1.material')</th>
        //                             </tr>
        //                             <tr>
        //                                 <td style="font-size: 1.4vh;">${d.brand}</td>
        //                                 <td style="font-size: 1.4vh;">${d.manufacturer}</td>
        //                                 <td style="font-size: 1.4vh;">${d.productGroup}</td>
        //                                 <td style="font-size: 1.4vh;">${d.type}</td>
        //                                 <td style="font-size: 1.4vh;">${d.binding}</td>
        //                             </tr>          
        //                         </tbody>
        //                     </table>
        //                 </div>
        //             </div>
        //         </div>
        //     `
        // }
        // ADRI 
        if (amazon_sellers.length > 0) {
            tables['amazon_table_all'] = $('#amazon_table_all').DataTable({
                processing: true,
                serverSide: true,
                paging: true,
                pageLength: 15,
                lengthMenu: [15, 25, 50, 100],  // Pagination options
                autoWidth: false,
                language: {
                    info: "Showing _START_ to _END_ of _TOTAL_ entries"
                },
                select: {
                    style: 'multi'
                },
                ajax: {
                    url: "/amazon/table/products/all",
                    data: function(d) {
                        d.category = $('#amazon_list_filter_category_table_all').val()
                        d.synced = $('#amazon_list_filter_sync_all').val()
                        d.status = $('#amazon_list_filter_status_all').val()
                    },
                    dataSrc: function(json) {
                        return json.data || [];
                    },
                    error: function(xhr, error, thrown) {
                        // console.log("AJAX Error: ", xhr.responseText);
                    }
                },
                columns: [
                    {
                        data: null,
                        orderable: false,
                        searchable: false,
                        width: '10px',
                        render: function(data) {
                            return '<input type="checkbox" class="row-select" value="'+data.id+'">'
                        }
                    },
                    {
                        data: null,
                        orderable: false,
                        searchable: false,
                        width: '10px',
                        render: function(data) {
                            return '<i style="margin:auto; font-size: 2vh;" class="fa fa-plus-circle text-success cursor-pointer no-print rack-details dt-control selectable_td" title="' + LANG.details + '"></i>';
                        }
                    },
                    {
                        data: null,
                        orderable: false,
                        searchable: false,
                        width: '20px',
                        createdCell: function(td, cellData, rowData, row, col) {
                            // td       => the actual <td> element
                            // cellData => the value of the cell (in your case it's `null`)
                            // rowData  => the full row's data object (same as `data` in render)
                            // row, col => row and column indexes                                
                            if(rowData.reference_id) {
                                if('{{$user_id}}' == rowData.user_id) {
                                    td.style.backgroundColor = '#ffff00'; // Yellow
                                    // total_queue_table++;
                                    // localStorage.setItem('total_queue', total_queue_table);
                                    // $.each(amazon_sellers, function(k,v) {                        
                                    //     $('#total_label_queue' + v.seller_id).html('('+total_queue_table+')');
                                    //     $('#label-queue' + v.seller_id).css('display', 'inline-block');
                                    // })
                                }
                            }
                        },
                        render: function(data) {
                            var createCompetitivePrices = '';
                            if (!data.competitive_price_id) {
                                createCompetitivePrices = `<li><a href="javascript:void(0)" onclick="createCompetitivePricesToDb('${data.store}', '${data.asin}', this)"><i class="fa fa-microchip"></i> ${LANG.vh_ai_competitive_prices}</a></li>`;
                            }

                            var title = data.title.replace(/'/g, "\\'");    
                            
                            var queue_labels = `<li><a href="javascript:void(0)" onclick="addToPrintQueue(event, ${data.id}, 'all')" data-toggle="tooltip" title="${LANG.add_to_print_queue}"><i class="fa fa-barcode"></i> ${LANG.add_to_print_queue}</a></li>`;
                            if(data.reference_id) {
                                if('{{$user_id}}' == data.user_id) {
                                    queue_labels = `
                                        <li><a href="javascript:void(0)" onclick="removeItemPrintLabelsQueue(event, ${data.id}, 'remove_action', 'all')" data-toggle="tooltip" title="${LANG.remove_from_print_queue}"><i class="fa fa-barcode"></i> ${LANG.remove_from_print_queue}</a></li> 
                                    `;
                                }                                    
                            }


                            return `<div class="btn-group"><button type="button" class="btn btn-info dropdown-toggle btn-xs" data-toggle="dropdown" aria-expanded="false"><i class="fa fa-cog"> </i><span class="caret"></span><span class="sr-only">Toggle Dropdown</span></button><ul class="dropdown-menu dropdown-menu-left" role="menu">
                                <li><a href="${baseUrl + '/amazon/labels/' + data.id}" data-toggle="tooltip" title="${LANG.label_help}"><i class="fa fa-barcode"></i> ${LANG.labels}</a></li>    
                                ${queue_labels}
                                ${createCompetitivePrices}
                                <li><a href="javascript:void(0)" onclick="updateSellerListingQuantityModal('${data.store}', '${data.sku}', '${title}', '${data.qty}')"><i class="fa fa-database"></i> ${LANG.update_listing_quantity}</a></li>    
                                {{-- <li><a href="javascript:void(0)" onclick="updatePriceModal('${data.store}', '${data.sku}', '${title}', '${data.price}')"><i class="fa fa-database"></i> ${LANG.update_listing_price}</a></li> --}}
                                <li><a href="javascript:void(0)" onclick="updateConditionModal('${data.store}', '${data.sku}', '${title}', '${data.item_condition}')"><i class="fa fa-database"></i> ${LANG.update_listing_condition}</a></li>    
                            </ul></div>`;
                        }
                    },
                    {
                        data: 'image',
                        name: 'image',
                        render: function(data, type, row) {
                            //console.log('Image data:', data);
                            //return data || 'N/A';
                            var image = data ? data : "{{ asset('img/no_img.png') }} "
                            return '<div style="display: flex;"><img src="' + image + '" alt="Product image" class="product-thumbnail-small"></div>';
                        }
                    },
                    {
                        data: 'asin',
                        name: 'asin',
                        class: 'copyable',
                        render: function(data, type, row) {
                            //console.log('ASIN data:', data);
                            return '<section style="font-size: 1.4vh;" class="copyable">' + data + '</section>' || 'N/A';
                        }
                    },
                    {
                        data: 'sku',
                        name: 'sku',
                        class: 'copyable',
                        render: function(data, type, row) {
                            //console.log('ASIN data:', data);
                            var urlProductDetail = baseUrl + '/amazon/product/preview/modal/' + row.id;
                            return '<a href="javascript:void(0)" style="font-size: 1.4vh;" class="btn-modal copyable" data-container=".view_modal" data-href="'+urlProductDetail+'">' + data + '</a>' || 'N/A';
                        }
                    },
                    {
                        data: 'isbn13',
                        name: 'isbn13',
                        class: 'copyable',
                        render: function(data, type, row) {
                            //console.log('ASIN data:', data);
                            return '<section style="font-size: 1.4vh;" class="copyable">' + data + '</section>' || 'N/A';
                        }
                    },
                    {
                        data: 'item_condition',
                        name: 'item_condition',
                        class: 'copyable',
                        render: function(data, type, row) {
                            //console.log('ASIN data:', data);
                            return '<section style="font-size: 1.4vh;" class="copyable">' + data + '</section>' || 'N/A';
                        }
                    },
                    {
                        data: 'title',
                        name: 'title',
                        class: 'copyable',
                        render: function(data, type, row) {
                            //console.log('Title data:', data);
                            return '<section style="font-size: 1.4vh;" class="copyable">' + data + '</section>' || 'N/A';
                        }
                    },
                    // { 
                    //     data: 'brand',
                    //     name: 'brand',
                    //     render: function(data, type, row) {
                    //         //console.log('brand data:', data);
                    //         return data || 'N/A';
                    //     }
                    // },
                    {
                        data: 'category',
                        name: 'category',
                        class: 'copyable',
                        render: function(data, type, row) {
                            //console.log('category data:', data);
                            return '<section style="font-size: 1.4vh;" class="copyable">' + data + '</section>' || 'N/A';
                        }
                    },
                    // { 
                    //     data: 'manufacturer',
                    //     name: 'manufacturer',
                    //     render: function(data, type, row) {
                    //         //console.log('manufacturer data:', data);
                    //         return data || 'N/A';
                    //     }
                    // },
                    // { 
                    //     data: 'productGroup',
                    //     name: 'productGroup',
                    //     render: function(data, type, row) {
                    //         //console.log('productGroup data:', data);
                    //         return data || 'N/A';
                    //     }
                    // },
                    // { 
                    //     data: 'type',
                    //     name: 'type',
                    //     render: function(data, type, row) {
                    //         //console.log('type data:', data);
                    //         return data || 'N/A';
                    //     }
                    // },
                    // { 
                    //     data: 'binding',
                    //     name: 'binding',
                    //     render: function(data, type, row) {
                    //         //console.log('binding data:', data);
                    //         return data || 'N/A';
                    //     }
                    // },
                    {
                        data: 'current_price',
                        name: 'current_price',
                        class: 'copyable',
                        render: function(data, type, row) {
                            //console.log('Price data:', data);
                            return '<section style="font-size: 1.4vh;" class="copyable">' + data + '</section>' || 'N/A';
                        }
                    },
                    {
                        data: 'label_price',
                        name: 'label_price',
                        class: 'copyable',
                        render: function(data, type, row) {
                            //console.log('Price data:', data);
                            return '<section style="font-size: 1.4vh;" class="copyable">' + data + '</section>' || 'N/A';
                        }
                    },
                    {
                        data: 'current_qty',
                        name: 'current_qty',
                        class: 'copyable',
                        render: function(data, type, row) {
                            //console.log('Price data:', data);
                            return '<section style="font-size: 1.4vh;" class="copyable">' + data + '</section>' || 'N/A';
                        }
                    },
                    // {
                    //     data: 'status',
                    //     name: 'status',
                    //     class: 'copyable',
                    //     render: function(data, type, row) {
                    //         //console.log('Price data:', data);
                    //         return '<section style="font-size: 1.4vh;" class="copyable">' + data + '</section>' || 'N/A';
                    //     }
                    // },
                    {
                        data: 'sync',
                        name: 'sync',
                        class: 'copyable',
                        render: function(data, type, row) {
                            //console.log('Price data:', data);
                            return '<section style="font-size: 1.4vh;" class="copyable">' + data + '</section>' || 'N/A';
                        }
                    },
                ],
                // createdRow: function(row, data, dataIndex) {
                //     $(row).attr('data-href', baseUrl + '/amazon/product/preview/modal/' + data.id); // Menambahkan 
                //     // atribut data-id
                //     $( row ).find('td:eq(0)').attr('class', 'selectable_td');
                // },
                order: [
                    [1, 'asc']
                ]
            })

            $('#amazon_table_all input').on('click', function() {
                $(this).select();
            });

            $('#amazon_table_all tbody').on('click', 'td.copyable', function() {
                const text = $(this).text().trim();

                // Copy to clipboard
                navigator.clipboard.writeText(text).then(function() {
                    // Show "Copied!" in the status cell of the same row
                    toastr.info('Copied to clipboard!');
                }.bind(this));
            });

            $('#amazon_table_all tbody').on('click', 'tr i.rack-details', function() {
                var i = $(this);
                var tr = $(this).closest('tr');
                var row = tables['amazon_table_all'].row(tr);
                var idx = $.inArray(tr.attr('id'), detailRows);

                if (row.child.isShown()) {
                    i.addClass('fa-plus-circle text-success');
                    i.removeClass('fa-minus-circle text-danger');

                    row.child.hide();

                    // Remove from the 'open' array
                    detailRows.splice(idx, 1);
                } else {
                    i.removeClass('fa-plus-circle text-success');
                    i.addClass('fa-minus-circle text-danger');

                    row.child(format_amazon_table(row.data())).show();

                    // Add to the 'open' array
                    if (idx === -1) {
                        detailRows.push(tr.attr('id'));
                    }
                }
            });

            $.each(amazon_sellers, function(k, v) {
                tables['amazon_table_' + (k + 1)] = $('#amazon_table_' + (k + 1)).DataTable({
                    processing: true,
                    serverSide: true,
                    paging: true,
                    pageLength: 15,
                    lengthMenu: [15, 25, 50, 100],  // Pagination options
                    autoWidth: false,
                    language: {
                        info: "Showing _START_ to _END_ of _TOTAL_ entries"
                    },
                    select: {
                        style: 'multi'
                    },
                    ajax: {
                        url: "/amazon/table/products/" + v.seller_id,
                        data: function(d) {
                            d.category = $('#amazon_list_filter_category_table' + (k + 1)).val()
                            d.synced = $('#amazon_list_filter_sync' + (k + 1)).val()
                            d.status = $('#amazon_list_filter_status' + (k + 1)).val()
                        },
                        dataSrc: function(json) {
                            return json.data || [];
                        },
                        error: function(xhr, error, thrown) {
                            // console.log("AJAX Error: ", xhr.responseText);
                        }
                    },
                    columns: [
                        {
                            data: null,
                            orderable: false,
                            searchable: false,
                            width: '10px',
                            render: function(data) {
                                return '<input type="checkbox" class="row-select" value="'+data.id+'">'
                            }
                        },
                        {
                            data: null,
                            orderable: false,
                            searchable: false,
                            width: '10px',
                            render: function(data) {
                                return '<i style="margin:auto; font-size: 2vh;" class="fa fa-plus-circle text-success cursor-pointer no-print rack-details dt-control selectable_td" title="' + LANG.details + '"></i>';
                            }
                        },
                        {
                            data: null,
                            orderable: false,
                            searchable: false,
                            width: '20px',
                            createdCell: function(td, cellData, rowData, row, col) {
                                // td       => the actual <td> element
                                // cellData => the value of the cell (in your case it's `null`)
                                // rowData  => the full row's data object (same as `data` in render)
                                // row, col => row and column indexes                                
                                if(rowData.reference_id) {
                                    if('{{$user_id}}' == rowData.user_id) {
                                        td.style.backgroundColor = '#ffff00'; // Yellow
                                        // total_queue_table++;
                                        // localStorage.setItem('total_queue', total_queue_table);
                                        // $.each(amazon_sellers, function(k,v) {                        
                                        //     $('#total_label_queue' + v.seller_id).html('('+total_queue_table+')');
                                        //     $('#label-queue' + v.seller_id).css('display', 'inline-block');
                                        // })
                                    }
                                }
                            },
                            render: function(data) {
                                var createCompetitivePrices = '';
                                if (!data.competitive_price_id) {
                                    createCompetitivePrices = `<li><a href="javascript:void(0)" onclick="createCompetitivePricesToDb('${data.store}', '${data.asin}', this)"><i class="fa fa-microchip"></i> ${LANG.vh_ai_competitive_prices}</a></li>`;
                                }

                                var title = data.title.replace(/'/g, "\\'");    
                                
                                var queue_labels = `<li><a href="javascript:void(0)" onclick="addToPrintQueue(event, ${data.id}, '${data.store}')" data-toggle="tooltip" title="${LANG.add_to_print_queue}"><i class="fa fa-barcode"></i> ${LANG.add_to_print_queue}</a></li>`;
                                if(data.reference_id) {
                                    if('{{$user_id}}' == data.user_id) {
                                        queue_labels = `
                                            <li><a href="javascript:void(0)" onclick="removeItemPrintLabelsQueue(event, ${data.id}, 'remove_action', '${data.store}')" data-toggle="tooltip" title="${LANG.remove_from_print_queue}"><i class="fa fa-barcode"></i> ${LANG.remove_from_print_queue}</a></li> 
                                        `;
                                    }                                    
                                }


                                return `<div class="btn-group"><button type="button" class="btn btn-info dropdown-toggle btn-xs" data-toggle="dropdown" aria-expanded="false"><i class="fa fa-cog"> </i><span class="caret"></span><span class="sr-only">Toggle Dropdown</span></button><ul class="dropdown-menu dropdown-menu-left" role="menu">
                                    <li><a href="${baseUrl + '/amazon/labels/' + data.id}" data-toggle="tooltip" title="${LANG.label_help}"><i class="fa fa-barcode"></i> ${LANG.labels}</a></li>    
                                    ${queue_labels}
                                    ${createCompetitivePrices}
                                    <li><a href="javascript:void(0)" onclick="updateSellerListingQuantityModal('${data.store}', '${data.sku}', '${title}', '${data.qty}')"><i class="fa fa-database"></i> ${LANG.update_listing_quantity}</a></li>    
                                    {{-- <li><a href="javascript:void(0)" onclick="updatePriceModal('${data.store}', '${data.sku}', '${title}', '${data.price}')"><i class="fa fa-database"></i> ${LANG.update_listing_price}</a></li> --}}
                                    <li><a href="javascript:void(0)" onclick="updateConditionModal('${data.store}', '${data.sku}', '${title}', '${data.item_condition}')"><i class="fa fa-database"></i> ${LANG.update_listing_condition}</a></li>    
                                </ul></div>`;
                            }
                        },
                        {
                            data: 'image',
                            name: 'image',
                            render: function(data, type, row) {
                                //console.log('Image data:', data);
                                //return data || 'N/A';
                                var image = data ? data : "{{ asset('img/no_img.png') }} "
                                return '<div style="display: flex;"><img src="' + image + '" alt="Product image" class="product-thumbnail-small"></div>';
                            }
                        },
                        {
                            data: 'asin',
                            name: 'asin',
                            class: 'copyable',
                            render: function(data, type, row) {
                                //console.log('ASIN data:', data);
                                return '<section style="font-size: 1.4vh;" class="copyable">' + data + '</section>' || 'N/A';
                            }
                        },
                        {
                            data: 'sku',
                            name: 'sku',
                            class: 'copyable',
                            render: function(data, type, row) {
                                //console.log('ASIN data:', data);
                                var urlProductDetail = baseUrl + '/amazon/product/preview/modal/' + row.id;
                                return '<a href="javascript:void(0)" style="font-size: 1.4vh;" class="btn-modal copyable" data-container=".view_modal" data-href="'+urlProductDetail+'">' + data + '</a>' || 'N/A';
                            }
                        },
                        {
                            data: 'isbn13',
                            name: 'isbn13',
                            class: 'copyable',
                            render: function(data, type, row) {
                                //console.log('ASIN data:', data);
                                return '<section style="font-size: 1.4vh;" class="copyable">' + data + '</section>' || 'N/A';
                            }
                        },
                        {
                            data: 'item_condition',
                            name: 'item_condition',
                            class: 'copyable',
                            render: function(data, type, row) {
                                //console.log('ASIN data:', data);
                                return '<section style="font-size: 1.4vh;" class="copyable">' + data + '</section>' || 'N/A';
                            }
                        },
                        {
                            data: 'title',
                            name: 'title',
                            class: 'copyable',
                            render: function(data, type, row) {
                                //console.log('Title data:', data);
                                return '<section style="font-size: 1.4vh;" class="copyable">' + data + '</section>' || 'N/A';
                            }
                        },
                        // { 
                        //     data: 'brand',
                        //     name: 'brand',
                        //     render: function(data, type, row) {
                        //         //console.log('brand data:', data);
                        //         return data || 'N/A';
                        //     }
                        // },
                        {
                            data: 'category',
                            name: 'category',
                            class: 'copyable',
                            render: function(data, type, row) {
                                //console.log('category data:', data);
                                return '<section style="font-size: 1.4vh;" class="copyable">' + data + '</section>' || 'N/A';
                            }
                        },
                        // { 
                        //     data: 'manufacturer',
                        //     name: 'manufacturer',
                        //     render: function(data, type, row) {
                        //         //console.log('manufacturer data:', data);
                        //         return data || 'N/A';
                        //     }
                        // },
                        // { 
                        //     data: 'productGroup',
                        //     name: 'productGroup',
                        //     render: function(data, type, row) {
                        //         //console.log('productGroup data:', data);
                        //         return data || 'N/A';
                        //     }
                        // },
                        // { 
                        //     data: 'type',
                        //     name: 'type',
                        //     render: function(data, type, row) {
                        //         //console.log('type data:', data);
                        //         return data || 'N/A';
                        //     }
                        // },
                        // { 
                        //     data: 'binding',
                        //     name: 'binding',
                        //     render: function(data, type, row) {
                        //         //console.log('binding data:', data);
                        //         return data || 'N/A';
                        //     }
                        // },
                        {
                            data: 'current_price',
                            name: 'current_price',
                            class: 'copyable',
                            render: function(data, type, row) {
                                //console.log('Price data:', data);
                                return '<section style="font-size: 1.4vh;" class="copyable">' + data + '</section>' || 'N/A';
                            }
                        },
                        {
                            data: 'label_price',
                            name: 'label_price',
                            class: 'copyable',
                            render: function(data, type, row) {
                                //console.log('Price data:', data);
                                return '<section style="font-size: 1.4vh;" class="copyable">' + data + '</section>' || 'N/A';
                            }
                        },
                        {
                            data: 'current_qty',
                            name: 'current_qty',
                            class: 'copyable',
                            render: function(data, type, row) {
                                //console.log('Price data:', data);
                                return '<section style="font-size: 1.4vh;" class="copyable">' + data + '</section>' || 'N/A';
                            }
                        },
                        // {
                        //     data: 'status',
                        //     name: 'status',
                        //     class: 'copyable',
                        //     render: function(data, type, row) {
                        //         //console.log('Price data:', data);
                        //         return '<section style="font-size: 1.4vh;" class="copyable">' + data + '</section>' || 'N/A';
                        //     }
                        // },
                        {
                            data: 'sync',
                            name: 'sync',
                            class: 'copyable',
                            render: function(data, type, row) {
                                //console.log('Price data:', data);
                                return '<section style="font-size: 1.4vh;" class="copyable">' + data + '</section>' || 'N/A';
                            }
                        },
                    ],
                    // createdRow: function(row, data, dataIndex) {
                    //     $(row).attr('data-href', baseUrl + '/amazon/product/preview/modal/' + data.id); // Menambahkan 
                    //     // atribut data-id
                    //     $( row ).find('td:eq(0)').attr('class', 'selectable_td');
                    // },
                    order: [
                        [1, 'asc']
                    ]
                })

                $('#amazon_table_' + (k + 1) + ' input').on('click', function() {
                    $(this).select();
                });

                $('#amazon_table_' + (k + 1) + ' tbody').on('click', 'td.copyable', function() {
                    const text = $(this).text().trim();

                    // Copy to clipboard
                    navigator.clipboard.writeText(text).then(function() {
                        // Show "Copied!" in the status cell of the same row
                        toastr.info('Copied to clipboard!');
                    }.bind(this));
                });

                $('#amazon_table_' + (k + 1) + ' tbody').on('click', 'tr i.rack-details', function() {
                    var i = $(this);
                    var tr = $(this).closest('tr');
                    var row = tables['amazon_table_' + (k + 1)].row(tr);
                    var idx = $.inArray(tr.attr('id'), detailRows);

                    if (row.child.isShown()) {
                        i.addClass('fa-plus-circle text-success');
                        i.removeClass('fa-minus-circle text-danger');

                        row.child.hide();

                        // Remove from the 'open' array
                        detailRows.splice(idx, 1);
                    } else {
                        i.removeClass('fa-plus-circle text-success');
                        i.addClass('fa-minus-circle text-danger');

                        row.child(format_amazon_table(row.data())).show();

                        // Add to the 'open' array
                        if (idx === -1) {
                            detailRows.push(tr.attr('id'));
                        }
                    }
                });

                function format_amazon_table(d) {
                    return `
                        <div class="row">
                            <div class="col-md-10 col-md-offset-1 col-xs-12">
                                <div class="table-responsive">
                                    <table class="table table-condensed bg-gray">
                                        <tbody>
                                            <tr>
                                                <th style="font-size: 1.4vh;">@lang('product.brand')</th>
                                                <th style="font-size: 1.4vh;">@lang('lang_v1.manufacturer')</th>
                                                <th style="font-size: 1.4vh;">@lang('lang_v1.product_group')</th>
                                                <th style="font-size: 1.4vh;">@lang('product.type')</th>
                                                <th style="font-size: 1.4vh;">@lang('lang_v1.material')</th>
                                            </tr>
                                            <tr>
                                                <td style="font-size: 1.4vh;">${d.brand ? d.brand : ''}</td>
                                                <td style="font-size: 1.4vh;">${d.manufacturer ? d.manufacturer : ''}</td>
                                                <td style="font-size: 1.4vh;">${d.productGroup ? d.productGroup : ''}</td>
                                                <td style="font-size: 1.4vh;">${d.type ? d.type : ''}</td>
                                                <td style="font-size: 1.4vh;">${d.binding ? d.binding : ''}</td>
                                            </tr>          
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    `
                }
            })
        }

        // ADRI
        // amazon_table1 = $('#amazon_table_1').DataTable({
        //     processing: true,
        //     processing: true,
        //     aaSorting: [[1, 'asc']],
        //     // scrollY: "75vh",
        //     // scrollX: true,
        //     // scrollCollapse: true                    
        //     "ajax": {
        //         "url": "/products?vhomni_type=amazon&seller_id=A2NODI4BBRA1B1",
        //     },                           
        //     /* columnDefs: [ {
        //         "targets": [0, 1, 2],
        //         "orderable": false,
        //         "searchable": false
        //     }], */
        //     columns: [                
        //         // { data: 'mass_delete', orderable: false, searchable: false},
        //         // { data: 'image_vhomni', name: 'products.image_vhomni', orderable: false, searchable: false},   
        //         { data: 'action', name: 'action', orderable: false, searchable: false},             
        //         { data: 'product', name: 'products.name', "width": '300px'},
        //         // { data: 'product_locations', name: 'product_locations'},                
        //         { data: 'selling_price', name: 'max_price', searchable: false},                
        //         { data: 'current_stock', searchable: false},
        //         { data: 'sku', name: 'products.sku'},                    
        //         { data: 'amazon_asin', name: 'products.amazon_asin'},                
        //     ],
        // })
        // amazon_table2 = $('#amazon_table_2').DataTable({
        //     processing: true,
        //     serverSide: true,
        //     aaSorting: [
        //         [1, 'asc']
        //     ],
        //     // scrollY: "75vh",
        //     // scrollX: true,
        //     // scrollCollapse: true                    
        //     "ajax": {
        //         "url": "/products?vhomni_type=amazon&seller_id=A7YLKH07FY1LY",
        //         dataSrc: function(json) {
        //             return [];
        //         },
        //     },
        //     /* columnDefs: [ {
        //         "targets": [0, 1, 2],
        //         "orderable": false,
        //         "searchable": false
        //     }], */
        //     columns: [
        //         // { data: 'mass_delete', orderable: false, searchable: false},
        //         // { data: 'image_vhomni', name: 'products.image_vhomni', orderable: false, searchable: false},   
        //         {
        //             data: 'action',
        //             name: 'action',
        //             orderable: false,
        //             searchable: false
        //         },
        //         {
        //             data: 'product',
        //             name: 'products.name',
        //             "width": '300px'
        //         },
        //         // { data: 'product_locations', name: 'product_locations'},                
        //         {
        //             data: 'selling_price',
        //             name: 'max_price',
        //             searchable: false
        //         },
        //         {
        //             data: 'current_stock',
        //             searchable: false
        //         },
        //         {
        //             data: 'sku',
        //             name: 'products.sku'
        //         },
        //         {
        //             data: 'amazon_asin',
        //             name: 'products.amazon_asin'
        //         },
        //     ],
        // });
        // amazon_table3 = $('#amazon_table_3').DataTable({
        //     processing: true,
        //     serverSide: true,
        //     aaSorting: [
        //         [1, 'asc']
        //     ],
        //     // scrollY: "75vh",
        //     // scrollX: true,
        //     // scrollCollapse: true                    
        //     "ajax": {
        //         "url": "/products?vhomni_type=amazon&seller_id=A13Y3JSUKFVTQ5",
        //         dataSrc: function(json) {
        //             return [];
        //         },
        //     },
        //     /* columnDefs: [ {
        //         "targets": [0, 1, 2],
        //         "orderable": false,
        //         "searchable": false
        //     }] ,*/
        //     columns: [
        //         // { data: 'mass_delete', orderable: false, searchable: false},
        //         // { data: 'image_vhomni', name: 'products.image_vhomni', orderable: false, searchable: false},   
        //         {
        //             data: 'action',
        //             name: 'action',
        //             orderable: false,
        //             searchable: false
        //         },
        //         {
        //             data: 'product',
        //             name: 'products.name',
        //             "width": '300px'
        //         },
        //         // { data: 'product_locations', name: 'product_locations'},                
        //         {
        //             data: 'selling_price',
        //             name: 'max_price',
        //             searchable: false
        //         },
        //         {
        //             data: 'current_stock',
        //             searchable: false
        //         },
        //         {
        //             data: 'sku',
        //             name: 'products.sku'
        //         },
        //         {
        //             data: 'amazon_asin',
        //             name: 'products.amazon_asin'
        //         },
        //     ],
        // });

        $('table#walmart_table tbody').on('click', 'a.delete-product', function(e) {
            e.preventDefault();
            swal({
                title: LANG.sure,
                icon: "warning",
                buttons: true,
                dangerMode: true,
            }).then((willDelete) => {
                if (willDelete) {
                    var href = $(this).attr('href');
                    $.ajax({
                        method: "DELETE",
                        url: href,
                        dataType: "json",
                        beforeSend: function() {
                            $('#pos-loader').css('display', 'inline-flex')
                        },
                        success: function(result) {
                            $('#pos-loader').css('display', 'none')
                            if (result.success == true) {
                                toastr.success(result.msg);
                                shopify_table.ajax.reload();
                            } else {
                                toastr.error(result.msg);
                            }
                        }
                    });
                }
            });
        });

        $(document).on('click', '#delete-selected-walmart', function(e) {
            e.preventDefault();
            var selected_rows = getSelectedRows();

            if (selected_rows.length > 0) {
                $('input#selected_rows_walmart').val(selected_rows);
                swal({
                    title: LANG.sure,
                    icon: "warning",
                    buttons: true,
                    dangerMode: true,
                }).then((willDelete) => {
                    if (willDelete) {
                        $('#pos-loader').css('display', 'inline-flex');
                        $('form#mass_delete_form_walmart').submit();
                    }
                });
            } else {
                $('input#selected_rows_walmart').val('');
                swal('@lang("lang_v1.no_row_selected")');
            }
        });

        $('#walmart_test_btn').click(function() {
            //PALIGU
            // console.log('shopify test');
            $.ajax({
                method: 'GET',
                url: '/check-location-have-products',
                dataType: 'json',
                data: {
                    location_id: $('#product_locations_walmart').val(),
                    type: 'walmart'
                },
                beforeSend: function() {
                    $('#pos-loader').css('display', 'inline-flex')
                },
                success: function(result) {
                    $('#pos-loader').css('display', 'none')
                    if (result.rc == 1) {
                        swal({
                            title: 'Information',
                            text: "If you change WALMART product location from " + result.location + " to " + $('#product_locations_walmart').find('option:selected').text() + ", all product in " + result.location + " will be moved to " + $('#product_locations_walmart').find('option:selected').text() + "?",
                            icon: 'info',
                            buttons: {
                                cancel: "No",
                                confirm: "Yes"
                            },
                        }).then((confirmed) => {
                            if (confirmed) {
                                sync_walmart();
                            }
                        })
                    } else if (result.rc == 2) {
                        swal({
                            title: 'Information',
                            text: result.rm,
                            icon: 'info',
                            // button: false,
                        })
                    } else {
                        sync_walmart();
                    }
                }
            }).fail(function(xhr, status, q) {
                Pace.stop();
                $('#pos-loader').css('display', 'none')
                // consoole.log(xhr.responseText)
                swal({
                    title: 'Information',
                    text: xhr.responseText,
                    icon: 'info',
                    // button: false,
                })
            });
        });

        // setTimeout(() => {
        $('span.select2-container').css('width', '100%');
        // }, 200);

        table_hide('walmart')
    })

    
    function sync_walmart() {
        swal({
            title: 'Information',
            text: 'This Process May Take littler longer than regular sync process, Please do not CLOSE or REFRESH your browser during this process.',
            icon: 'info',
            buttons: {
                cancel: "CANCEL",
                confirm: "START SYNC"
            },
        }).then((confirmed) => {
            if (confirmed) {
                $.ajax({
                    method: 'GET',
                    url: '/walmart-auth',
                    dataType: 'json',
                    data: {
                        product_locations: $('#product_locations_walmart').val(),
                        checkmarks: $("input[name='checkmarks_walmart[]']:checked").serializeArray()
                    },
                    beforeSend: function() {
                        $('#pos-loader').css('display', 'inline-flex')
                        // swal('Information', 'This process may take litle bit long time, please do not close or refresh the browser', 'info')
                    },
                    success: function(result) {
                        Pace.stop();
                        $('#pos-loader').css('display', 'none')
                        // console.log(result)
                        var message = '<p>' + result.message;
                        var icon = 'info'
                        var title = 'Information'
                        if (result.data) {
                            var inserted = 0;
                            var updated = 0;
                            $.each(result.data, function(k, v) {
                                $.each(v, function(k1, v1) {
                                    // console.log(v1)
                                    if (v1.status == 2) {
                                        updated++;
                                    } else {
                                        inserted++;
                                    }
                                })
                            })

                            message += '<br>' + inserted + ' Products Imported and Created <br>' + updated + ' Products Updated and Synced</p>';

                            icon = 'success'
                            title = 'Success'
                        }
                        var msg = document.createElement('div');
                        msg.innerHTML = message;
                        swal({
                            title: title,
                            content: msg,
                            icon: icon,
                            // buttons: true,
                            dangerMode: true,
                        })
                        walmart_table.ajax.reload();
                    },
                }).fail(function(xhr, status, q) {
                    Pace.stop();
                    $('#pos-loader').css('display', 'none')
                    // alert(xhr.responseText)            
                    swal({
                        title: 'Information',
                        text: xhr.responseText,
                        icon: 'info',
                        // buttons: false,
                    })
                });
                //Commented by Paligu
            }
        });
    }
    ///////////////////////////////////
    function sync_etsy() {
        swal({
            title: 'Information',
            text: 'This Process May Take littler longer than regular sync process, Please do not CLOSE or REFRESH your browser during this process.',
            icon: 'info',
            buttons: {
                cancel: "CANCEL",
                confirm: "START SYNC"
            },
        }).then((confirmed) => {
            if (confirmed) {
                $.ajax({
                    method: 'GET',
                    url: '/etsy-auth',
                    dataType: 'json',
                    // data: {
                    //     product_locations: $('#product_locations_walmart').val(),
                    //     checkmarks: $("input[name='checkmarks_walmart[]']:checked").serializeArray()
                    // },
                    beforeSend: function() {
                        $('#pos-loader').css('display', 'inline-flex')
                        // swal('Information', 'This process may take litle bit long time, please do not close or refresh the browser', 'info')
                    },
                    success: function(result) {
                        Pace.stop();
                        $('#pos-loader').css('display', 'none')
                        // console.log(result)
                        var message = '<p>' + result.message + '</p>';
                        var icon = 'info'
                        var title = 'Information'
                        // if(result.data) {
                        //     var inserted = 0;
                        //     var updated = 0;
                        //     $.each(result.data, function(k, v) {
                        //         $.each(v, function(k1, v1) {
                        //             // console.log(v1)
                        //             if(v1.status == 2) {
                        //                 updated++;
                        //             } else {
                        //                 inserted++;
                        //             }                        
                        //         })
                        //     })

                        //     message+= '<br>' + inserted + ' Products Imported and Created <br>' + updated + ' Products Updated and Synced</p>';

                        //     icon = 'success'
                        //     title = 'Success'
                        // } 
                        var msg = document.createElement('div');
                        msg.innerHTML = message;
                        swal({
                            title: title,
                            content: msg,
                            icon: icon,
                            // buttons: true,
                            dangerMode: true,
                        })
                        //walmart_table.ajax.reload();
                    },
                }).fail(function(xhr, status, q) {
                    Pace.stop();
                    $('#pos-loader').css('display', 'none')
                    // alert(xhr.responseText)            
                    swal({
                        title: 'Information',
                        text: xhr.responseText,
                        icon: 'info',
                        // buttons: false,
                    })
                });
                //Commented by Paligu
            }
        });
    }
    ///////////////////////////////////
    function sync_amazon() {
        swal({
            title: 'Information',
            text: 'This Process May Take littler longer than regular sync process, Please do not CLOSE or REFRESH your browser during this process.',
            icon: 'info',
            buttons: {
                cancel: "CANCEL",
                confirm: "START SYNC"
            },
        }).then((confirmed) => {
            if (confirmed) {
                $.ajax({
                    method: 'GET',
                    url: '/amazon-auth',
                    dataType: 'json',
                    data: {
                        product_locations: $('#product_locations_amazon').val(),
                        checkmarks: $("input[name='checkmarks_amazon[]']:checked").serializeArray()
                    },
                    beforeSend: function() {
                        $('#pos-loader').css('display', 'inline-flex')
                        // swal('Information', 'This process may take litle bit long time, please do not close or refresh the browser', 'info')
                    },
                    success: function(result) {
                        Pace.stop();
                        $('#pos-loader').css('display', 'none')
                        // console.log(result)
                        var message = '<p>' + result.message;
                        var icon = 'info'
                        var title = 'Information'
                        /* if(result.data) {
                            var inserted = 0;
                            var updated = 0;
                            $.each(result.data, function(k, v) {
                                $.each(v, function(k1, v1) {
                                    // console.log(v1)
                                    if(v1.status == 2) {
                                        updated++;
                                    } else {
                                        inserted++;
                                    }                        
                                })
                            })
    
                            message+= '<br>' + inserted + ' Products Imported and Created <br>' + updated + ' Products Updated and Synced</p>';
    
                            icon = 'success'
                            title = 'Success'
                        }  */
                        var msg = document.createElement('div');
                        msg.innerHTML = message;
                        swal({
                            title: title,
                            content: msg,
                            icon: icon,
                            // buttons: true,
                            dangerMode: true,
                        })
                        // amazon_table.ajax.reload();
                    },
                }).fail(function(xhr, status, q) {
                    Pace.stop();
                    $('#pos-loader').css('display', 'none')
                    // alert(xhr.responseText)            
                    swal({
                        title: 'Information',
                        text: xhr.responseText,
                        icon: 'info',
                        // buttons: false,
                    })
                });
                //Commented by Paligu
            }
        });
    }

    function getAmazonProductData(inputString, sellerId) {
        //inputString = '0062507109';
        url = '/amazon/getProductDetails/' + inputString + '/true/' + sellerId;
        console.log(url);
        $.ajax({
            method: 'GET',
            url: url,
            dataType: 'json',
            success: function(result) {

                var product = result;

                let largestImage = product.Images.reduce((largest, image) => {
                    return (image.width * image.height > largest.width * largest.height) ? image : largest;
                }, product.Images[0]);

                var html = `
                    <div style="max-width: 100%; padding: 10px;">
                        <table style="width: 100%; border-collapse: collapse; font-family: Arial, sans-serif;">
                            <tbody>
                                <tr><th style="text-align: left; padding: 8px; background: #f2f2f2;">ASIN</th><td style="padding: 8px;">${product.ASIN}</td></tr>
                                <tr><th style="text-align: left; padding: 8px; background: #f2f2f2;">Title</th><td style="padding: 8px;">${product.Title}</td></tr>
                                <tr><th style="text-align: left; padding: 8px; background: #f2f2f2;">Binding</th><td style="padding: 8px;">${product.Binding}</td></tr>
                                <tr><th style="text-align: left; padding: 8px; background: #f2f2f2;">Publication Date</th><td style="padding: 8px;">${product.PublicationDate}</td></tr>
                                <tr><th style="text-align: left; padding: 8px; background: #f2f2f2;">Release Date</th><td style="padding: 8px;">${product.ReleaseDate}</td></tr>
                                <tr><th style="text-align: left; padding: 8px; background: #f2f2f2;">Pages</th><td style="padding: 8px;">${product.Pages}</td></tr>
                                <tr><th style="text-align: left; padding: 8px; background: #f2f2f2;">Target Audience</th><td style="padding: 8px;">${product.TargetAudience}</td></tr>
                                <tr><th style="text-align: left; padding: 8px; background: #f2f2f2;">Price</th><td style="padding: 8px; color: green; font-weight: bold;">${product.Price}</td></tr>
                                <tr><th style="text-align: left; padding: 8px; background: #f2f2f2;">Authors</th><td style="padding: 8px;">${product.Authors.join(', ')}</td></tr>
                                <tr>
                                    <th style="text-align: left; padding: 8px; background: #f2f2f2;">Classification Ranks</th>
                                    <td style="padding: 8px;">
                                        ${product.ClassificationRanks.map(rank => 
                                            `<span style="display: block; font-size: 14px; color: #555;">
                                                <a href="${rank.link}" target="_blank" style="color: #0073e6; text-decoration: none;">
                                                    <strong>${rank.title}</strong>
                                                </a> (Rank: #${rank.rank})
                                            </span>`).join('')}
                                    </td>
                                </tr>
                                <tr>
                                    <th style="text-align: left; padding: 8px; background: #f2f2f2;">Image</th>
                                    <td style="padding: 8px; text-align: center;">
                                        <a href="${largestImage.link}" target="_blank">
                                            <img src="${largestImage.link}" style="max-width: auto; height: 200px; border-radius: 5px; box-shadow: 2px 2px 5px rgba(0,0,0,0.2); cursor: pointer;" title="Click to open in new tab">
                                        </a>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                `;

                let existsInDbText = result.ExistsInDb ? '' : '\nThis product is not listed in your store!';

                swal({
                    title: '📦 Product Details',
                    text: "Here is the information about the scanned product." + existsInDbText,
                    content: $(html)[0], // Ensures the HTML content is properly displayed
                    buttons: {
                        cancel: "Close",
                        ...(result.ExistsInDb ? {} : {
                            listProduct: {
                                text: "📋 List in My Store",
                                value: "list",
                                className: "swal-button--list"
                            },
                            addToWishList: {
                                text: "⭐ Add to Wish List",
                                value: "wish",
                                className: "swal-button--wishlist"
                            }
                        })
                    },
                    className: 'swal-wide' // Custom class to make the popup wider
                }).then((value) => {
                    if (value === "list") {
                        listProductInStore(product);
                    } else if (value === "wish") {
                        addToWishList(product);
                    }
                });

                // Add custom styles to make the swal popup wider
                var style = document.createElement('style');
                style.innerHTML = `
                    .swal-wide {
                        width: 80% !important;
                        max-width: 800px !important;
                    }
                    .swal-button--list {
                        background-color: #0073e6 !important;
                        color: white !important;
                    }
                    .swal-button--wishlist {
                        background-color: #00b7ff !important;
                        color: white !important;
                    }
                `;
                document.head.appendChild(style);
            },
            error: function(xhr, status, error) {
                swal({
                    title: 'Product Not Found',
                    text: 'Unfortunately, we were unable to locate the product on Amazon.',
                    icon: 'error',
                    button: 'OK'
                });
            }
        });
    }

    function get_input(val, tipe) {
        if (val == '1') {
            if (tipe == 'bigcommerce') {
                // bigcommerce
                $('#etsy_api_url').css('display', 'block')
                $('#etsy_api_access_token').css('display', 'block')
                $('#etsy_api_key').css('display', 'block')
                $('#etsy_api_secret').css('display', 'block')
                $('#etsy_space').addClass('col-sm-3')
            }
            if (tipe == 'amazon') {
                // amazon
                $('#amazon_api_url').css('display', 'block')
                $('#amazon_api_access_token').css('display', 'block')
                $('#amazon_api_key').css('display', 'block')
                $('#amazon_api_secret').css('display', 'block')
                $('#amazon_space').addClass('col-sm-3')
            }
            if (tipe == 'walmart') {
                // woo commerce
                $('#walmart_api_url').css('display', 'block')
                $('#walmart_api_access_token').css('display', 'block')
                $('#walmart_api_key').css('display', 'block')
                $('#walmart_api_secret').css('display', 'block')
                $('#walmart_space').addClass('col-sm-3')
            }
            if (tipe == 'ebay') {
                // ebay
                $('#ebay_api_url').css('display', 'block')
                $('#ebay_api_access_token').css('display', 'block')
                $('#ebay_api_key').css('display', 'block')
                $('#ebay_api_secret').css('display', 'block')
                $('#ebay_space').addClass('col-sm-3')
            }
        } else {
            if (tipe == 'bigcommerce') {
                // big commerce
                $('#etsy_api_url').css('display', 'none')
                $('#etsy_api_access_token').css('display', 'none')
                $('#etsy_api_key').css('display', 'none')
                $('#etsy_api_secret').css('display', 'none')
                $('#etsy_space').removeClass('col-sm-3')
            }
            if (tipe == 'amazon') {
                // amazon
                $('#amazon_api_url').css('display', 'none')
                $('#amazon_api_access_token').css('display', 'none')
                $('#amazon_api_key').css('display', 'none')
                $('#amazon_api_secret').css('display', 'none')
                $('#amazon_space').removeClass('col-sm-3')
            }
            if (tipe == 'walmart') {
                // woo commerce
                $('#walmart_api_url').css('display', 'none')
                $('#walmart_api_access_token').css('display', 'none')
                $('#walmart_api_key').css('display', 'none')
                $('#walmart_api_secret').css('display', 'none')
                $('#walmart_space').removeClass('col-sm-3')
            }
            if (tipe == 'ebay') {
                // ebay
                $('#ebay_api_url').css('display', 'none')
                $('#ebay_api_access_token').css('display', 'none')
                $('#ebay_api_key').css('display', 'none')
                $('#ebay_api_secret').css('display', 'none')
                $('#ebay_space').removeClass('col-sm-3')
            }
        }
    }

    function getOption(type, val, order) {
        if (val == 1 && type == 1) {
            $('#option_marketplace_collapse_' + order).css('display', 'block')
            // $('#option_marketplace_collapse_amazon_1').css('display', 'block')            
        } else if (val == 0 && type == 1) {
            $('#option_marketplace_collapse_' + order).css('display', 'none')
            // $('#option_marketplace_collapse_amazon_1').css('display', 'none') 
            $('#checkmarks_marketplace_11').removeAttr('checked');
            $('#checkmarks_marketplace_12').removeAttr('checked');
            $('#checkmarks_marketplace_13').removeAttr('checked');
            $('#checkmarks_marketplace_14').removeAttr('checked');
        }

        if (val == 1 && type == 2) {
            $('#option_marketplace_collapse_' + order).css('display', 'block')
        } else if (val == 0 && type == 2) {
            $('#option_marketplace_collapse_' + order).css('display', 'none')
            $('#checkmarks_marketplace_21').removeAttr('checked');
            $('#checkmarks_marketplace_22').removeAttr('checked');
            $('#checkmarks_marketplace_23').removeAttr('checked');
            $('#checkmarks_marketplace_24').removeAttr('checked');
        }
    }

    function getOptionAmazon(type, val, order) {
        if (val == 1 && type == 1) {
            // $('#option_marketplace_collapse_amazon_' + order).css('display', 'block')            
            $('#option_marketplace_collapse_amazon_1').css('display', 'block')
        } else if (val == 0 && type == 1) {
            // $('#option_marketplace_collapse_amazon_' + order).css('display', 'none') 
            $('#option_marketplace_collapse_amazon_1').css('display', 'none')
            $('#checkmarks_marketplace_amazon_11').removeAttr('checked');
            $('#checkmarks_marketplace_amazon_12').removeAttr('checked');
            $('#checkmarks_marketplace_amazon_13').removeAttr('checked');
            $('#checkmarks_marketplace_amazon_14').removeAttr('checked');
        }

        if (val == 1 && type == 2) {
            $('#option_marketplace_collapse_amazon_2').css('display', 'block')
            // $('#option_marketplace_collapse_amazon_' + order).css('display', 'block')            
        } else if (val == 0 && type == 2) {
            $('#option_marketplace_collapse_amazon_2').css('display', 'none')
            // $('#option_marketplace_collapse_amazon_' + order).css('display', 'none')            
            $('#checkmarks_marketplace_amazon_21').removeAttr('checked');
            $('#checkmarks_marketplace_amazon_22').removeAttr('checked');
            $('#checkmarks_marketplace_amazon_23').removeAttr('checked');
            $('#checkmarks_marketplace_amazon_24').removeAttr('checked');
        }
    }

    function table_hide(x) {
        $('.table_hide').addClass('hide');
        $('.' + x + '_table').removeClass('hide');
        $('.btn-sync').addClass('hide');
        var btn = $('#' + x + '_test_btn');
        if (btn.length) {
            btn.removeClass('hide');
        }
    }

    function importFile(e) {
        e.preventDefault();
        var form = document.getElementById('omni_edit_form');
        var formData = new FormData(form);
        $.ajax({
            type: 'POST',
            url: '/keepa/import',
            data: formData,
            processData: false, // tell jQuery not to process the data
            contentType: false, // tell jQuery not to set contentType
            // enctype: 'multipart/form-data',
            headers: {
                "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content")
            },
            beforeSend: function() {
                $('#pos-loader').css('display', 'inline-flex')
                // swal('Information', 'This process may take litle bit long time, please do not close or refresh the browser', 'info')
            },
            success: function(result) {
                Pace.stop();
                $('#pos-loader').css('display', 'none')
                swal({
                    title: 'Information',
                    text: result.message,
                    icon: 'info',
                    // buttons: false,
                })
            },
        }).fail(function(xhr, status, q) {
            Pace.stop();
            $('#pos-loader').css('display', 'none')
            // alert(xhr.responseText)            
            swal({
                title: 'Information',
                text: xhr.responseText,
                icon: 'info',
                // buttons: false,
            })
        });
    }

    function createCompetitivePricesToDb(seller_id, asin, element) {
        var closest_tr = $(element).closest("tr");
        $.ajax({
            type: 'POST',
            url: '/amazon/createCompetitivePricesToDb?credit=-5',
            data: {
                seller_id: seller_id,
                asin: asin,
            },
            // enctype: 'multipart/form-data',
            headers: {
                "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content")
            },
            beforeSend: function() {
                $('#pos-loader').css('display', 'inline-flex')
                // swal('Information', 'This process may take litle bit long time, please do not close or refresh the browser', 'info')
            },
            success: function(result) {
                // Pace.stop();
                $('#pos-loader').css('display', 'none')
                if (result.error) {
                    swal({
                        title: 'Information',
                        text: result.error,
                        icon: 'info',
                        // buttons: false,
                    })
                    setTimeout(() => {
                        $('#refresh-competitive-price').removeAttr('disabled');
                    }, 2000);
                } else {
                    swal({
                        title: 'Information',
                        text: result.message,
                        icon: 'info',
                        // buttons: false,
                    })
                    if (amazon_sellers.length > 0) {
                        $.each(amazon_sellers, function(k, v) {
                            tables['amazon_table_' + (k + 1)].ajax.reload();
                        })
                    }
                    $(closest_tr).click();
                    setTimeout(() => {
                        $('#refresh-competitive-price').attr('disabled', true);
                    }, 2000);
                    setTimeout(() => {
                        $('#refresh-competitive-price').removeAttr('disabled');
                    }, 30000);
                }
            },
        }).fail(function(xhr, status, q) {
            Pace.stop();
            $('#pos-loader').css('display', 'none')
            // alert(xhr.responseText)            
            swal({
                title: 'Information',
                text: xhr.responseText,
                icon: 'info',
                // buttons: false,
            })
        });
    }

    function refreshCompetitivePrice(seller_id, asin, id) {
        $('.view_modal').modal('hide');
        $('.view_modal').html('');
        createCompetitivePricesToDb(seller_id, asin, null)
        setTimeout(() => {
            $.ajax({
                url: baseUrl + '/amazon/product/preview/modal/' + id,
                dataType: 'html',
                success: function(result) {
                    // console.log(result);
                    $('.view_modal')
                        .html(result)
                        .modal('show');
                    $('#refresh-competitive-price').attr('disabled', true);
                },
            });
        }, 1000);
        setTimeout(() => {
            $('#refresh-competitive-price').removeAttr('disabled');
        }, 30000);
    }

    function getSellerPerformanceReport(seller_id) {
        $.ajax({
            method: 'GET',
            url: baseUrl + '/amazon/checkDashboard/' + seller_id + '?credit=-10',
            dataType: 'json',
            beforeSend: function() {
                $('#lateShipmentTarget').html('Loading ...');
                $('#lateShipmentRate').html('Loading ...');
                $('#orderDefectTargetAFN').html('Loading ...');
                $('#orderDefectRateAFN').html('Loading ...');
                $('#orderDefectTargetMFN').html('Loading ...');
                $('#orderDefectRateMFN').html('Loading ...');
                $('#onTimeDeliveryTarget').html('Loading ...');
                $('#onTimeDeliveryRate').html('Loading ...');
                // $('#pos-loader').css('display', 'inline-flex')
                // swal('Information', 'This process may take litle bit long time, please do not close or refresh the browser', 'info')
                $('#amazon-dashboard-button').attr('disabled', true);

                setTimeout(() => {
                    $('#amazon-dashboard-button').removeAttr('disabled');
                }, 60000);
            },
            success: function(result) {
                if (result.coming_from == 'database') {
                    $('#amazon-dashboard-button').removeAttr('disabled');
                }
                var performance_metrics = result.performance_metrics;
                $('#pos-loader').css('display', 'none')
                if (performance_metrics.error) {
                    $('#amazon-dashboard-button').removeAttr('disabled');
                    $('#lateShipmentTarget').html('0%');
                    $('#lateShipmentRate').html('0%');
                    $('#orderDefectTargetAFN').html('0%');
                    $('#orderDefectRateAFN').html('0%');
                    $('#orderDefectTargetMFN').html('0%');
                    $('#orderDefectRateMFN').html('0%');
                    $('#onTimeDeliveryTarget').html('0%');
                    $('#onTimeDeliveryRate').html('0%');
                    swal({
                        title: 'Information',
                        text: performance_metrics.error,
                        icon: 'info',
                        // buttons: false,
                    })
                    $('#updated_at_dashboard').html('Updated at: -')
                } else {
                    var lateShipmentTarget = performance_metrics.lateShipmenttargetValue * 100;
                    var lateShipmentRate = performance_metrics.lateShipmentRate * 100;
                    var orderDefectTargetAFN = performance_metrics.orderDefectRateAfnTargetValue * 100;
                    var orderDefectRateAFN = performance_metrics.orderDefectRateAfnRate * 100;
                    var orderDefectTargetMFN = performance_metrics.orderDefectRateMfnTargetValue * 100;
                    var orderDefectRateMFN = performance_metrics.orderDefectRateMfnRate * 100;
                    var onTimeDeliveryTarget = performance_metrics.onTimeDeliveryRateTargetValue * 100;
                    var onTimeDeliveryRate = performance_metrics.onTimeDeliveryRate * 100;

                    $('#lateShipmentTarget').html(parseFloat(lateShipmentTarget).toFixed(0) + '%');
                    $('#lateShipmentRate').html(parseFloat(lateShipmentRate).toFixed(0) + '%');
                    $('#orderDefectTargetAFN').html(parseFloat(orderDefectTargetAFN).toFixed(0) + '%');
                    $('#orderDefectRateAFN').html(parseFloat(orderDefectRateAFN).toFixed(0) + '%');
                    $('#orderDefectTargetMFN').html(parseFloat(orderDefectTargetMFN).toFixed(0) + '%');
                    $('#orderDefectRateMFN').html(parseFloat(orderDefectRateMFN).toFixed(0) + '%');
                    $('#onTimeDeliveryTarget').html(parseFloat(onTimeDeliveryTarget).toFixed(0) + '%');
                    $('#onTimeDeliveryRate').html(parseFloat(onTimeDeliveryRate).toFixed(0) + '%');

                    if (result.coming_from == 'database') {
                        updated_at = result.updated_at ? result.updated_at : '-'
                        last_date_updated_at = result.last_date_updated_at ? result.last_date_updated_at : '-'
                    } else {
                        updated_at = performance_metrics.updated_at ? performance_metrics.updated_at : '-'
                        last_date_updated_at = result.last_date_updated_at ? result.last_date_updated_at : '-'
                    }
                    $('#updated_at_dashboard').html('Updated at: ' + updated_at)
                    $('#last_date_updated_at_sales').html(last_date_updated_at)
                    $('#last_date_updated_at_traffic').html(last_date_updated_at)
                }
            },
        }).fail(function(xhr, status, q) {
            $('#pos-loader').css('display', 'none')
            $('#lateShipmentTarget').html('0%');
            $('#lateShipmentRate').html('0%');
            $('#orderDefectTargetAFN').html('0%');
            $('#orderDefectRateAFN').html('0%');
            $('#orderDefectTargetMFN').html('0%');
            $('#orderDefectRateMFN').html('0%');
            $('#onTimeDeliveryTarget').html('0%');
            $('#onTimeDeliveryRate').html('0%');
            // alert(xhr.responseText)            
            swal({
                title: 'Information',
                text: xhr.responseText,
                icon: 'info',
                // buttons: false,
            })
        });
    }

    function updateSellerPerformanceReport(seller_id) {
        $.ajax({
            method: 'GET',
            url: baseUrl + '/amazon/requestSellerPerformanceReport/' + seller_id + '?credit=-10',
            dataType: 'json',
            beforeSend: function() {
                $('#lateShipmentTarget').html('Loading ...');
                $('#lateShipmentRate').html('Loading ...');
                $('#orderDefectTargetAFN').html('Loading ...');
                $('#orderDefectRateAFN').html('Loading ...');
                $('#orderDefectTargetMFN').html('Loading ...');
                $('#orderDefectRateMFN').html('Loading ...');
                $('#onTimeDeliveryTarget').html('Loading ...');
                $('#onTimeDeliveryRate').html('Loading ...');
                // $('#pos-loader').css('display', 'inline-flex')
                // swal('Information', 'This process may take litle bit long time, please do not close or refresh the browser', 'info')
                // $('#pos-loader').css('display', 'inline-flex')
                $('#amazon-dashboard-button').attr('disabled', true);

                setTimeout(() => {
                    $('#amazon-dashboard-button').removeAttr('disabled');
                }, 60000);
            },
            success: function(result) {
                if (result.updated_at) {
                    var updated_at = result.updated_at;
                    var last_date_updated_at = result.last_date_updated_at;
                }
                // $('#pos-loader').css('display', 'none')
                if (result.error) {
                    $('#pos-loader').css('display', 'none')
                    $('#lateShipmentTarget').html('0%');
                    $('#lateShipmentRate').html('0%');
                    $('#orderDefectTargetAFN').html('0%');
                    $('#orderDefectRateAFN').html('0%');
                    $('#orderDefectTargetMFN').html('0%');
                    $('#orderDefectRateMFN').html('0%');
                    $('#onTimeDeliveryTarget').html('0%');
                    $('#onTimeDeliveryRate').html('0%');
                    $('#amazon-dashboard-button').removeAttr('disabled');
                    swal({
                        title: 'Information',
                        text: result.error,
                        icon: 'info',
                        // buttons: false,
                    })
                } else {
                    var lateShipmentTarget = result.lateShipmenttargetValue * 100;
                    var lateShipmentRate = result.lateShipmentRate * 100;
                    var orderDefectTargetAFN = result.orderDefectRateAfnTargetValue * 100;
                    var orderDefectRateAFN = result.orderDefectRateAfnRate * 100;
                    var orderDefectTargetMFN = result.orderDefectRateMfnTargetValue * 100;
                    var orderDefectRateMFN = result.orderDefectRateMfnRate * 100;
                    var onTimeDeliveryTarget = result.onTimeDeliveryRateTargetValue * 100;
                    var onTimeDeliveryRate = result.onTimeDeliveryRate * 100;

                    $('#lateShipmentTarget').html(parseFloat(lateShipmentTarget).toFixed(0) + '%');
                    $('#lateShipmentRate').html(parseFloat(lateShipmentRate).toFixed(0) + '%');
                    $('#orderDefectTargetAFN').html(parseFloat(orderDefectTargetAFN).toFixed(0) + '%');
                    $('#orderDefectRateAFN').html(parseFloat(orderDefectRateAFN).toFixed(0) + '%');
                    $('#orderDefectTargetMFN').html(parseFloat(orderDefectTargetMFN).toFixed(0) + '%');
                    $('#orderDefectRateMFN').html(parseFloat(orderDefectRateMFN).toFixed(0) + '%');
                    $('#onTimeDeliveryTarget').html(parseFloat(onTimeDeliveryTarget).toFixed(0) + '%');
                    $('#onTimeDeliveryRate').html(parseFloat(onTimeDeliveryRate).toFixed(0) + '%');

                    salesAndTrafficReportApi(seller_id);

                    $('#updated_at_dashboard').html('Updated at: ' + updated_at)
                    $('#last_date_updated_at_sales').html('Updated at: ' + last_date_updated_at)
                    $('#last_date_updated_at_traffic').html('Updated at: ' + last_date_updated_at)
                }
            },
        }).fail(function(xhr, status, q) {
            $('#pos-loader').css('display', 'none')
            $('#lateShipmentTarget').html('0%');
            $('#lateShipmentRate').html('0%');
            $('#orderDefectTargetAFN').html('0%');
            $('#orderDefectRateAFN').html('0%');
            $('#orderDefectTargetMFN').html('0%');
            $('#orderDefectRateMFN').html('0%');
            $('#onTimeDeliveryTarget').html('0%');
            $('#onTimeDeliveryRate').html('0%');
            // alert(xhr.responseText)            
            swal({
                title: 'Information',
                text: xhr.responseText,
                icon: 'info',
                // buttons: false,
            })
        });
    }

    function salesAndTrafficReportApi(seller_id) {
        var aggregate_by = $('#aggregate_by').val();
        var first_date = $("#first_date_sales_traffic").val();
        var last_date = $("#today_sales_traffic").val();
        $.ajax({
            method: 'GET',
            url: baseUrl + '/amazon/salesAndTrafficByDate/' + seller_id + '/' + first_date + '/' + last_date + '/' + aggregate_by,
            dataType: 'json',
            beforeSend: function() {
                $('#pos-loader').css('display', 'inline-flex')
                $('#sales_order_product_amount').html('-')
                $('#sales_order_shipped').html('-')
                $('#sales_average_sales_per_order').html('-')
                $('#sales_average_selling_price').html('-')
                $('#sales_refund_rate').html('-')
                $('#sales_browser_page_views').html('-')
                $('#sales_mobile_app_page_views').html('-')
                $('#sales_buy_box_percentage').html('-')
                $('#sales_feedback_received').html('-')
                $('#sales_negative_feedback').html('-')
            },
            success: function(result) {
                $('#pos-loader').css('display', 'none')
                $('.view_modal').modal('hide');
                if (result.error) {
                    swal({
                        title: 'Information',
                        text: result.error,
                        icon: 'info',
                        // buttons: false,
                    })
                } else {
                    $('#sales_order_product_amount').html(result.sales.orderedProductSales.amount)
                    $('#sales_order_shipped').html(result.sales.orderShipped)
                    $('#sales_average_sales_per_order').html(result.sales.averageSalesPerOrderItem.amount)
                    $('#sales_average_selling_price').html(result.sales.averageSellingPrice.amount)
                    $('#sales_refund_rate').html(result.sales.refundRate)
                    $('#sales_browser_page_views').html(result.traffic.browserPageViews)
                    $('#sales_mobile_app_page_views').html(result.traffic.mobileAppPageViews)
                    $('#sales_buy_box_percentage').html(result.traffic.buyBoxPercentage)
                    $('#sales_feedback_received').html(result.traffic.feedbackReceived)
                    $('#sales_negative_feedback').html(result.traffic.negativeFeedbackReceived)
                }
            },
        }).fail(function(xhr, status, q) {
            $('#sales_order_product_amount').html('-')
            $('#sales_order_shipped').html('-')
            $('#sales_average_sales_per_order').html('-')
            $('#sales_average_selling_price').html('-')
            $('#sales_refund_rate').html('-')
            $('#sales_browser_page_views').html('-')
            $('#sales_mobile_app_page_views').html('-')
            $('#sales_buy_box_percentage').html('-')
            $('#sales_feedback_received').html('-')
            $('#sales_negative_feedback').html('-')
            $('.view_modal').modal('hide');
            $('#pos-loader').css('display', 'none')
            // alert(xhr.responseText)            
            swal({
                title: 'Information',
                text: xhr.responseText,
                icon: 'info',
                // buttons: false,
            })
        });
    }

    function updateSellerListingQuantityModal(store, sku, title, qty) {
        var title = title.replace(/\\'/g, /'/g);
        $.ajax({
            url: baseUrl + '/amazon/update-listing/modal/' + store + '/' + sku + '/' + title + '?old_qty=' + qty + '&type=qty',
            dataType: 'html',
            success: function(result) {
                // console.log(result);
                $('.view_modal')
                    .html(result)
                    .modal('show');
                $('#refresh-competitive-price').attr('disabled', true);
            },
        });
    }

    function updateListingQuantityApi(e) {
        e.preventDefault();
        var sellerId = $('#sellerId').val()
        var sku = $('#sku').val()
        var quantity = $('#quantity').val()
        $.ajax({
            method: 'GET',
            url: baseUrl + '/amazon/updateSellerListingQuantity/' + sellerId + '/' + sku + '/' + quantity + '?credit=-10',
            dataType: 'json',
            beforeSend: function() {
                $('#pos-loader').css('display', 'inline-flex')
            },
            success: function(result) {
                $('#pos-loader').css('display', 'none')
                $('.view_modal').modal('hide');
                if (result.error) {
                    swal({
                        title: 'Information',
                        text: result.error,
                        icon: 'info',
                        // buttons: false,
                    })
                } else {
                    var icon = result.status == 'INVALID' ? 'error' : 'success';
                    var title = result.status == 'INVALID' ? 'Failed' : 'Information';
                    var issues = '';
                    if (result.issues.length > 0) {
                        issues = '-' + result.issues[0].message;
                    }
                    message = 'INVALID ';
                    if (result.status == "ACCEPTED") {
                        message = 'Update Listing Quantity Successfully';
                        if (amazon_sellers.length > 0) {
                            $.each(amazon_sellers, function(k, v) {
                                tables['amazon_table_' + (k + 1)].ajax.reload();
                            })
                        }
                    }
                    swal({
                        title: title,
                        text: message + issues,
                        icon: icon,
                        // buttons: false,
                    })
                }
            },
        }).fail(function(xhr, status, q) {
            $('.view_modal').modal('hide');
            $('#pos-loader').css('display', 'none')
            // alert(xhr.responseText)            
            swal({
                title: 'Information',
                text: xhr.responseText,
                icon: 'info',
                // buttons: false,
            })
        });
    }

    function updatePriceModal(store, sku, title, price) {
        var title = title.replace(/\\'/g, /'/g);
        $.ajax({
            url: baseUrl + '/amazon/update-listing/modal/' + store + '/' + sku + '/' + title + '?old_price=' + price + '&type=price',
            dataType: 'html',
            success: function(result) {
                // console.log(result);
                $('.view_modal')
                    .html(result)
                    .modal('show');
                $('#refresh-competitive-price').attr('disabled', true);
            },
        });
    }

    function updateListingPriceApi(e) {
        e.preventDefault();
        var sellerId = $('#sellerId').val()
        var sku = $('#sku').val()
        var price = $('#price').val()
        $.ajax({
            method: 'GET',
            url: baseUrl + '/amazon/updateSellerListingPrice/' + sellerId + '/' + sku + '/' + price + '?credit=-10',
            dataType: 'json',
            beforeSend: function() {
                $('#pos-loader').css('display', 'inline-flex')
            },
            success: function(result) {
                $('#pos-loader').css('display', 'none')
                $('.view_modal').modal('hide');
                if (result.error) {
                    swal({
                        title: 'Information',
                        text: result.error,
                        icon: 'info',
                        // buttons: false,
                    })
                } else {
                    var icon = result.status == 'INVALID' ? 'error' : 'success';
                    var title = result.status == 'INVALID' ? 'Failed' : 'Information';
                    var issues = '';
                    if (result.issues.length > 0) {
                        issues = '-' + result.issues[0].message;
                    }
                    message = 'INVALID ';
                    if (result.status == "ACCEPTED") {
                        message = 'Update Listing Price Successfully';
                        if (amazon_sellers.length > 0) {
                            $.each(amazon_sellers, function(k, v) {
                                tables['amazon_table_' + (k + 1)].ajax.reload();
                            })
                        }
                    }
                    swal({
                        title: title,
                        text: message + issues,
                        icon: icon,
                        // buttons: false,
                    })
                }
            },
        }).fail(function(xhr, status, q) {
            $('.view_modal').modal('hide');
            $('#pos-loader').css('display', 'none')
            // alert(xhr.responseText)            
            swal({
                title: 'Information',
                text: xhr.responseText,
                icon: 'info',
                // buttons: false,
            })
        });
    }

    function updateConditionModal(store, sku, title, condition) {
        var title = title.replace(/\\'/g, /'/g);
        $.ajax({
            url: baseUrl + '/amazon/update-listing/modal/' + store + '/' + sku + '/' + title + '?old_condition=' + condition + '&type=condition',
            dataType: 'html',
            success: function(result) {
                // console.log(result);
                $('.view_modal')
                    .html(result)
                    .modal('show');
                $('#refresh-competitive-price').attr('disabled', true);
            },
        });
    }

    function updateListingConditionApi(e) {
        e.preventDefault();
        var sellerId = $('#sellerId').val()
        var sku = $('#sku').val()
        var condition = $('#condition').val()
        $.ajax({
            method: 'GET',
            url: baseUrl + '/amazon/updateSellerListingCondition/' + sellerId + '/' + sku + '/' + condition + '?credit=-10',
            dataType: 'json',
            beforeSend: function() {
                $('#pos-loader').css('display', 'inline-flex')
            },
            success: function(result) {
                $('#pos-loader').css('display', 'none')
                $('.view_modal').modal('hide');
                if (result.error) {
                    swal({
                        title: 'Information',
                        text: result.error,
                        icon: 'info',
                        // buttons: false,
                    })
                } else {
                    var icon = result.status == 'INVALID' ? 'error' : 'success';
                    var title = result.status == 'INVALID' ? 'Failed' : 'Information';
                    var issues = '';
                    if (result.issues.length > 0) {
                        issues = '-' + result.issues[0].message;
                    }
                    message = 'INVALID ';
                    if (result.status == "ACCEPTED") {
                        message = 'Update Listing Condition Successfully';
                        if (amazon_sellers.length > 0) {
                            $.each(amazon_sellers, function(k, v) {
                                tables['amazon_table_' + (k + 1)].ajax.reload();
                            })
                        }
                    }
                    swal({
                        title: title,
                        text: message + issues,
                        icon: icon,
                        // buttons: false,
                    })
                }
            },
        }).fail(function(xhr, status, q) {
            $('.view_modal').modal('hide');
            $('#pos-loader').css('display', 'none')
            // alert(xhr.responseText)            
            swal({
                title: 'Information',
                text: xhr.responseText,
                icon: 'info',
                // buttons: false,
            })
        });
    }

    function getSalesTrafficReport(sellerId) {
        var aggregate_by = $('#aggregate_by').val();
        var first_date = $("#first_date_sales_traffic").val();
        var last_date = $("#today_sales_traffic").val();
        $.ajax({
            method: 'GET',
            url: baseUrl + '/amazon/checkSalesAndTrafficReport/' + sellerId + '/' + first_date + '/' + last_date + '/' + aggregate_by,
            dataType: 'json',
            beforeSend: function() {
                $('#pos-loader').css('display', 'inline-flex')
                $('#sales_order_product_amount').html('-')
                $('#sales_order_shipped').html('-')
                $('#sales_average_sales_per_order').html('-')
                $('#sales_average_selling_price').html('-')
                $('#sales_refund_rate').html('-')
                $('#sales_browser_page_views').html('-')
                $('#sales_mobile_app_page_views').html('-')
                $('#sales_buy_box_percentage').html('-')
                $('#sales_feedback_received').html('-')
                $('#sales_negative_feedback').html('-')
            },
            success: function(result) {
                $('#pos-loader').css('display', 'none')
                $('.view_modal').modal('hide');
                if (result.error) {
                    swal({
                        title: 'Information',
                        text: result.error,
                        icon: 'info',
                        // buttons: false,
                    })
                } else {
                    if (result.coming_from == 'API') {
                        var report = result.data;
                        $('#sales_order_product_amount').html(report.sales.orderedProductSales.amount)
                        $('#sales_order_shipped').html(report.sales.orderShipped)
                        $('#sales_average_sales_per_order').html(report.sales.averageSalesPerOrderItem.amount)
                        $('#sales_average_selling_price').html(report.sales.averageSellingPrice.amount)
                        $('#sales_refund_rate').html(report.sales.refundRate)
                        $('#sales_browser_page_views').html(report.traffic.browserPageViews)
                        $('#sales_mobile_app_page_views').html(report.traffic.mobileAppPageViews)
                        $('#sales_buy_box_percentage').html(report.traffic.buyBoxPercentage)
                        $('#sales_feedback_received').html(report.traffic.feedbackReceived)
                        $('#sales_negative_feedback').html(report.traffic.negativeFeedbackReceived)
                    } else {
                        $('#sales_order_product_amount').html(result.data.ordered_product_sales)
                        $('#sales_order_shipped').html(result.data.orders_shipped)
                        $('#sales_average_sales_per_order').html(result.data.average_sales_per_order)
                        $('#sales_average_selling_price').html(result.data.average_selling_price)
                        $('#sales_refund_rate').html(result.data.refund_rate)
                        $('#sales_browser_page_views').html(result.data.browser_page_views)
                        $('#sales_mobile_app_page_views').html(result.data.mobile_app_page_views)
                        $('#sales_buy_box_percentage').html(result.data.buy_box_percentage)
                        $('#sales_feedback_received').html(result.data.feedback_received)
                        $('#sales_negative_feedback').html(result.data.negative_feedback)
                    }
                }
            },
        }).fail(function(xhr, status, q) {
            $('#sales_order_product_amount').html('-')
            $('#sales_order_shipped').html('-')
            $('#sales_average_sales_per_order').html('-')
            $('#sales_average_selling_price').html('-')
            $('#sales_refund_rate').html('-')
            $('#sales_browser_page_views').html('-')
            $('#sales_mobile_app_page_views').html('-')
            $('#sales_buy_box_percentage').html('-')
            $('#sales_feedback_received').html('-')
            $('#sales_negative_feedback').html('-')
            $('.view_modal').modal('hide');
            $('#pos-loader').css('display', 'none')
            // alert(xhr.responseText)            
            swal({
                title: 'Information',
                text: xhr.responseText,
                icon: 'info',
                // buttons: false,
            })
        });
    }

    function popupSelectedItems(seller_id) {
        var selected_rows = getSelectedRows();
            
        if(selected_rows.length > 0){
            $.ajax({
                url: baseUrl + '/amazon/popupSelectedItems',
                data: {
                    selected_rows: selected_rows,
                    seller_id: seller_id
                },
                dataType: 'html',
                success: function(result) {
                    // console.log(result);
                    $('.view_modal')
                        .html(result)
                        .modal('show');
                },
            });
        } else {
            $('input#selected_products').val('');
            swal('@lang("lang_v1.no_row_selected")');
        }
    }

    function printLabelMultiple(e, seller_id) {        
        e.preventDefault();
        var selected_rows = getSelectedRows();   
        if(selected_rows.length > 0) {
            var query = {
                seller_id: seller_id,
                products: selected_rows
            };
            // Buat URL query string
            let params = new URLSearchParams();
            params.append('seller_id', seller_id);
            selected_rows.forEach(p => params.append('products[]', p));
    
            // Redirect
            window.location.href = baseUrl + '/amazon/labels/multiple?' + params.toString();       
        } else {
            $('input#selected_products').val('');
            swal('@lang("lang_v1.no_row_selected")');
        }        
    }

    function updateOnAllAmazon(e) {
        e.preventDefault();
        var form = document.getElementById('form-selected-items');
        var objData = new FormData(form);
        $.ajax({
            method: 'POST',
            url: baseUrl + '/amazon/updateOnAllAmazon',
            data: objData,
            dataType: 'json',
            processData: false,     // << Prevent jQuery from processing the data
            contentType: false,     // << Prevent jQuery from setting Content-Type
            beforeSend: function() {
                $('#pos-loader').css('display', 'inline-flex')
            },
            success: function(result) {
                $('#pos-loader').css('display', 'none')
                $('.view_modal').modal('hide');
                if(result.rc == 500) {
                    swal({
                        title: 'Failed',
                        text: result.message,
                        icon: 'danger',
                        // buttons: false,
                    })
                } else {
                    swal({
                        title: 'Success',
                        text: result.message,
                        icon: 'success',
                        // buttons: false,
                    })
                    shopify_table.ajax.reload()
                }
            },
        }).fail(function(xhr, status, q) {
            $('.view_modal').modal('hide');
            $('#pos-loader').css('display', 'none')
            // alert(xhr.responseText)            
            swal({
                title: 'Information',
                text: xhr.responseText,
                icon: 'info',
                // buttons: false,
            })
        });
    }

    // function startSync() 
    // {        // var seller_id = $('#product_locations_amazon').val();   
    //     var results;
    //     var count = 0;
    //     $('#pos-loader').css('display', 'inline-flex');
    //     $.each(amazon_sellers, function(index, v) {
    //         setTimeout(function() {
    //             $.ajax({
    //                 method: 'GET',
    //                 url: baseUrl + '/amazon/requestInventoryReport/' + v.seller_id,
    //                 dataType: 'json',
    //                 beforeSend: function() {                
    //                     // $('#pos-loader').css('display', 'inline-flex');
    //                 },
    //                 success: function(result) { 
    //                     // $('#pos-loader').css('display', 'none');
    //                     $('.view_modal').modal('hide');
    //                     // swal({
    //                     //     title: 'Information',
    //                     //     text: result.success,
    //                     //     icon: 'info',
    //                     // });
    //                     results = result.success;
    //                     count++;
    //                 },
    //             }).fail(function(xhr, status, q) {                    
    //                 $('.view_modal').modal('hide');                    
    //                 results = xhr.responseText;
    //                 // swal({
    //                 //     title: 'Information',
    //                 //     text: xhr.responseText,
    //                 //     icon: 'info',
    //                 // });
    //             });   
    //         }, index * 75000); // Delay each request by 65 seconds
    //     });  
    //     // /amazon/update-amazon-seller-inventory
    //     while (amazon_sellers.length < count) {
    //         setTimeout(() => {            
    //             updateAmazonTable();            
    //             $('#pos-loader').css('display', 'none');
    //             swal({
    //                 title: 'Information',
    //                 text: results,
    //                 icon: 'info',
    //             });
    //         }, 30000);
    //     }        
    // }

    function syncTest(){
        $.ajax({
            method: 'GET',
            url: baseUrl + '/amazon/updateAmazonTest',
            dataType: 'json',
            success: function(result) { 
                console.log(result.success);
            },
            error: function(xhr) {                    
                console.log(xhr.responseText);
            }
        });
    }

    function startSync() {

        // updateAmazonTable();        
        //WILL BE UNCOMMENTED LATER
        var results = [];
        // $('#pos-loader').css('display', 'inline-flex');        

        var ajaxCalls = []; // Store all AJAX requests
        startPollingProgress();
        $.each(amazon_sellers, function(index, v) {
            var ajaxCall = new Promise((resolve, reject) => {
                setTimeout(function() {
                    $.ajax({
                        method: 'GET',
                        url: baseUrl + '/amazon/requestInventoryReport/' + v.seller_id,
                        dataType: 'json',
                        success: function(result) { 
                            $('.view_modal').modal('hide');
                            results.push(result.success); // Store result
                            resolve(); // Mark this request as completed
                            // bar_percent = '';
                            // $('#progressBar').css('width', '33%');
                        },
                        error: function(xhr) {                    
                            $('.view_modal').modal('hide');
                            results.push(xhr.responseText); // Store error
                            reject(); // Mark this request as failed
                        }
                    });
                }, index * 90000); // Delay each request by 90 seconds
            });

            ajaxCalls.push(ajaxCall);
        });

        // Wait for all AJAX calls to complete before running updateAmazonTable
        Promise.allSettled(ajaxCalls).then(() => {
            updateAmazonTable().then(() => {
                // checkJobStatus(); // Polling hanya dimulai setelah update selesai
                // $('#pos-loader').css('display', 'none');
                swal({
                    title: 'Information',
                    text: "Processing send to shopify on background process.",
                    icon: 'info',
                    // buttons: false,
                }) 
            });
        });
        //WILL BE UNCOMMENTED LATER

    }

    // ✅ Ubah updateAmazonTable agar mengembalikan Promise
    function updateAmazonTable() {
        return new Promise((resolve, reject) => {
            // startPollingProgress();
            $.ajax({
                method: 'GET',
                // url: baseUrl + '/amazon/update-amazon-table-new', //remove -new (PALIGU)
                url: baseUrl + '/amazon/update-amazon-table',
                dataType: 'json',
                success: function(result) {
                    $('.view_modal').modal('hide');
                    resolve(result.success);
                },
                error: function(xhr) {
                    $('.view_modal').modal('hide');
                    reject(xhr.responseText);
                }
            });
        });
    }


    // can't use if we change tha page
    // document.addEventListener("DOMContentLoaded", function() {
    //     // Cek apakah job masih berjalan saat halaman dimuat
    //     var isJobRunning = localStorage.getItem("jobRunning");

    //     if (isJobRunning === "true") {
    //         // console.log("🔄 Page reload, continue checkJobStatus...");
    //         checkJobStatus(); // Lanjutkan polling
    //     }
    // });

    // function checkJobStatus() {
    //     // console.log("🕵️‍♂️ Start polling checkJobStatus...");

    //     // Simpan status job di localStorage agar tetap bisa dicek setelah reload
    //     localStorage.setItem("jobRunning", "true");

    //     var interval = setInterval(function() {
    //         console.log("🔄 Checking job status...");
    //         $.ajax({
    //             method: 'GET',
    //             url: baseUrl + '/check-job-status',
    //             dataType: 'json',
    //             success: function(response) {
    //                 // console.log("✅ Job Status:", response);
    //                 if (response.status === 'completed') {
    //                     // console.log("🎉 Job finish! Menghentikan polling & menjalankan convertAmazonToShopify...");
    //                     clearInterval(interval);
    //                     localStorage.removeItem("jobRunning"); // Hapus status job dari localStorage
    //                     convertAmazonToShopify();
    //                 }
    //             },
    //             error: function(xhr) {
    //                 console.error("❌ Error checking job status:", xhr.responseText);
    //             }
    //         });
    //     }, 10000);
    // }

    // function convertAmazonToShopify() {
    //     $.ajax({
    //         method: 'GET',
    //         url: baseUrl + '/amazon/convert-amazon-to-shopify/cheapBookDepot',
    //         dataType: 'json',
    //         success: function(result) { 
    //             results.push(result.message);               
    //             $('#pos-loader').css('display', 'none');
    //         },
    //         error: function(xhr) {                  
    //             $('#pos-loader').css('display', 'none');  
    //             $('.view_modal').modal('hide');                
    //             results.push(xhr.responseText);               
    //         }
    //     });
    // }

    function checkSyncProgress() {
        $.ajax({
            method: 'GET',
            url: baseUrl + '/amazon/check-sync-progress',
            dataType: 'json',
            success: function(result) { 
                $('#progressBarHead').css('display', 'block');  
                $('#progressBarTitle').css('display', 'block');  
                var progressRequestInventoryReport = Math.round((result.requestInventoryReportComplete / result.requestInventoryReportTotal) * 100);
                if(progressRequestInventoryReport >= 100 || (result.requestInventoryReportComplete == 0 && result.requestInventoryReportTotal == 0)) {
                    var progressupdateAmazonTable = Math.round((result.updateAmazonTableComplete / result.updateAmazonTableTotal) * 100);
                    $('#progressBarTitle').html('Updating Amazon List');         
                    $('#progressBarHead').css('display', 'block');         
                    $('#progressBar').css('width', progressupdateAmazonTable + '%').text(progressupdateAmazonTable + '%');
                } else {
                    $('#progressBarTitle').html('Updating Amazon Seller Inventory');         
                    $('#progressBarHead').css('display', 'block');         
                    $('#progressBar').css('width', progressRequestInventoryReport + '%').text(progressRequestInventoryReport + '%');
                }

                if(progressRequestInventoryReport >= 100 || result.requestInventoryReportTotal == 0) {
                    if(progressupdateAmazonTable >= 100 || result.updateAmazonTableTotal == 0) {
                        stopPollingProgress();
                        $('#progressBarHead').css('display', 'none');  
                        $('#progressBarTitle').css('display', 'none');  
                    }
                }
            },
            error: function(xhr) {                                  
                stopPollingProgress();
                $('#progressBarHead').css('display', 'none');  
                swal({
                    title: 'Information',
                    text: xhr.responseText,
                    icon: 'info',
                    // buttons: false,
                })
            }
        });        
    }

    function startPollingProgress() {
        if (pollProgress === null) {
            pollProgress = setInterval(() => {
                checkSyncProgress();
            }, 5000); // every 5 seconds
        }
    }

    function stopPollingProgress() {
        if (pollProgress !== null) {
            clearInterval(pollProgress);
            pollProgress = null;
        }
    }
    
    function addToPrintQueue(e, id, seller_id) {                
        e.preventDefault();        
        total_queue_table = 0;
        var objData = new FormData();
        objData.append('reference_id', id);
        objData.append('reference_table', 'amazon_table');
        $.ajax({
            method: 'POST',
            url: baseUrl + '/labels/add-to-print-label-queue',
            data: objData,
            dataType: 'json',
            processData: false,     // << Prevent jQuery from processing the data
            contentType: false,     // << Prevent jQuery from setting Content-Type
            beforeSend: function() {
                $('#pos-loader').css('display', 'inline-flex')
            },
            success: function(result) {
                $('#pos-loader').css('display', 'none')
                $('.view_modal').modal('hide');
                if(result.rc == 500) {
                    swal({
                        title: 'Failed',
                        text: result.rm,
                        icon: 'danger',
                        // buttons: false,
                    })
                } else if(result.rc == 1) {
                    // swal({
                    //     title: 'Success',
                    //     text: result.rm,
                    //     icon: 'success',
                    //     // buttons: false,
                    // })
                    // Get the <td> that contains the dropdown button
                    const td = e.target.closest('td'); // This is the clicked <td>
                    td.style.backgroundColor = '#ffff00';
                    const link = td.querySelector('a[onclick*="addToPrintQueue"]');
                    if (link) {
                        link.setAttribute('onclick', `removeItemPrintLabelsQueue(event, ${id}, 'remove_action', '${seller_id}')`);
                        link.innerHTML = '<i class="fa fa-barcode"></i> Remove From Print Queue'; // Optional change in label
                    }
                    localStorage.setItem('total_queue', result.total_queue);
                    $.each(amazon_sellers, function(k,v) {                        
                        $('#total_label_queue' + v.seller_id).html('('+result.total_queue+')');
                        $('#label-queue' + v.seller_id).css('display', 'inline-block');
                    })
                    $('#total_label_queueall').html('('+result.total_queue+')');
                    $('#label-queueall').css('display', 'inline-block');
                } else {
                    swal({
                        title: 'Information',
                        text: result.rm,
                        icon: 'info',
                        // buttons: false,
                    })
                }
            },
        }).fail(function(xhr, status, q) {
            $('.view_modal').modal('hide');
            $('#pos-loader').css('display', 'none')
            // alert(xhr.responseText)            
            swal({
                title: 'Information',
                text: xhr.responseText,
                icon: 'info',
                // buttons: false,
            })
        });
    }

    function popupPrintLabelsQueue(e, seller_id) {
        $.ajax({
            url: baseUrl + '/labels/popupPrintLabelsQueue',
            data: {                
                seller_id: seller_id,
                reference_table: 'amazon_table'
            },
            dataType: 'html',
            success: function(result) {
                // console.log(result);
                $('.view_modal')
                    .html(result)
                    .modal('show');
            },
        });
    }

    function removeItemPrintLabelsQueue(e, id, type='default', seller_id_from_td = null) {
        e.preventDefault();
        total_queue_table = 0;
        var objData = new FormData();
        objData.append('reference_id', id);
        objData.append('reference_table', 'amazon_table');
        $.ajax({
            method: 'POST',
            url: baseUrl + '/labels/delete-item-print-label-queue',
            data: objData,
            dataType: 'json',
            processData: false,     // << Prevent jQuery from processing the data
            contentType: false,     // << Prevent jQuery from setting Content-Type
            beforeSend: function() {
                $('#pos-loader').css('display', 'inline-flex')
            },
            success: function(result) {
                $('#pos-loader').css('display', 'none')
                $('.view_modal').modal('hide');
                if(result.rc == 500) {
                    swal({
                        title: 'Failed',
                        text: result.rm,
                        icon: 'danger',
                        // buttons: false,
                    })
                } else if(result.rc == 1) {
                    // swal({
                    //     title: 'Success',
                    //     text: result.rm,
                    //     icon: 'success',
                    //     // buttons: false,
                    // })
                    if(type == 'remove_action') {                        
                        const td = e.target.closest('td'); // This is the clicked <td>
                        td.style.backgroundColor = '#ffffff';
                        const link = td.querySelector('a[onclick*="removeItemPrintLabelsQueue"]');              
                        if (link) {
                            link.setAttribute('onclick', `addToPrintQueue(event, ${id}, '${seller_id_from_td}')`);
                            link.innerHTML = '<i class="fa fa-barcode"></i> Add To Print Queue'; // Optional change in label                        
                        }
                        if(result.total_queue == 0) {
                            localStorage.removeItem('total_queue');
                            $.each(amazon_sellers, function(k,v) {
                                $('#total_label_queue' + v.seller_id).html('('+result.total_queue+')');
                                $('#label-queue' + v.seller_id).css('display', 'none');
                            })
                            $('#total_label_queueall').html('('+result.total_queue+')');
                            $('#label-queueall').css('display', 'none');
                        } else {
                            localStorage.setItem('total_queue', result.total_queue);
                            $.each(amazon_sellers, function(k,v) {                                
                                $('#total_label_queue' + v.seller_id).html('('+result.total_queue+')');
                                $('#label-queue' + v.seller_id).css('display', 'inline-block');
                            })
                            $('#total_labelall').html('('+result.total_queue+')');
                            $('#label-queueall').css('display', 'inline-block');
                        }
                    } else {
                        var seller_id = $('#seller_id_label_queue').val();                
                        if(result.total_queue == 0) {
                            localStorage.removeItem('total_queue');
                            $.each(amazon_sellers, function(k,v) {
                                $('#total_label_queue' + v.seller_id).html('('+result.total_queue+')');
                                $('#label-queue' + v.seller_id).css('display', 'none');
                                tables['amazon_table_' + (k + 1)].ajax.reload();
                            })
                            $('#total_label_queueall').html('('+result.total_queue+')');
                            $('#label-queueall').css('display', 'none');
                            tables['amazon_table_all'].ajax.reload();
                            $('.view-modal').modal('hide');
                        } else {
                            localStorage.setItem('total_queue', result.total_queue);
                            $.each(amazon_sellers, function(k,v) {                                
                                $('#total_label_queue' + v.seller_id).html('('+result.total_queue+')');
                                $('#label-queue' + v.seller_id).css('display', 'inline-block');
                                tables['amazon_table_' + (k + 1)].ajax.reload();
                            })  
                            $('#total_label_queueall').html('('+result.total_queue+')');
                            $('#label-queueall').css('display', 'inline-block');
                            tables['amazon_table_all'].ajax.reload();
                            $('.view-modal').modal('hide');
                            setTimeout(() => {                        
                                popupPrintLabelsQueue(e, seller_id);
                            }, 500);
                        }
                    }
                } else {
                    swal({
                        title: 'Information',
                        text: result.rm,
                        icon: 'info',
                        // buttons: false,
                    })
                }
            },
        }).fail(function(xhr, status, q) {
            $('.view_modal').modal('hide');
            $('#pos-loader').css('display', 'none')
            // alert(xhr.responseText)            
            swal({
                title: 'Information',
                text: xhr.responseText,
                icon: 'info',
                // buttons: false,
            })
        });
    }

    function printLabelsQueue(e) {
        var seller_id = $('#seller_id_label_queue').val();
        let productIds = $("input[name='products_label_queue[]']").map(function () {
            return $(this).val();
        }).get();

        var query = {
            seller_id: seller_id,
            products: productIds
        };
        // Buat URL query string
        let params = new URLSearchParams();
        params.append('seller_id', seller_id);
        productIds.forEach(p => params.append('products[]', p));
        
        // Redirect
        window.location.href = baseUrl + '/amazon/labels/multiple?' + params.toString();   
    }

    function getPrintQueueCountByUser() {
        $.ajax({
            url: baseUrl + '/labels/get-print-queue-count-by-user',
            data: {                
                reference_table: 'amazon_table'
            },
            dataType: 'json',
            success: function(result) {
                // console.log(result);
                if(result > 0) {
                    localStorage.setItem('total_queue', result);
                    $.each(amazon_sellers, function(k,v) {                                
                        $('#total_label_queue' + v.seller_id).html('('+result+')');
                        $('#label-queue' + v.seller_id).css('display', 'inline-block');
                        // tables['amazon_table_' + (k + 1)].ajax.reload();
                    })      
                    $('#total_label_queueall').html('('+result+')');
                    $('#label-queueall').css('display', 'inline-block');
                }
            },
        });
    }
</script>
@endsection