@extends('layouts.app')
@section('title','Voucher Types')
@section('pages')
<style type="text/css">
    .breadcrumb-title {
      border-right: none;
    }
    .select2-container {
      z-index: 10000;
    }
    .add_btn {
        height: 30px; width: 30px; border-radius: 100%; padding: 0
    }
</style>

  <!--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"> Voucher Types | 
        {{$voucher_type->name}} 
</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="32" data-bs-toggle="modal" data-bs-target="#commonModal"></i></li>
          <li class="breadcrumb-item" aria-current="page">Voucher Master</li>
            <li class="breadcrumb-item active" aria-current="page"><i class="bi bi-dot"></i> Voucher Types </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-3 col-md-3 col-8">
            <div class="position-relative">
                <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" value="{!! request()->get('search') !!}" autofocus>
            </div>
        </div>

       

        <div class="col-lg-9 col-md-9">
          <div class="ms-auto float-md-end">
          <div class="btn-group">
            <!-- @if(in_array('voucher-series-create', $authRolePermissions)) -->
              <button type="button" class="btn btn-primary" id="create"  data-bs-toggle="modal" data-bs-target="#commonModal"><i class="bi bi-plus-circle"></i> Add New</button>
            <!-- @endif -->
            </div>
            @php $masterId = request('master');
             $redirectBack = request('redirect-back')??'';
             $redirectUrl  = $redirectBack .'/'.$masterId;
             @endphp
            <div class="btn-group">
                <a href="{!! url($redirectUrl) !!}" class="btn btn-outline-secondary me-1"><i class="bx bx-arrow-back ms-0 me-1"></i>Back</a>
            </div>

            

          </div>
        </div>
      </div>
    </div>

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

      @include('voucher-types.clearance-settings.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>

  <script>

     /***************** Global Delay Fucntion ***************/
    

    $(document).ready(function(){

      function clear_icon(){
        $('#id_icon').html('');
        $('#post_title_icon').html('');
      }

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

      $(document).on('click', '#create', function(){
        $('#commonModalLabel').text('Add New Department');
        $('.save_button_span').text('Save Department');
        $.ajax({
          url:"{!! route('clearance-settings.create' , $id) !!}",
          success:function(data){
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);

            $('.single-select').select2({
                minimumInputLength: 2,
                dropdownParent: $('.modal'),
                theme: 'bootstrap4',
                width: $(this).data('width') ? $(this).data('width') : $(this).hasClass('w-100') ? '100%' : 'style',
                placeholder: $(this).data('placeholder'),
                allowClear: Boolean($(this).data('allow-clear')),
            });
          }
        })
      });

        $("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 remove 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'),
                  },
                  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 page        = $('.pager').find('.active a').attr('href') == undefined ? 1 : $('.pager').find('.active a').attr('href').split('page=')[1];
                          var column_name = $('.sorting').val()?$('.sorting').val():'';
                          var sort_type   = $('#hidden_sort_type').val();
                          var query       = $('#search').val()?$('#search').val():'';

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


      $(document).on('click', '.save_button', function(event){
        event.preventDefault();

        
          $('.department_id').hide();
          var error = 0;
          if ($('#commonModal').find('form').find('select[name="department_id"]').val() == '') {
            $('.department_id').show();
            error = 1;
            setTimeout(function () {
                $('.department_id').hide();
                }, 1000);
          }

          if (error == 0) {
            let formdata = new FormData($('#commonModal').find('form')[0]);

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

                        var page        = $('.pager').find('.active a').attr('href') == undefined ? 1 : $('.pager').find('.active a').attr('href').split('page=')[1];
                        var column_name = $('.sorting').val()?$('.sorting').val():'';
                        var sort_type   = $('#hidden_sort_type').val();
                        var query       = $('#search').val()?$('#search').val():'';
                        fetch_data(page, sort_type , column_name , 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('');
                $('#commonModal').removeClass('category');
            });
          }
        error = 1;
      });



      
     /***************** Global Delay Fucntion ***************/
     function delay(callback, ms) {
        var timer = 0;
        return function() {
            var context = this,
                args = arguments;
            clearTimeout(timer);
            timer = setTimeout(function() {
                callback.apply(context, args);
            }, ms || 0);
        };
    }



       /******** searching ********/
        $(document).on('keyup', '#search', delay(function() {
            var query = $('#search').val();

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

            var column_name = $('.sorting').val();
            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);
        }, 700));

    });
  </script>
@endsection
