@extends('layouts.app')
@section('title','Accounts')
@section('pages')
<style type="text/css">
    .add_btn {
        height: 30px; width: 30px; border-radius: 100%; padding: 0
    }
    .breadcrumb-title {
      border-right: none;
    }
    .dataTables_info {
        padding: 16px 0 0 20px;
    }
    .exl_file {
        height: 32px !important;
    }
</style>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/12.1.10/css/intlTelInput.css">
  <!--breadcrumb-->
  <div class="page-breadcrumb row align-items-center justify-content-between mb-3 px-3 px-md-0">
    <div class="breadcrumb-title col-md-6"> Accounts</div>
    <div class="col-md-6">
      <nav aria-label="breadcrumb">
        <ol class="breadcrumb justify-content-md-end mb-0">
          <li class="breadcrumb-item"><i class="bi bi-info-circle-fill text-info show-help-support" data-id="46" data-bs-toggle="modal" data-bs-target="#commonModal"></i></li>
          <li class="breadcrumb-item" aria-current="page">Accounts</li>
          <li class="breadcrumb-item active" aria-current="page"><i class="bi bi-dot"></i> Bulk Import </li>
        </ol>
      </nav>
    </div>
  </div>
  <!--end breadcrumb-->

  <div class="card style_table shadow-none radius-5 min-height">
    <div class="card-header py-3">
      @include('layouts.partials.nav-menu')
      <div class="row gx-2">
        <div class="col-lg-12 col-md-12">
            <div class="btn-group">
                <h5 class="mt-1">Temporary Accounts List &nbsp;&nbsp;</h5>
                <div class="btn-group">
                    <form class="btn-group">
                        <div class="position-absolute top-50 translate-middle-y search-icon px-3"><i class="bi bi-search"></i></div>
                        <input class="form-control ps-5" type="search" id="search" placeholder="Search">

                        {{--<button class="btn btn-success w-100 mx-3" id="submit" type="submit" style="width: 50px !important;"><i class="bi bi-search"></i></button>--}}
                    </form>
                </div>

            </div>
            <div class="ms-auto float-md-end action_buttons">

                <div class="btn-group">
                    <a href="{{route('accounts.index')}}" class="btn btn-outline-secondary me-1"><i class="bx bx-arrow-back ms-0 me-1"></i>Back</a>
                </div>
                @if(count($data)>0)
                <div class="btn-group">
                    <button type="button" class="btn btn-success" id="import"><i class="bi bi-floppy-fill"></i> Save to Database</button>
                </div>

                <div class="btn-group">
                    <button type="button" class="btn btn-danger" id="clear_temp"><i class="bi bi-floppy-fill"></i> Clear Temp Data</button>
                </div>
                @endif
            </div>
        </div>
      </div>
    </div>

    <div class="card-body" id="tables">

        @include('temp-accounts-import.table')

        <input type="hidden" name="hidden_page" id="hidden_page" value="1" />
        <input type="hidden" name="hidden_column_name" id="hidden_column_name" value="name" />
        <input type="hidden" name="hidden_sort_type" id="hidden_sort_type" value="asc" />
    </div>
<!--end row-->
@endsection

@section('js')
<script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/12.1.10/js/intlTelInput.js"></script>
<script>
    $(document).ready(function() {
        function fetch_data(page, sort_type, sort_by, query){
            $.ajax({
              url:"?page="+page+"&sortby="+sort_by+"&sorttype="+sort_type+"&query="+query,
              success:function(data){
                $('#tables').html('');
                $('#tables').html(data);
                $(document).ready(function(){$.switcher();});
              }
            })
        }
        $('body').on('keyup change input', '#search', function(){
            var query       = $('#search').val();

            if (query.length < 2 && query.length != 0) {
                return;
            }

            var column_name = 10;
            var sort_type   = $('#hidden_sort_type').val();
            var page        = 1?1:(this).attr('href').split('page=')[1];
            fetch_data(page, sort_type, column_name, query);
        });
        $('body').on('click', '.pager a', function(event){
            event.preventDefault();
            $('#hidden_page').val(page);
            var page        = $(this).attr('href').split('page=')[1];
            var column_name = 10;
            var sort_type   = $('#hidden_sort_type').val();
            var query       = $('#search').val()?$('#search').val():'';
            $('li').removeClass('active');
            $(this).parent().addClass('active');
            fetch_data(page, sort_type, column_name, query);
        });

        $(document).on('click', '#create', function(){
            $('#commonModalLabel').text('Import Accounts');
            $('.save_button_span').text('Upload Accounts');
            $('.save_button').addClass('importProduct');
            $('.save_button').removeClass('editProduct');
            $.ajax({
                url:"{!! route('accounts-import.create') !!}",
                success:function(data) {
                    $('#commonModal').find('.modal-body').html('');
                    $('#commonModal').find('.modal-body').html(data);
                }
            });
        });

        $(document).on('click', '.edit', function() {
            $('#commonModalLabel').text('Edit Accounts');
            $('.save_button_span').text('Update Accounts');
            $('.save_button').removeClass('importProduct');
            $('.save_button').addClass('editProduct');
            var id = $(this).data('id');
            var url = `{!! route('accounts-import.edit', ':id') !!}`.replace(':id', id);

            $.ajax({
                url:url,
                success:function(data) {
                    $('#commonModal').find('.modal-body').html('');
                    $('#commonModal').find('.modal-body').html(data);

                    // Destroy the existing instances
                    telInput.intlTelInput('destroy');

                    // Reinitialize the input fields with the new country code
                    telInput.intlTelInput({
                        utilsScript: 'https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.13/js/utils.js',
                        initialCountry: countryCode, // Set the received country code directly
                        separateDialCode: true
                    });
                }
            });
        });

        $(document).on('click', '#clear_temp', function() {
            var url = `{!! route('accounts-import.clear-data') !!}`;

            Swal.fire({
                title: 'Are you sure you want to delete this?',
                icon: 'warning',
                showDenyButton: true,
                showCancelButton: false,
                confirmButtonText: 'Yes',
                denyButtonText: 'No',
            }).then((result) => {
                /* Read more about isConfirmed, isDenied below */
                if (result.isConfirmed) {
                    $.ajax({
                        url:url,
                        success:function(response) {
                            if (response.success === true) {
                                toastr.success(response.message, 'Success.');

                                var query = $('#search').val();

                                var sort_type   = $('#hidden_sort_type').val();

                                fetch_data(1, sort_type, 10, query);
                            } else {
                                toastr.error(response.message, 'Error!');
                            }
                        }
                    });
                }
            });
        });

        $(document).on('click', '.editProduct', function(e) {
            let formdata = new FormData($('.edit_product')[0]);

            $.ajax({
                  url: $('.edit_product').attr('action'),
                  data: formdata,
                  processData: false,
                  contentType: false,
                  type: 'POST',
                  success: function (response) {
                        if (response.success === true) {
                          toastr.success(response.message, 'Success.');

                            var query = $('#search').val();

                            var sort_type   = $('#hidden_sort_type').val();

                            fetch_data(1, sort_type, 10, query);

                            // hide modal
                            $('#commonModal').modal('hide');
                            $('#commonModal').find('.modal-body').html('');
                        } else {
                            toastr.error(response.message, 'Error!');
                        }
                  }
            })
            .fail(function(jqXHR, textStatus, errorThrown) {
                  console.log('AJAX request failed:', textStatus, errorThrown);
                  toastr.error('An error occurred during the request.', 'Error!');

                  // hide modal
                  $('#commonModal').modal('hide');
                  $('#commonModal').find('.modal-body').html('');
            });
        });

        $(document).on('click','.importProduct', function(e) {
            e.preventDefault();

            if ($('.exl_file').val() == '') {
                toastr.error("Excel file field is required.");
            }

            var file = $('.exl_file').val();
            var error = 0;
            var ext = file.match(/\.(.+)$/)[1];

            if(ext != 'xls' && ext != 'xlsx'){
                toastr.error('File must be type of xls & xlsx.');
                $('.exl_file').val('');
                error = 1;
            }

            const size = $(".exl_file")[0].files[0].size;

            if (size > 5e+6) {
                toastr.error('File must be less than 5 MB');
                $('.exl_file').val('');
                error = 1;
            }

            // var formData = new FormData($('.form')[0]);
            var formData = new FormData();
            formData.append('file', $('.exl_file')[0].files[0]);

            if (error == 0) {
                $.ajax({
                    url:"{{ route('accounts-import.store')}}",
                    type:'POST',
                    data: formData,
                    contentType: false,
                    processData: false,
                    success:function(data){
                        if (data.success === true) {
                            $('[name="excel"]').val('');
                            $('.btn-close').click();

                            toastr.success(data.message);
                            var sort_type   = $('#hidden_sort_type').val();

                            fetch_data(1, sort_type, 10, query);
                        } else {
                            $('[name="excel"]').val('');
                            toastr.error(data.message);
                        }
                    }
                });
            }
            error = 1;
        });

        $("body").on("click", '.deleteDataCustom', function(event) {
            dataString = {
                "id": $(this).data('id')
            };
            var UrlValue = $(this).data('url');
            var btn = $(this);

            Swal.fire({
                title: 'Are you sure you want to delete this?',
                icon: 'warning',
                showDenyButton: true,
                showCancelButton: false,
                confirmButtonText: 'Yes',
                denyButtonText: 'No',
            }).then((result) => {
                /* Read more about isConfirmed, isDenied below */
                if (result.isConfirmed) {
                    $.ajax({
                        url: UrlValue,
                        method: 'post',
                        data: {
                            "_token": $('meta[name="csrf-token"]').attr('content'),
                            "id": $(this).data('id')
                        },
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        },
                        beforeSend: function(xhr) {
                            // xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
                        },
                        success: function(response) {
                            if (response.success) {
                                $(this).Toastshow('success', response.message);

                                var query = $('#search').val();

                                var sort_type   = $('#hidden_sort_type').val();

                                fetch_data(1, sort_type, 10, query);
                            } else {
                                var ErroMsg = $(this).printErrorMsg(response
                                    .message);
                                $(this).Toastshow('error', ErroMsg);
                            }
                        },
                        error: function(data) {
                            console.log("error ", data);
                        }
                    });
                }
            });
        });

        $(document).on('click', '#import', function() {
            $.ajax({
                url:"{{ route('accounts-import.proceed')}}",
                type:'POST',
                data: {},
                contentType: false,
                processData: false,
                success:function(data){
                    if (data.success === true) {
                        toastr.success(data.message);

                        var query = $('#search').val();
                        var sort_type   = $('#hidden_sort_type').val();

                        fetch_data(1, sort_type, 10, query);
                    } else {
                        toastr.error(data.message);

                        var query = $('#search').val();
                        var sort_type   = $('#hidden_sort_type').val();

                        fetch_data(1, sort_type, 10, query);
                    }
                }
            });
        });
    });
</script>
@endsection
