@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" />
		<link href="{{asset('build/assets/plugins/datatable/buttonbootstrap.min.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('Agent View Reports')}}</span></h4>
								</div>
							</div>
							<!--End Page header-->

                            <div class="row">
								<div class="col-xl-3 col-lg-4 col-md-12">
									<div class="card user-pro-list overflow-hidden">
										<div class="card-body">
											<div class="user-pic text-center">
												@if ($users->image == null)

                                                <img src="{{asset('uploads/profile/user-profile.png')}}" class="avatar avatar-xxl brround" alt="">

												@else
                                                <img src="{{ route('getprofile.url', ['imagePath' =>$users->image,'storage_disk'=>$users->storage_disk ?? 'public']) }}" class="avatar avatar-xxl brround" alt="">

												@endif
												<div class="pro-user mt-3">
													<h5 class="pro-user-username text-dark mb-1 fs-16">{{$users->name}}</h5>
													<h6 class="pro-user-desc text-muted fs-12">{{$users->email}}</h6>
													@if(!empty($users->getRoleNames()[0]))
													<h6 class="pro-user-desc text-muted fs-12">{{ $users->getRoleNames()[0]}}</h6>
													@endif
													{{-- <div class="profilerating" data-rating="{{$avg}}"></div> --}}
												</div>
											</div>
										</div>
									</div>
									<div class="card">
										<div class="card-header border-0">
											<h4 class="card-title"> {{lang('Personal Details')}}</h4>
										</div>
										<div class="card-body px-0 pb-0">

											<div class="table-responsive tr-lastchild">
												<table class="table mb-0 table-information">
													<tbody>
														<tr>
															<td class="py-2">
																<span class="font-weight-semibold w-50"> {{lang('Employee ID')}}</span>
															</td>
															<td class="py-2 ps-4">{{$users->empid}}</td>
														</tr>
														<tr>
															<td class="py-2">
																<span class="font-weight-semibold w-50"> {{lang('Name')}} </span>
															</td>
															<td class="py-2 ps-4">{{$users->name}}</td>
														</tr>
														<tr>
															<td class="py-2">
																<span class="font-weight-semibold w-50"> {{lang('Role Name')}} </span>
															</td>
															<td class="py-2 ps-4">
																@if(!empty($users->getRoleNames()[0]))

																 {{$users->getRoleNames()[0]}}
																 @endif

															</td>
														</tr>
														<tr>
															<td class="py-2">
																<span class="font-weight-semibold w-50"> {{lang('Email')}} </span>
															</td>
															<td class="py-2 ps-4">{{$users->email}}</td>
														</tr>
														<tr>
															<td class="py-2">
																<span class="font-weight-semibold w-50"> {{lang('Phone')}} </span>
															</td>
															<td class="py-2 ps-4">{{$users->phone}}</td>
														</tr>
														<tr>
															<td class="py-2">
																<span class="font-weight-semibold w-50"> {{lang('Languages')}} </span>
															</td>
															<td class="py-2 ps-4">
																@php
																$values = explode(",", $users->languagues);

																@endphp

																<ul class="custom-ul">
																	@foreach ($values as $value)

																	<li class="tag mb-1">{{ucfirst($value)}}</li>

																	@endforeach

																</ul>
															</td>
														</tr>
														<tr>
															<td class="py-2">
																<span class="font-weight-semibold w-50">{{lang('Skills')}} </span>
															</td>
															<td class="py-2 ps-4">
																@php
																$values = explode(",", $users->skills);
																@endphp

																<ul class="custom-ul">
																	@foreach ($values as $value)

																	<li class="tag mb-1">{{ucfirst($value)}}</li>

																	@endforeach

																</ul>
															</td>
														</tr>
														<tr>
															<td class="py-2">
																<span class="font-weight-semibold w-50"> {{lang('Location')}} </span>
															</td>
															<td class="py-2 ps-4">{{$users->country}}</td>
														</tr>

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

								</div>
								<div class="col-xl-9 col-lg-8 col-md-12">
									<div class="card">
										<div class="card-header border-0">
											<h4 class="card-title">{{lang('Agent View Reports')}}</h4>
										</div>
										<div class="card-body" style="min-height: 250px;">
											<div class="table-responsive">
												<table class="table border-bottom table-bordered w-100" id="reports">
													<thead>
														<tr>
															<th width="10">{{lang('Sl.No')}}</th>
															<th>#{{lang('ID')}}</th>
															<th>{{lang('Rating')}}</th>
															<th>{{lang('Ticket Comment')}}</th>
															<th>{{lang('Ticket Customer')}}</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>
												</table>
											</div>
										</div>
									</div>
								</div>
							</div>
							<!--Reports List-->

							<!--End Reports List-->

  							@endsection


  		@section('scripts')


		<!-- 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 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($employeeratings);

                let dateFormat = @json(setting('date_format'));

                var dataTable;
                var tableDropDown;

                loadTable(tableData);

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

                function dateTime(createdTime) {

                    const jsDate = new Date(createdTime);

                    let format = @json(setting('date_format'));
                    switch (format) {
                        case 'd M, Y':
                            return jsDate.toLocaleDateString('en-GB', {
                                day: '2-digit',
                                month: 'short',
                                year: 'numeric'
                            });
                        case 'm.d.y':
                            return jsDate.toLocaleDateString('en-US', {
                                day: '2-digit',
                                month: '2-digit',
                                year: '2-digit'
                            }).replace(/\//g, '.');
                        case 'Y-m-d':
                            return jsDate.toISOString().split('T')[0];
                        case 'd-m-Y':
                            return jsDate.toLocaleDateString('en-GB').replace(/\//g, '-');
                        case 'd/m/Y':
                            return jsDate.toLocaleDateString('en-GB');
                        case 'Y/m/d':
                            return jsDate.toISOString().split('T')[0].replace(/-/g, '/');
                        default:
                            return jsDate.toLocaleDateString(); // Default format
                    }

                }

                function generateProfileUrl(imagePath, storageDisk) {
                    var baseUrl = "{{ route('getprofile.url', ['imagePath' => ':imagePath', 'storage_disk' => ':storage_disk']) }}";
                    return baseUrl.replace(':imagePath', encodeURIComponent(imagePath)).replace(':storage_disk', encodeURIComponent(storageDisk));
                }

                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>
                                    <a href="${data.viewRoteUrl}" target="_blank">${data.ticket_id}</a>
                                </td>

                                <td>
                                    <div class="allemployeerating pt-1 text-nowrap" data-rating="${data.rating}"></div>
                                </td>

                                ${data.ticketdata.length > 0 ?
                                    data.ticketdata.map((ticket) => {
                                        return `
                                            <td>${ticket.ratingcomment}</td>
                                            <td>
                                                ${ticket.customer.username}
                                            </td>`;
                                    }).join('')
                                    :
                                    `<td></td>
                                    <td></td>`
                                }

                                <td>
                                    <div class = "d-flex">
                                        ${data.ticketdata.length > 0 ?
                                            `<a href="javascript:void(0);" class="action-btns1 delete-report" data-id="${data.id}" data-bs-toggle="tooltip" data-bs-placement="top" title="{{lang('Delete')}}"><i class="feather feather-trash-2 text-danger"></i></a>`
                                            :
                                            '~'
                                        }
                                </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('reports').appendChild(createTbody);

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

                    $(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
                        $('#reports').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() {

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

                    $(".allemployeerating").starRating({
                        readOnly: true,
                        starSize: 25,
                        emptyColor  :  '#ffffff',
                        activeColor :  '#F2B827',
                        strokeColor :  '#F2B827',
                        strokeWidth :  15,
                        useGradient : false
                    });

                    // Delete Testimonial
                    $('body').on('click', '.delete-report', 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: "post",
                                    url: SITEURL + "/admin/reports/ratingticket/delete/"+_id,
                                    success: function (data) {
                                        toastr.success(data.success);
                                        $(parent[0]).addClass('fade-out');
                                        let newData = tableData.filter(item => item.id != parseInt(_id));
                                        tableData = newData;
                                        setTimeout(() => {
                                            parent[0].remove();
                                            if ($.fn.DataTable.isDataTable('#reports')) {
                                                $('#reports').DataTable().clear().destroy();
                                            }
                                            loadTable(tableData);
                                        }, 1500);
                                    },
                                    error: function (data) {
                                        console.log('Error:', data);
                                    }
                                });
                            }
                        });
                    });
                });
            });

		</script>
  @endsection
