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

<style type="text/css">
    .breadcrumb-title {
      border-right: none;
    }
    .dataTables_filter{
        margin-bottom: 6px;
    }
</style>
<link rel="stylesheet/less" type="text/css" href="{{ asset('admin/plugins/datepicker/less/datepicker.less') }}">
<link href="{{ asset('admin/plugins/datepicker/css/datepicker.css')}}" rel="stylesheet" />
  <!--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"> Category
    </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="42" data-bs-toggle="modal" data-bs-target="#commonModal"></i></li>
          <li class="breadcrumb-item" aria-current="page">Course</li>
            <li class="breadcrumb-item active" aria-current="page"><i class="bi bi-dot"></i>  Category </li>
        </ol>
      </nav>
    </div>
  </div>
  <!--end breadcrumb-->
  <div class="card style_table shadow-none radius-5 min-height my-auto">
    <div class="card-header py-3">
      @include('layouts.partials.nav-menu')
      <div class="row gx-2">
        <div class="col-md-4">
            <h5><b>{{$category->name}}</b> / Sub Category</h5>
        </div>
        <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">
        </div>
      </div>
        <div class="col-lg-5 col-md-5">
          <div class="ms-auto float-md-end">

          <div class="btn-group">
            <a data-bs-toggle="modal" data-bs-target="#commonModal" id="createSubCategory" class="btn btn-primary" ><i class="bx bx-plus-circle"></i> Add New Sub Category</a>
          </div>
            <div class="btn-group">
                @if(in_array('website-content-category-edit', $authRolePermissions))
                    <a data-id="{!! $id !!}" id="edit"  data-bs-toggle="modal" data-bs-target="#commonModal" class="btn btn-warning editCategory" data-bs-toggle="tooltip" data-bs-placement="bottom" title="Edit">
                        <i class="bi bi-pencil-square text-white"></i> <span class="text-white"> Edit Category</span>
                    </a>
                @endif
            </div>
            <div class="btn-group">
                <a href="{{route('content-category.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="sub_category_tables">
    </div>
  </div>

    <!--end row-->
@endsection
@section('js')
<script type="text/javascript" src="{{ asset('admin/plugins/datepicker/js/bootstrap-datepicker.js')}}"></script>
<script type="text/javascript">
    $(document).on('click', '.save_button', function(event){
        event.preventDefault();
        var error = 0;

        if ($('#commonModal').find('form').hasClass('category')) {

            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.');

                          // hide modal
                          $('#commonModal').modal('hide');
                          fetch_sub_category();
                        } 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('');
                });
            }
        }

        if ($('#commonModal').find('form').hasClass('subCategory')) {

            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) {
                            fetch_sub_category();
                            toastr.success(response.message, 'Success.');

                            // hide modal
                            $('#commonModal').modal('hide');
                        } 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('');
                });
              }
        }

        if ($('#commonModal').find('form').hasClass('create_study_material_types')) {
            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) {
                            fetch_sub_category();
                            toastr.success(response.message, 'Success.');

                            // hide modal
                            $('#commonModal').modal('hide');
                        } 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('');
                });
            }
        }

        if ($('#commonModal').find('form').hasClass('edit_study_material_types')) {
            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) {
                            fetch_sub_category();
                            toastr.success(response.message, 'Success.');

                            // hide modal
                            $('#commonModal').modal('hide');
                        } 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('');
                });
            }
        }
        error = 1;
    })
    $( function() {
        $('.datepicker').datepicker({
            "dateFormat" : "dd-mm-yy",
            "maxDate": '0',
            "changeMonth": true,
            "changeYear": true
        }).datepicker("setDate",'now')
        .on('changeDate', function (ev) {
             $(this).datepicker('hide');
        })

    });
    $(document).ready(function(){
        fetch_sub_category();
        
    });
    function fetch_sub_category(){
      $.ajax({
        url:"{!! route('content-sub-category.index1') !!}?id={{$id}}",
        success:function(data){
            $('#sub_category_tables').html('');
            $('#sub_category_tables').html(data);
            $.switcher('#sub_category_tables .changeStatusCustom');
        }
      })
    }

    // Edit Category
    $(document).on('click', '.editCategory', function(){
        $('#commonModalLabel').text('Edit Content Category');
        $('.save_button_span').text('Update Content Category');
        var id = $(this).data('id');
        var url = `{!! route('content-category.edit', ':id') !!}`.replace(':id', id);

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

    // create sub category
    $(document).on('click', '#createSubCategory', function() {
        $('#commonModalLabel').text('Add New Content Sub Category');
        $('.save_button_span').text('Save Content Sub Category');
        $.ajax({
          url:"{!! route('content-sub-category.create') !!}",
          success:function(data){
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);
            $('.single-select').select2({
                dropdownParent: $('.modal'),
                theme: 'bootstrap4',
        
            });
          }
        })
    });
    // edit sub category
    $(document).on('click', '.editSubCategory', function(){
        $('#commonModalLabel').text('Edit Content Sub Category');
        $('.save_button_span').text('Update Content Sub Category');
        var id = $(this).data('id');
        var url = `{!! route('content-sub-category.edit', ':id') !!}`.replace(':id', id);

        $.ajax({
          url:url,
          success:function(data){
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);
            $('.single-select').select2({
                dropdownParent: $('.modal'),
                theme: 'bootstrap4',
            });
          }
        })
    })
// Create Study Materials Modal
$(document).on('click', '#create_study_materials', function() {
    $('#commonModalLabel').text('New Study Materials');
    $('.save_button_span').text('Save Study Materials');
    $.ajax({
        url: "{{ route('study-materials-create') }}",
        success: function(data) {
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);
        }
    })
});
// Edit Study Materials Modal 
$(document).on('click', '#edit_study_materials', function() {
    var id = $(this).data('id');
    $('#commonModalLabel').text('Edit Study Materials');
    $('.save_button_span').text('Update Study Materials');
    var url = `{!! route('study-materials.edit', ':id') !!}`.replace(':id', id);

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

$(document).on('click', '.edit_study_material_types', function() {
    var id = $(this).data('id');
     $('#commonModalLabel').text('Edit Study Material Types');
        $('.save_button_span').text('Update Study Material Types');
        var url = `{!! route('study-material-types.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');
        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);

                  fetch_sub_category();
                } 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) {
            fetch_sub_category();
          }
          //return false;
        });
        //return false;
      });

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

                fetch_sub_category();
                } else {
                  var ErroMsg = $(this).printErrorMsg(response.message);
                  $(this).Toastshow('error', ErroMsg);
                }
              },
              error: function(data) {
                console.log("error ", data);
              }
            });
          }
        });
      });
</script>
@endsection
