@extends('layouts.app')
@section('title', __('product.product_analyzer'))

@section('content')

<!-- Content Header (Page header) -->
<section class="content-header">
    <h1>@lang('product.product_analyzer')
    </h1>
    <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">
    
    @if (session('notification') || !empty($notification))
        <div class="row">
            <div class="col-sm-12">
                <div class="alert alert-danger alert-dismissible">
                    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                    @if(!empty($notification['msg']))
                        {{$notification['msg']}}
                    @elseif(session('notification.msg'))
                        {{ session('notification.msg') }}
                    @endif
                </div>
            </div>  
        </div>     
    @endif
    
    <div class="row">
        <div class="col-sm-12">
            @component('components.widget', ['class' => 'box-primary'])
                {!! Form::open(['url' => action([\App\Http\Controllers\ProductController::class, 'store_product_analyzer']), 'method' => 'post', 'id' => 'form_import_products', 'enctype' => 'multipart/form-data' ]) !!}
                    <div class="row">
                        <div class="col-sm-6">
                        <div class="col-sm-8">
                            <div class="form-group">
                                {!! Form::label('name', __( 'product.file_to_analyze' ) . ':') !!}
                                {!! Form::file('products_csv', ['accept'=> '.xls, .xlsx, .csv', 'required' => 'required']); !!}
                              </div>
                        </div>
                        <div class="col-sm-4">
                        <br>
                            <button type="submit" class="btn btn-primary" id="btn_sumbit_import_product" onclick="startPollingProgress()">@lang('product.analyze')</button>
                        </div>
                        </div>
                        <div class="clearfix"></div>
                        <!-- <div class="col-sm-4">
                            <div class="form-group">
                                <label for="">@lang('lang_v1.import_method')</label>
                                {!! Form::select('import_method', ['' => 'Please choose import method', '1' => 'Add/Update', '2' => 'Add/Replace'], null, ['class' => 'form-control select2', 'style' => 'width: 100%', 'required', 'onchange' => 'getTextImportMethod(this.value)']) !!}
                                <p id="information_import_method"></p>
                            </div>
                        </div> -->
                    </div>

                {!! Form::close() !!}
                <br><br>
                <!-- <div class="row">
                    <div class="col-sm-4">
                        {{-- <a href="{{ asset('files/import_products_csv_template.xls') }}" class="btn btn-success" download><i class="fa fa-download"></i> @lang('lang_v1.download_template_file')</a> --}}                        
                        <a class="btn btn-success" target="_blank" href="{{action([\App\Http\Controllers\ImportProductsController::class, 'downloadExcel'])}}"><i class="fa fa-download"></i> @lang('lang_v1.download_template_file')</a>                        
                    </div>
                </div> -->
            @endcomponent
        </div>
    </div>
    <div class="row">
        <div class="col-sm-12">
            @component('components.widget', ['class' => 'box-primary', 'title' => ''])
                <table class="table table-striped" id="product-analyzer-table">
                    <thead>
                        <tr>
                            <th>@lang('product.isbn13')</th>
                            <th>@lang('product.title')</th>
                            <th>@lang('product.condition')</th>
                            <th>@lang('product.binding')</th>
                            <th>@lang('product.in_our_system')</th>
                            <th>@lang('product.total_quantity')</th>
                            <th>@lang('product.price')</th>
                            <th>@lang('product.analyze_date')</th>
                        </tr>
                    </thead>
                    <tbody>
                    @if (session('status'))
                    @if(session('status.products'))
                      @foreach(session('status.products') as $value)
                        <tr>
                          <td>{{$value['isbn']}}</td>
                          <td>{{$value['title']}}</td>
                          <td>{{$value['condition']}}</td>
                          <td>{{$value['binding']}}</td>
                          <td>{{$value['in_our_system']}}</td>
                          <td>{{$value['total_quantity']}}</td>
                          <td>{{$value['price']}}</td>
                          <td>{{date('m/d/Y H:i', strtotime($value['created_at']))}}</td>
                        </tr>
                        @endforeach
                    @endif
                    @endif
                    </tbody>
                </table>
            @endcomponent
        </div>
    </div>

</section>
<!-- /.content -->

@endsection
@section('javascript')
<script>
    let pollProgress = null; // declared globally,
    const baseUrl = window.location.origin;
    $(document).ready(function() {    
        $('#btn_sumbit_import_product').on('click', function() {                 
            $('form#form_import_products').find('input').find('select').each(function(){
                if(!$(this).prop('required')){                    
                } else {
                    $('#pos-loader').css('display', 'flex');                       
                }
            });
        });
        
        $('#product-analyzer-table').DataTable();
    })

    function checkProductAnalyzerProgress() {
        $.ajax({
            method: 'GET',
            url: baseUrl + '/products/product-analyzer-progress',
            dataType: 'json',
            success: function(result) { 
                $('#progressBarHead').css('display', 'block');  
                $('#progressBarTitle').css('display', 'block');  
                var progressProductAnalyzer = Math.round((result.ProductAnalyzerComplete / result.ProductAnalyzerTotal) * 100);
                if(progressProductAnalyzer < 100) {                    
                    $('#progressBarTitle').html('Analyze Progress');         
                    $('#progressBarHead').css('display', 'block');         
                    $('#progressBar').css('width', progressProductAnalyzer + '%').text(progressProductAnalyzer + '%');
                } else if(progressProductAnalyzer >= 100 || (result.ProductAnalyzerComplete == 0 && result.ProductAnalyzerTotal == 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() {        
        document.getElementById("form_import_products").submit();
        if (pollProgress === null) {
            pollProgress = setInterval(() => {
                checkProductAnalyzerProgress();
            }, 2000);
        }
    }

    function stopPollingProgress() {
        if (pollProgress !== null) {
            clearInterval(pollProgress);
            pollProgress = null;
        }
    }
</script>
@endsection