@extends('layouts.app')

@section('title', 'Task Stages')

@section('pages')

<style type="text/css">
.breadcrumb-title {
    border-right: none;
}

tr td {
    vertical-align: middle !important;
}
</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">Task Stages</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="93"
                        data-bs-toggle="modal" data-bs-target="#commonModal"></i></li>
                <li class="breadcrumb-item active" aria-current="page">IPD-In Task Stages</li>
                <li class="breadcrumb-item active" aria-current="page"><i class="bi bi-dot"></i> Task Stages</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">
                <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" autofocus>
                </div>
            </div>

             <div class="col-lg-3 col-md-3 col-8">
                    <!-- Dropdown for Building Selection -->
                    <div class="d-flex align-items-center">
                        <select class="form-select task_group_id" id="task_group_id" name="example_length" aria-controls="example">
                            <option value="">Select Task Groups Name</option>
                            @foreach($task_groups as $list)
                                <option value="{!! $list->id !!}" {!! $task_group_id == $list->id ? 'selected' : ''  !!}>{!! $list->name !!}
                                </option>
                            @endforeach
                        </select>
                    </div>
                </div>

            <div class="col-lg-6 col-md-6">
                <div class="ms-auto float-md-end">
                    <div class="btn-group">
                        <button class="btn btn-primary" id="create_pipeline_stages" type="button" data-bs-toggle="modal"
                            data-bs-target="#commonModal">+ Add New Task Stages</button>
                    </div>

                    <div class="btn-group">
                        <a href="{!! route('task-groups.index') !!}" 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('task-manager.pipeline-stages.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>
</div>

@endsection
@section('js')

<script>
/***************** 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);
    };
}


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

function fetch_data(page, sort_type, column_name, query ,task_group_id) {
    var search_type = $('[name="search_type"]').val();

    $.ajax({
        url: "?page=" + page + "&sorttype=" + sort_type + "&column_name=" + column_name + "&query=" + query +
              "&task_group_id=" + task_group_id,
        success: function(data) {
            $('#tables').html('');
            $('#tables').html(data);
            $(document).ready(function() {
                $.switcher();
            });
        }
    });
}

/******** 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];
    var task_group_id     = $('#task_group_id').val();

    fetch_data(page, sort_type, column_name, query ,task_group_id);
}, 700));

$('body').on('change', '.sorting', function() {

    var column_name       = $(this).val();
    var order_type        = $(this).data('sorting_type');
    var reverse_order     = '';
    var page              = 1 ? 1                                  : (this).attr('href').split('page = ')[1];
    var query             = $('#search').val() ? $('#search').val(): '';
    var task_group_id     = $('#task_group_id').val();
    fetch_data(page, sort_type, column_name, query ,task_group_id);
});

$('body').on('change', '.task_group_id', function() {

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


/*********delete data**********/
$("body").on("click", '.deleteDataCustom', function(event) {
    var UrlValue = $(this).data('url');

    Swal.fire({
        title: 'Are you sure you want to delete this?',
        icon: 'warning',
        showDenyButton: true,
        showCancelButton: false,
        confirmButtonText: 'Yes',
        denyButtonText: 'No',
    }).then((result) => {
        if (result.isConfirmed) {
            $.ajax({
                url: UrlValue,
                method: 'delete',
                data: {
                    "_token": $('meta[name="csrf-token"]').attr('content'),
                    "id": $(this).data('id')
                },
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                success: function(response) {
                    if (response.success) {

                        $(this).Toastshow('success', response.message);

                        // Refreshing data after deletion
                        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() : '';
                        var task_group_id     = $('#task_group_id').val();

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


// Create Pipeline Stages Modal
$(document).on('click', '#create_pipeline_stages', function() {
    $('#commonModalLabel').text('New Pipeline Stages');
    $('.save_button_span').text('Save Pipeline Stages');
    $.ajax({
        url: "{{ route('pipeline-stages-account-create') }}",
        success: function(data) {
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);
        }
    });
});

//Create Task Group
$(document).on('click', '.save_button', function(e) {
    e.preventDefault();

    var error = 0;

    if ($('#commonModal').find('form').hasClass('create_pipeline_stages')) {
        if (error == 0) {
            let formdata = new FormData($('#create_pipeline_stages_form')[0]);
            $.ajax({
                    url: $('#create_pipeline_stages_form').attr('action'),
                    data: formdata,
                    processData: false,
                    contentType: false,
                    type: 'POST',
                    success: function(response) {
                        if (response.success === true) {
                            toastr.success(response.message, 'Success.');

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

                            // Refreshing data after deletion
                            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() : '';
                            var task_group_id     = $('#task_group_id').val();

                            fetch_data(page, sort_type, column_name, query ,task_group_id);
                        } else {
                            // Handle failure case
                            var ErroMsg = $(this).printErrorMsg(response.message);
                            $(this).Toastshow('error', ErroMsg);
                        }

                    }
                })
                .fail(function(jqXHR, textStatus, errorThrown) {
                    console.log('AJAX request failed:', textStatus, errorThrown);
                    toastr.error('An error occurred during the request.', 'Error!');
                });
        }
    }

    if ($('#commonModal').find('form').hasClass('edit_pipeline_stages')) {
        if (error == 0) {
            $.ajax({
                    url: $('#edit_pipeline_stages_form').attr('action'),
                    data: $('#edit_pipeline_stages_form').serialize(),
                    // processData: false,
                    // contentType: false,
                    type: 'PUT',
                    success: function(response) {
                        if (response.success === true) {
                            toastr.success(response.message, 'Success.');
                            $('[name="pipeline_stages_id"]').val(response.data.id);
                            $('#commonModal').modal('hide');
                            $('#commonModal').find('.modal-body').html('');

                            // Refreshing data after deletion
                            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() : '';
                            var task_group_id     = $('#task_group_id').val();

                            fetch_data(page, sort_type, column_name, query ,task_group_id);
                        } else {
                            // Handle failure case
                            var ErroMsg = $(this).printErrorMsg(response.message);
                            $(this).Toastshow('error', ErroMsg);
                        }
                    }
                })
                .fail(function(jqXHR, textStatus, errorThrown) {
                    console.log('AJAX request failed:', textStatus, errorThrown);
                    toastr.error('An error occurred during the request.', 'Error!');
                });
        }
    }
})


// Edit Pipeline Stages Modal 
$(document).on('click', '#edit_pipeline_stages', function() {
    var id = $(this).data('id');
    $('#commonModalLabel').text('Edit Pipeline Stages');
    $('.save_button_span').text('Update Pipeline Stages');
    var url = `{!! route('pipeline-stages.edit', ':id') !!}`.replace(':id', id);

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

/*********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');

          console.log(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){
                              $(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():'';
                              var task_group_id = $('#task_group_id').val();

                              fetch_data(page, sort_type, column_name, query ,task_group_id);
                          } 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) {
                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():'';
                var task_group_id = $('#task_group_id').val();

                fetch_data(page, sort_type, column_name, query ,task_group_id);
              }
              //return false;
          });
  });
</script>
@endsection