@extends('layouts.adminmaster')

		@section('styles')

		<!-- INTERNAL Data table css -->
		<link href="{{asset('build/assets/plugins/datatable/css/dataTables.bootstrap5.min.css')}}?v=<?php echo time(); ?>" rel="stylesheet" />
		<link href="{{asset('build/assets/plugins/datatable/responsive.bootstrap5.css')}}?v=<?php echo time(); ?>" rel="stylesheet" />

		<!-- INTERNAL Sweet-Alert css -->
		<link href="{{asset('build/assets/plugins/sweet-alert/sweetalert.css')}}?v=<?php echo time(); ?>" rel="stylesheet" />

        <style>
            #hideAfterloading {
                position: absolute;
                top: 100px;
                left: 45%;
            }
        </style>

		@endsection

							@section('content')

							<!--Page header-->
							<div class="page-header d-xl-flex d-block">
								<div class="page-leftheader">
									<h4 class="page-title"><span class="font-weight-normal text-muted ms-2">{{lang('Testimonial', 'menu')}}</span></h4>
								</div>
							</div>
							<!--End Page header-->

							<!--Testimonial Section-->
							<div class="col-xl-12 col-lg-12 col-md-12">
								<div class="card ">
									<form method="POST" action="{{url('/admin/testimonial')}}" enctype="multipart/form-data">
										@csrf

										@honeypot

										<div class="card-header border-0 d-sm-max-flex">
											<h4 class="card-title">{{lang('Testmonial Section')}}</h4>
											<div class="card-options card-header-styles mt-sm-max-2">
												<small class="me-1 mt-1">{{lang('Show Section')}}</small>
												<div class="float-end mt-0">
													<div class="switch-toggle">
														<a class="onoffswitch2">
															<input type="checkbox"  name="testimonialcheck" id="testimonialchecks" class=" toggle-class onoffswitch2-checkbox" value="on" @if($basic->testimonialcheck == 'on')  checked=""  @endif>
															<label for="testimonialchecks" class="toggle-class onoffswitch2-label" ></label>
														</a>
													</div>
												</div>
											</div>
										</div>
										<div class="card-body" >
											<div class="row">
												<div class="col-sm-12 col-md-12">
													<input type="hidden" class="form-control " name="id" value="{{$basic->id}}">
													<div class="form-group">
														<label class="form-label">{{lang('Title')}} <span class="text-red">*</span></label>
														<input type="text" class="form-control @error('testimonialtitle') is-invalid @enderror" name="testimonialtitle" value="{{$basic->testimonialtitle}}">
														@error('testimonialtitle')

															<span class="invalid-feedback d-block" role="alert">
																<strong>{{ lang($message) }}</strong>
															</span>
														@enderror

													</div>
												</div>
												<div class="col-sm-12 col-md-12">
													<div class="form-group">
														<label class="form-label">{{lang('Subtitle')}}</label>
														<input type="text" class="form-control @error('testimonialsub') is-invalid @enderror" name="testimonialsub" value="{{$basic->testimonialsub}}">
														@error('testimonialsub')

															<span class="invalid-feedback d-block" role="alert">
																<strong>{{ lang($message) }}</strong>
															</span>
														@enderror

													</div>
												</div>
											</div>
										</div>
										<div class="col-md-12 card-footer ">
											<div class="form-group float-end">
                                                <button type="submit" class="btn btn-secondary" onclick="this.disabled=true;this.innerHTML=`Saving <i class='fa fa-spinner fa-spin'></i>`;this.form.submit();">{{lang('Save Changes')}}</button>
											</div>
										</div>
									</form>
								</div>
							</div>
							<!--End Testimonial Section-->

							<!--Testimonial List-->
							<div class="col-xl-12 col-lg-12 col-md-12">
								<div class="card ">
									<div class="card-header border-0 d-sm-max-flex">
										<h4 class="card-title">{{lang('Testimonial List')}}</h4>
										<div class="card-options mt-sm-max-2">
											@can('Testimonial Create')

											<a href="javascript:void(0)" class="btn btn-secondary me-3" id="create-new-testimonial">{{lang('Add Testmonial')}}</a>
											@endcan

										</div>
									</div>
									<div class="card-body" style="min-height: 250px;">
										<div class="table-responsive spruko-delete">
											@can('Testimonial Delete')

											<button id="massdeletenotify" class="btn btn-outline-light btn-sm mb-4 data-table-btn" style="display: none;"><i class="fe fe-trash"></i> {{lang('Delete')}}</button>
											@endcan

											<table class="table table-bordered border-bottom text-nowrap ticketdeleterow w-100" id="support-articlelists">
												<thead>
													<tr>
														<th  width="10">{{lang('Sl.No')}}</th>
														@can('Testimonial Delete')

														<th width="10" >
															<input type="checkbox"  id="customCheckAll" class="form-check-input">
															<label  for="customCheckAll"></label>
														</th>
														@endcan
														@cannot('Testimonial Delete')

														<th width="10" >
															<input type="checkbox"  id="customCheckAll" class="form-check-input" disabled>
															<label  for="customCheckAll"></label>
														</th>
														@endcannot

														<th >{{lang('Name')}}</th>
														<th >{{lang('Designation')}}</th>
														<th >{{lang('Actions')}}</th>
													</tr>
												</thead>
                                                <div id="hideAfterloading"><img src="{{ asset('build/assets/images/loader.svg') }}" alt="">
                                                    <p>{{lang('loading.. Please Wait')}}</p>
                                                </div>
												{{-- <tbody>
													@php $i = 1; @endphp
													@foreach($testimonials as $testimonial)
														<tr>
															<td>{{$i++}}</td>
															<td>
																@if(Auth::user()->can('Testimonial Delete'))

																	<input type="checkbox" name="spruko_checkbox[]" class="checkall form-check-input" value="{{$testimonial->id}}" />
																@else

																	<input type="checkbox" name="spruko_checkbox[]" class="checkall form-check-input" value="{{$testimonial->id}}" disabled />
																@endif
															</td>
															<td>
																{{Str::limit($testimonial->name, '40')}}
															</td>
															<td>{{Str::limit($testimonial->designation, '40')}}</td>
															<td>
																<div class = "d-flex">
																@if(Auth::user()->can('Testimonial Edit'))

																	<a href="javascript:void(0)" data-id="{{$testimonial->id}}" class="action-btns1 edit-testimonial">
																		<i class="feather feather-edit text-primary" data-id="{{$testimonial->id}}"data-bs-toggle="tooltip" data-bs-placement="top" title="{{lang('Edit')}}"></i>
																	</a>
																@else
																	~
																@endif
																@if(Auth::user()->can('Testimonial Delete'))

																	<a href="javascript:void(0)" data-id="{{$testimonial->id}}" class="action-btns1" id="delete-testimonial" >
																		<i class="feather feather-trash-2 text-danger" data-id="{{$testimonial->id}}" data-bs-toggle="tooltip" data-bs-placement="top" title="{{lang('Delete')}}"></i>
																	</a>

																@else
																	~
																@endif

																</div>
															</td>
														</tr>
													@endforeach
												</tbody> --}}
											</table>
										</div>
									</div>
								</div>
							</div>
							<!--End Testimonial List-->

							@endsection
	@section('modal')

   	@include('admin.testimonial.model')

	@endsection

		@section('scripts')

		<!-- INTERNAL Vertical-scroll js-->
		<script src="{{asset('build/assets/plugins/vertical-scroll/jquery.bootstrap.newsbox.js')}}?v=<?php echo time(); ?>"></script>

		<!-- INTERNAL Data tables -->
		<script src="{{asset('build/assets/plugins/datatable/js/jquery.dataTables.min.js')}}?v=<?php echo time(); ?>"></script>
		<script src="{{asset('build/assets/plugins/datatable/js/dataTables.bootstrap5.js')}}?v=<?php echo time(); ?>"></script>
		<script src="{{asset('build/assets/plugins/datatable/dataTables.responsive.min.js')}}?v=<?php echo time(); ?>"></script>
		<script src="{{asset('build/assets/plugins/datatable/responsive.bootstrap5.min.js')}}?v=<?php echo time(); ?>"></script>
		<script src="{{asset('build/assets/plugins/datatable/datatablebutton.min.js')}}?v=<?php echo time(); ?>"></script>
		<script src="{{asset('build/assets/plugins/datatable/buttonbootstrap.min.js')}}?v=<?php echo time(); ?>"></script>

		<!-- INTERNAL Index js-->
        @vite(['resources/assets/js/support/support-sidemenu.js'])

		<!-- INTERNAL Sweet-Alert js-->
		<script src="{{asset('build/assets/plugins/sweet-alert/sweetalert.min.js')}}?v=<?php echo time(); ?>"></script>

        <script type="text/javascript">
            "use strict";

            document.addEventListener("DOMContentLoaded", (event) => {

                let tableData = @json($testimonials);

                let dateFormat = @json(setting('date_format'));
                let delPerm = @json(Auth::user()->can('Testimonial Delete'));
                let editPerm = @json(Auth::user()->can('Testimonial Edit'));

                var dataTable;
                var tableDropDown;

                loadTable(tableData);

                function truncateTitle(title) {
                    const maxLength = 40;
                    return title.length > maxLength ? title.substring(0, maxLength) + '...' : title;
                }

                function loadTable(tableData) {
                    document.getElementById('hideAfterloading')?.classList.remove('d-none');
                    document.getElementById('theadShow')?.classList.add('d-none');
                    if (tableDropDown)
                        tableDropDown.destroy();

                    if (dataTable)
                        dataTable.destroy();

                    if (document.getElementById('tableBody'))
                        document.getElementById('tableBody').remove();

                    let createTbody = document.createElement('tbody');
                    createTbody.setAttribute('id', "tableBody");
                    let rows = tableData.map((data, index) => {

                        return `
                            <tr>
                                <td>${index + 1}</td>
                                <td class="text-center">
                                    ${delPerm
                                        ? `<input type="checkbox" name="spruko_checkbox[]" class="checkall form-check-input" value="${data.id}" />`
                                        : '~'
                                    }

                                </td>

                                <td>${data.name ? truncateTitle(data.name) : ''}</td>

                                <td>${ data.designation ? truncateTitle(data.designation) : ''}</td>

                                <td>
                                    <div class = "d-flex">

                                        ${editPerm ? `<a href="javascript:void(0)" data-id="${data.id}" class="action-btns1 edit-testimonial"><i class="feather feather-edit text-primary" data-id="${data.id}"data-bs-toggle="tooltip" data-bs-placement="top" title="{{lang('Edit')}}"></i></a>` : '~'
                                        }
                                        ${delPerm ? `<a href="javascript:void(0)" data-id="${data.id}" class="action-btns1" id="delete-testimonial" ><i class="feather feather-trash-2 text-danger" data-id="${data.id}" data-bs-toggle="tooltip" data-bs-placement="top" title="{{lang('Delete')}}"></i></a>` : '~'
                                        }
                                    </div>

                                </td>

                            </tr>
                        `;
                    });

                    if (tableData.length == 0)
                        createTbody.innerHTML = ` `;
                    else
                        createTbody.innerHTML = rows.join('');


                    // Append the tbody to your table
                    // Replace 'your-table-id' with the actual ID of your table element
                    document.getElementById('support-articlelists').appendChild(createTbody);

                    document.getElementById('hideAfterloading')?.classList.add('d-none');
                    document.getElementById('theadShow')?.classList.remove('d-none');

                    // var myTable = document.querySelector("#support-category");

                    $(document).ready(function() {

                        var SITEURL = '{{ url('') }}';

                        // Csrf field
                        $.ajaxSetup({
                            headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                            }
                        });

                        let prev = {!! json_encode(lang("Previous")) !!};
                        let next = {!! json_encode(lang("Next")) !!};
                        let nodata = {!! json_encode(lang("No data available in table")) !!};
                        let noentries = {!! json_encode(lang("No entries to show")) !!};
                        let showing = {!! json_encode(lang("showing page")) !!};
                        let ofval = {!! json_encode(lang("of")) !!};
                        let maxRecordfilter = {!! json_encode(lang("- filtered from ")) !!};
                        let maxRecords = {!! json_encode(lang("records")) !!};
                        let entries = {!! json_encode(lang("entries")) !!};
                        let show = {!! json_encode(lang("Show")) !!};
                        let search = {!! json_encode(lang("Search")) !!};
                        // Datatable
                        $('#support-articlelists').dataTable({
                            language: {
                                searchPlaceholder: search,
                                scrollX: "100%",
                                sSearch: '',
                                paginate: {
                                previous: prev,
                                next: next
                                },
                                emptyTable : nodata,
                                infoFiltered: `${maxRecordfilter} _MAX_ ${maxRecords}`,
                                info: `${showing} _PAGE_ ${ofval} _PAGES_`,
                                infoEmpty: noentries,
                                lengthMenu: `${show} _MENU_ ${entries} `,
                            },
                            order:[],
                            columnDefs: [
                                { "orderable": false, "targets":[ 0,1,4] }
                            ],
                        });

                        $('.form-select').select2({
                            minimumResultsForSearch: Infinity,
                            width: '100%'
                        });

                        $('.form-select').on('focus', function() {
                            $(this).attr('aria-hidden', 'false');
                        });
                    });


                    initializeTooltips();

                    function initializeTooltips() {
                        var tooltipElements = document.querySelectorAll('[data-bs-toggle="tooltip"]');
                        tooltipElements.forEach(function(element) {
                            new bootstrap.Tooltip(element);
                        });
                    }


                }

                $(function() {
                    (function($)  {

                        // Variables
                        var SITEURL = '{{url('')}}';

                        /*  When user click add testimonial button */
                        $('#create-new-testimonial').on('click', function () {
                            // $('#btnsave').val("create-product");
                            $('#btnsave').html("{{lang('Save')}}");
                            $('#testimonial_id').val('');
                            $('#testimonial_form').trigger("reset");
                            $('.modal-title').html("{{lang('Add New Testmonial')}}");
                            $('#testimonialimgdiv').addClass('d-none');
                            $('#addtestimonial').modal('show');
                            $('#image-preview').attr('src', '{{asset('build/assets/images/imagepreview/displayimage.png')}}');
                        });

                        /* When click edit testimonial */
                        $('body').on('click', '.edit-testimonial', function () {
                            var testimonial_id = $(this).data('id');
                            $.get('testimonial/' + testimonial_id , function (data) {
                                $('#nameError').html('');
                                $('#descriptionError').html('');
                                $('#designationError').html('');
                                $('#imageError').html('');

                                $('.modal-title').html("{{lang('Edit Testimonial')}}");
                                // $('#btnsave').val("edit-testimonial");
                                $('#btnsave').html("{{lang('Update')}}");
                                $('#addtestimonial').modal('show');
                                $('#testimonial_id').val(data.id);
                                $('#name').val(data.name);
                                $('#designation').val(data.designation);
                                $('#description').val(data.description);
                                $('#image-preview').attr('alt', 'No image available');
                                if(data.imageurl){
                                    $('#testinmonilalimage').attr('src', data.imageurl);
                                    $('.delete-image').attr('data-id', data.id);
                                    $('#testimonialimgdiv').removeClass('d-none');
                                }else{
                                    $('#testimonialimgdiv').addClass('d-none');
                                }
                            })
                        });

                        // Delete Testimonial image
                        $('body').on('click', '.delete-image', function () {
                            var testiId = $(this).data("id");
                            swal({
                                title: `{{lang('Are you sure you want to continue?', 'alerts')}}`,
                                text: "{{lang('This might erase your records permanently', 'alerts')}}",
                                icon: "warning",
                                buttons: true,
                                dangerMode: true,
                            })
                            .then((willDelete) => {
                                if (willDelete) {
                                    $.ajax({
                                        type: "post",
                                        url: SITEURL + "/admin/testimonial/imagedelete/" +testiId,
                                        success: function (data) {
                                            toastr.success(data.success);
                                            $('#testimonialimgdiv').addClass('d-none');
                                        },
                                        error: function (data) {
                                            console.log('Error:', data);
                                        }
                                    });
                                }
                            });
                        });

                        // Delete Testimonial
                        $('body').on('click', '#delete-testimonial', function () {
                            let parent = $(this).closest('tr');
                            var _id = $(this).data("id");
                            swal({
                                title: `{{lang('Are you sure you want to continue?', 'alerts')}}`,
                                text: "{{lang('This might erase your records permanently', 'alerts')}}",
                                icon: "warning",
                                buttons: true,
                                dangerMode: true,
                            })
                            .then((willDelete) => {
                                if (willDelete) {
                                    $.ajax({
                                        type: "get",
                                        url: SITEURL + "/admin/testimonial/delete/"+_id,
                                        success: function (data) {
                                            toastr.success(data.success);
                                            // location.reload();
                                            $(parent[0]).addClass('fade-out');
                                            let newData = tableData.filter(item => item.id != parseInt(_id));
                                            tableData = newData;
                                            setTimeout(() => {
                                                parent[0].remove();
                                                if ($.fn.DataTable.isDataTable('#support-articlelists')) {
                                                    $('#support-articlelists').DataTable().clear().destroy();
                                                }
                                                loadTable(tableData);
                                            }, 1500);
                                        },
                                        error: function (data) {
                                            console.log('Error:', data);
                                        }
                                    });
                                }
                            });
                        });

                        // Mass Delete Testimonial
                        $('body').on('click', '#massdeletenotify', function () {
                            var parent = [];
                            var id = [];
                            $('.checkall:checked').each(function(){
                                parent.push($(this).closest('tr'));
                                id.push($(this).val());
                            });
                            if(id.length > 0){
                                swal({
                                    title: `{{lang('Are you sure you want to continue?', 'alerts')}}`,
                                    text: "{{lang('This might erase your records permanently', 'alerts')}}",
                                    icon: "warning",
                                    buttons: true,
                                    dangerMode: true,
                                })
                                .then((willDelete) => {
                                    if (willDelete) {
                                        $.ajax({
                                            url:"{{ route('testimonial.deleteall')}}",
                                            method:"post",
                                            data:{id:id},
                                            success:function(data)
                                            {
                                                toastr.success(data.success);
                                                parent.forEach(function(row) {
                                                    row.addClass('fade-out');
                                                });
                                                let newData = tableData.filter(item => !id.includes(String(item.id)));
                                                tableData = newData;
                                                setTimeout(() => {
                                                    parent.forEach(function(row) {
                                                        row.remove();
                                                    });
                                                    if ($.fn.DataTable.isDataTable('#support-articlelists')) {
                                                        $('#support-articlelists').DataTable().clear().destroy();
                                                    }
                                                    $('#customCheckAll').prop('checked', false);
                                                    loadTable(tableData);
                                                }, 1500);

                                            },
                                            error:function(data){
                                                console.log(data);
                                            }
                                        });
                                    }
                                });
                            }else{
                                toastr.error('{{lang('Please select at least one check box.', 'alerts')}}');
                            }


                        });

                        // Testimonial submit form
                        $('body').on('submit', '#testimonial_form', function (e) {
                            e.preventDefault();
                            var actionType = $('#btnsave').val();
                            var fewSeconds = 2;
                            $('#btnsave').html('Sending ... <i class="fa fa-spinner fa-spin"></i>');
                            $('#btnsave').prop('disabled', true);
                                setTimeout(function(){
                                    $('#btnsave').prop('disabled', false);
                                }, fewSeconds*1000);
                            var formData = new FormData(this);
                            $.ajax({
                            type:'POST',
                            url: SITEURL + "/admin/testimonial/create",
                            data: formData,
                            cache:false,
                            contentType: false,
                            processData: false,

                            success: (data) => {
                                $('#nameError').html('');
                                $('#descriptionError').html('');
                                $('#designationError').html('');
                                $('#imageError').html('');

                                $('#testimonial_form').trigger("reset");
                                $('#addtestimonial').modal('hide');
                                $('#btnsave').html('{{lang('Save Changes')}}');
                                toastr.success(data.success);
                                // location.reload();
                                if ($.fn.DataTable.isDataTable('#support-articlelists')) {
                                    $('#support-articlelists').DataTable().clear().destroy();
                                }
                                tableData = data.testimonials;
                                loadTable(tableData);
                            },
                            error: function(data){

                                $('#nameError').html('');
                                $('#descriptionError').html('');
                                $('#designationError').html('');
                                $('#imageError').html('');
                                $('#nameError').html(data.responseJSON.errors.name);
                                $('#descriptionError').html(data.responseJSON.errors.description);
                                $('#designationError').html(data.responseJSON.errors.designation);
                                $('#imageError').html(data.responseJSON.errors.image);
                                $('#btnsave').html('{{lang('Save Changes')}}');
                            }
                            });
                        });

                        //checkbox script
                        $(document).ready(function() {

                            $(document).on('click', '#customCheckAll', function() {
                                $('.checkall').prop('checked', this.checked);
                                updateMassDeleteVisibility();
                            });

                            $(document).on('click', '.checkall', function() {
                                updateCustomCheckAll();
                                updateMassDeleteVisibility();
                            });


                            $(document).on('click', '.pagination a', function() {

                                setTimeout(function() {
                                    updateMassDeleteVisibility();
                                }, 100);
                            });


                            $('#customCheckAll').prop('checked', false);


                            function updateMassDeleteVisibility() {
                                if ($('.checkall:checked').length == 0) {
                                    $('#massdeletenotify').hide();
                                } else {
                                    $('#massdeletenotify').show();
                                }
                            }


                            function updateCustomCheckAll() {
                                var totalCheckboxes = $('.checkall').length;
                                var checkedCheckboxes = $('.checkall:checked').length;

                                if (checkedCheckboxes === totalCheckboxes) {
                                    $('#customCheckAll').prop('checked', true);
                                } else {
                                    $('#customCheckAll').prop('checked', false);
                                }
                            }
                        });


                    })(jQuery);
                });
            });
		</script>

		@endsection
