@extends('layouts.app')
@section('title','Test Package')
@section('pages')

<!-- include summernote css/js -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.18/summernote-bs4.min.css" rel="stylesheet">

<style type="text/css">
    .breadcrumb-title {
      border-right: none;
    }
</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"> {{ $packages->name ?? 'Package Name' }} </a>

      </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="84" data-bs-toggle="modal" data-bs-target="#commonModal"></i></li>
            <li class="breadcrumb-item" aria-current="page">Test Manager</li>
            <li class="breadcrumb-item active" aria-current="page"><i class="bi bi-dot"></i> Test Package</li>
            <li class="breadcrumb-item active" aria-current="page"><i class="bi bi-dot"></i> Test Package Group</li>
          </ol>
        </nav>
      </div>
    </div>
    <!--end breadcrumb-->

    <!-- main -->
    <div class="card style_table shadow-none radius-5 min-height" style="margin-bottom:-40px">
      <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 test_package_search" type="search" id="" placeholder="Search">
            </div>
          </div>
          <div class="col-lg-9 col-md-9">
            <div class="ms-auto float-md-end">

              <div class="btn-group">
                  <a href="{{route('test-packages.index')}}" class="btn btn-outline-secondary me-1"><i class="bx bx-arrow-back ms-0 me-1"></i>Back</a>
              </div>

              <div class="btn-group">
                @if(in_array('test-package-group-create', $authRolePermissions))
                  <button type="button" class="btn btn-primary" id="create" data-id="{{ $packages->id ?? '' }}" data-bs-toggle="modal" data-bs-target="#commonModal"><i class="bx bx-plus"></i> Add New</button>
                @endif
              </div>

            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- end main -->

    <!-- <div id="tables"> -->
    <div class="card-body" id="tables" style="padding: 0%; padding-top:10px">
      @include('test-package-groups.table')
    </div>
    <!-- </div> -->

@endsection
@section('js')
<script src="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.18/summernote-bs4.min.js"></script>

<script>
$(document).ready(function(){

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

    $(document).on('click', '#details', function(){
        $('#commonModalLabel').text('Test Item Detail');
        $('.modal-footer').hide();
        var id = $(this).data('id');
        var url = `{!! route('test-items.detail', ':id') !!}`.replace(':id', id);

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

    $(document).on('click', '#create', function(){
        $('.modal-dialog').css('max-width', '500px');
        $('#commonModalLabel').text('Add New Test Package Group');
        $('.save_button_span').text('Save Test Package Group');

        var id = $(this).data('id');
        var url = `{!! route('test-package-groups.create', ':id') !!}`.replace(':id', id);

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

    $(document).on('click', '.edit', function(){
        $('.modal-dialog').css('max-width', '500px');
        $('#commonModalLabel').text('Edit Test Package Group');
        $('.save_button_span').text('Update Test Package Group');
        var id = $(this).data('id');
        var url = `{!! route('test-package-groups.edit', ':id') !!}`.replace(':id', id);

        $.ajax({
          url:url,
          success:function(data){
            $('#commonModal').addClass('group_edit');
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);
            $.switcher('.page_break');
            $.switcher('.show_report');
          }
        });
    });

    $('#commonModal').on("hidden.bs.modal", function() {
        $('#commonModal').removeClass('group');
        $('#commonModal').removeClass('group_edit');
    });

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

        if ($('#commonModal').hasClass('group')) {
            $('.error_group_name').hide();
            var error = 0;

            if ($('#commonModal').find('form').find('input[name="group_name"]').val().trim() == '') {
              $('.error_group_name').show();
              error = 1;
            }

            if (error == 0) {
              $('#commonModal').find('form').submit();
            }
            error = 1;
        }
        else if ($('#commonModal').hasClass('group_edit')) {

            $('.error_group_name').hide();
            $('.error_priority').hide();
            var error = 0;

            if ($('#commonModal').find('form').find('input[name="group_name"]').val().trim() == '') {
              $('.error_group_name').show();
              error = 1;
            }

            if ($('#commonModal').find('form').find('input[name="priority"]').val().trim() == '') {
              $('.error_priority').show();
              error = 1;
            }

            if (error == 0) {
              $('#commonModal').find('form').submit();
            }
            error = 1;
        }
    });

    /*********change status**********/
    $("body").on("click",'.changeStatusCustom', function(event){
      dataString       = {"id":$(this).data('id'),"status":$(this).data('status')};
      var UrlValue     = $(this).data('url');
      var status       = $(this).data('status');
      var changeStatus = $(this);
      var btn = $(this);

      Swal.fire({
          title: 'Are you sure you want to change status?',
          icon: 'warning',
          showDenyButton: true,
          showCancelButton: false,
          confirmButtonText: 'Yes',
          denyButtonText: 'No',
      }).then((result) => {
          if (result.isConfirmed) {
              $.ajax({
                  url     : UrlValue,
                  method  : 'post',
                  data    :dataString,
                  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){
                          var ErroMsg = $(this).printErrorMsg(response.message);
                          $(this).Toastshow('success',ErroMsg);

                            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);
                          if (ErroMsg === '') {
                              ErroMsg = "Something went wrong!";
                          }
                          $(this).Toastshow('error',ErroMsg);

                          if (status == 1) {
                              changeStatus.parent().find('.ui-switcher').attr('aria-checked', false);
                          } else {
                              changeStatus.parent().find('.ui-switcher').attr('aria-checked', true);
                          }
                      }
                  },
                  error: function (data) {
                      console.log("error ",data);

                      if (status == 1) {
                          changeStatus.parent().find('.ui-switcher').attr('aria-checked', false);
                      } else {
                          changeStatus.parent().find('.ui-switcher').attr('aria-checked', true);
                      }
                  }
              });
          }
          else if (result.isDenied) {
                if (status == 1) {
                  changeStatus.parent().find('.ui-switcher').attr('aria-checked', false);
                } else {
                  changeStatus.parent().find('.ui-switcher').attr('aria-checked', true);
                }
          }
      });
    });

    /*********delete data**********/
    $("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){
                      var ErroMsg = $(this).printErrorMsg(response.message);

                      $(this).Toastshow('success',ErroMsg);

                      btn.closest('tr').remove();
                      btn.closest('.test_package_groups').remove();

                  }else{
                      var ErroMsg = $(this).printErrorMsg(response.message);
                      $(this).Toastshow('error',ErroMsg);
                  }
              },
              error: function (data) {
                console.log("error ",data);
              }
          });
          }
      });
    });
});
</script>
<script>
    $( ".tablecontents" ).sortable({
      items: "tr",
      cursor: 'grab',
      opacity: 0.7,
      update: function() {
          sendOrderToServer();
      }
    });

    function sendOrderToServer() {
      var order = [];
      $('tr.row1').each(function(index,element) {
        order.push({
          id: $(this).attr('data-id'),
          position: index+1
        });
        // $(this).find($('td.priority')).text(index+1);
        $(this).find($('td.item_sno')).text(index+1);
      });

      $.ajax({
        type: "POST",
        dataType: "json",
        url: "{{ route('reorder-test-items') }}",
        data: {
          order:order,
          _token: '{{csrf_token()}}'
        },
        success: function(response) {
            if (response.status == true) {
                toastr.success(response.message);
            } else {
              toastr.success('Error');
            }
        }
      });
    }
</script>
@endsection
