@extends('layouts.app')
@section('title','Study Materials Files')
@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" />
<link href="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote.min.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"> Study Materials Files
    </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">Study Materials</li>
            <li class="breadcrumb-item active" aria-current="page"><i class="bi bi-dot"></i>  Study Materials Files </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-6">
            <h6><b>{{$course->course_title??''}}</b> / {{$materialType->name??''}} / {{$study_materials->title??''}} </h6>
        </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 createImage" data-bs-toggle="modal" data-bs-target="#commonModal" data-bs-placement="bottom" data-id="{{$material_id??''}}" title="Upload">
                    <i class="bi bi-plus-circle text-white"></i> New File Upload
                </button>
            </div>
            <div class="btn-group">
                <a href="{{route('study-material-types.details',['course_id'=>$course_id,'material_type_id'=>$material_type_id])}}" 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>

  <div class="row auto">
      <div class="col-xl-12 mx-auto">
          <div class="shadow-none radius-5 min-height">
              <div class="row">
                  <div class="col-md-12">
                      <div class="card">
                          <div class="card-body g-3" id="material_tables">
                            <div class="table-responsive">
                                <table id="example" class="table table-bordered align-middle" style="width:100%">
                                    <thead class="table-light">
                                        <tr>
                                            
                                            <th class="thbutton">Sl No.</th>
                                            <th>Document Details</th>
                                            <th>File Upload</th>
                                            {{--<th class="thbutton">Edit</th>--}}
                                            <th class="thbutton"> Delete</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        @php $i=1;@endphp
                                        @if($documents->count() > 0)
                                            @foreach($documents as $list)
                                            <tr>
                                                <td class="text-center">{{$i++}}</td>
                                                <td class="text-left">
                                                    <b>{!! $list->document_note?? '' !!}</b> 
                                                    <br>
                                                    <span class="btn btn-sm btn-outline-dark badge" style="font-size: 8px !important;"> {!! $list->file_types? strtoupper(fileTypes($list->file_types)):'' !!}</span>
                                                    
                                                </td>
                                                <td class="text-left">
                                                    @if(fileTypes($list->file_types)=='text')
                                                            {!! $list->file_url??''  !!}]
                                                    @else
                                                        <a href="{{getTempUrl($list->file_url)}}" download="download" target="_blank">View File</a>
                                                    @endif
                                                </td>
                                                {{--<td class="thbutton">
                                                    <a data-url="{{ route('study-materials-flies.destroy', $list->id) }}" class="btn btn-warning edit" class="text-danger" data-bs-toggle="tooltip" data-bs-placement="bottom" title="Edit">
                                                        <i class="bi bi-pencil-square text-white"></i>
                                                    </a>
                                                </td>--}}
                                                <td class="thbutton">
                                                    <a data-url="{{ route('study-materials-flies.destroy', $list->id) }}" class="btn btn-danger deleteDataCustom study_materials" class="text-danger" data-bs-toggle="tooltip" data-bs-placement="bottom" title="Delete">
                                                        <i class="bi bi-trash text-white"></i>
                                                    </a>
                                                </td>

                                            </tr>
                                            @endforeach
                                        @else
                                            <tr>
                                                <td colspan="4">No Data Found</td>
                                            </tr>
                                        @endif
                                    </tbody>

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

    <!--end row-->
@endsection
@section('js')
<script src="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote.min.js"></script>
<script type="text/javascript" src="{{ asset('admin/plugins/datepicker/js/bootstrap-datepicker.js')}}"></script>
<script type="text/javascript">
    /*********change status**********/
    $("body").on("click",'.changeStatusCustom', function(event){
    
        var UrlValue     = $(this).data('url');
        var status       = $(this).data('status');
        var changeStatus = $(this);

        Swal.fire({
            title: 'Are you sure you want to change status?',
            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',
                    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);

                            if($(this).hasClass('semesters')){
                                fetch_study_material_type();
                            }
                            else if ($(this).hasClass('study_materials')) {
                                fetch_study_material();
                            }

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

                if($(this).hasClass('semesters')){
                    fetch_study_material_type();
                }
                else if ($(this).hasClass('study_materials')) {
                    fetch_study_material();
                }
            }
            //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);
        //alert(dataValue);
        console.log($('meta[name="csrf-token"]').attr('content'));
        console.log(dataString);

        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){
                    console.log(response.data);
                    if(response.success){
                        var ErroMsg = $(this).printErrorMsg(response.message);

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

                        location.reload();
                    }else{
                        var ErroMsg = $(this).printErrorMsg(response.message);
                        $(this).Toastshow('error',ErroMsg);
                        location.reload();
                    }
                },
                error: function (data) {
                  console.log("error ",data);
                }
            });
            }
        });
    });

    $(document).on('click', '.createImage', function(){
        $('#commonModalLabel').text('Upload New Image');
        $('.save_button_span').text('Upload Image');
        $(".modal-dialog").addClass("modal-lg");
        var material_id = $(this).data('id');
        var url = `{!! route('study-materials-file.create', ':id') !!}`.replace(':id', material_id);
        $.ajax({
          url:url,
          success:function(data){
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);
            $('#notes').summernote();
          }
        })
    });

    $(document).on('click', '.save_button', function(event){
        event.preventDefault();
        var error = 0;

        if ($('#commonModal').find('form').hasClass('image')) {
            $('.error_file').hide();
            $('.error_title').hide();
            if ($('#commonModal').find('form').find('[name="attachment"]').val().trim() == '' && $('#commonModal').find('form').find('[name="video_url"]').val().trim()== '' && $('#commonModal').find('form').find('[name="notes"]').val().trim()=='') {
              $('.error_file').show();
              error = 1;
            }

            var account_id = $('#commonModal').find('form').find('input[name="account_id"]').data('id');
            $('#commonModal').find('form').find('input[name="account_id"]').val(account_id);

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

                                location.reload();

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