@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" />

	<link href="{{asset('build/assets/plugins/rater-js/rater-js.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('Livechat Reports', 'menu')}}</span></h4>
    </div>
</div>
<!--End Page header-->

<div class="col-xl-12 col-lg-12 col-md-12">
    <div class="card mb-0">
        <div class="card-header d-sm-max-flex border-0">
            <h4 class="card-title">{{lang('Livechat Reports List')}}</h4>
        </div>
        <div class="card-body" style="min-height: 250px;">
            <div class="table-responsive spruko-delete">
                <button id="massdelete" class="btn btn-outline-light btn-sm mb-4 d-none data-table-btn"><i class="fe fe-trash"></i> {{lang('Delete')}}</button>

                <table class="table table-bordered border-bottom text-nowrap ticketdeleterow w-100" id="liveChatReviewTable">
                    <thead>
                        <tr>
                            <th  width="9">{{lang('Sl.No')}}</th>
                            <th width="10" >{{lang('User Title')}}</th>
                            <th width="10" >{{lang('Rating')}}</th>
                            <th width="10" >{{lang('Overall Rating')}}</th>
                            <th width="10" >{{lang('Total Answered chats')}}</th>
                            <th width="10" >{{lang('Action')}}</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 ($users as $user)
                            <tr>
                                <td>{{$i++}}</td>
                                <td>{{$user->name}}</td>
                                <td>

                                    <div class="star-ratings start-ratings-main mb-2 mt-1  clearfix">
                                        @php
                                            $count = 0;
                                            foreach($reviewsData as $review) {
                                                if ($review->users_id == $user->id) {
                                                    $count += $review->starRating;
                                                }
                                            };
                                            if($reviewsData->count() != 0){
                                                $totalrating = $count/$reviewsData->count();
                                            }else{
                                                $totalrating = 0;
                                            }
                                        @endphp

                                        <span class="star-rating" style="width: 100px; height: 20px; background-size: 20px;">
                                            <span class="star-value" style="background-size: 20px; width: {{ ($totalrating / 5) * 100 }}%;">
                                            </span>
                                        </span>

                                    </div>
                                </td>
                                @php
                                    $count = 0;
                                    foreach($reviewsData as $review) {
                                        if ($review->users_id == $user->id) {
                                            $count++;
                                        }
                                    };
                                @endphp
                                <td>{{$count}}</td>
                                <td>{{$user->TotalAnsweredTicket ? $user->TotalAnsweredTicket : 0}}</td>
                                <td>
                                    <div class="d-flex">
                                        <a href="{{route('admin.livechatEmpliyerRatings',['id' => $user->id])}}" class="action-btns1"
                                        data-bs-toggle="tooltip" data-bs-placement="top"
                                        title="" data-bs-original-title="View"
                                        aria-label="View">
                                        <i class="feather feather-eye text-primary"></i>
                                        </a>
                                    </div>
                                </td>
                            </tr>
                        @endforeach
                    </tbody> --}}
                </table>
            </div>
        </div>
    </div>
</div>
@endsection

@section('scripts')

<!-- INTERNAL Data tables -->
<script src="{{asset('build/assets/plugins/datatable/js/jquery.dataTables.min.js')}}"></script>
<script src="{{asset('build/assets/plugins/datatable/js/dataTables.bootstrap5.js')}}"></script>
<script src="{{asset('build/assets/plugins/datatable/dataTables.responsive.min.js')}}"></script>
<script src="{{asset('build/assets/plugins/datatable/responsive.bootstrap5.min.js')}}"></script>
<script src="{{asset('build/assets/plugins/rater-js/rater-js.js')}}"></script>

@vite(['resources/assets/js/select2.js'])

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

<script>
    "use strict";

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

        let tableData = @json($users);
        let reviewsData = @json($reviewsData);

        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) => {

                var countdata = 0;
                var totalrating;
                reviewsData.map((data1, index1) => {
                    if(data1.users_id == data.id){
                        countdata += data1.starRating;
                    }
                });
                if(reviewsData.length != 0){
                    totalrating = countdata/reviewsData.length;
                }else{
                    totalrating = 0;
                }

                var countemp = 0;
                reviewsData.map((data2, index2) => {
                    if(data2.users_id == data.id){
                        countemp++;
                    }
                });

                var routeUrl = "{{ route('admin.livechatEmpliyerRatings', ['id' => ':id']) }}".replace(':id', data.id);

                return `
                    <tr>
                        <td>${index + 1}</td>
                        <td>${data.name}</td>

                        <td>
                            <div class="star-ratings start-ratings-main mb-2 mt-1 clearfix">
                                <span class="star-rating" style="width: 100px; height: 20px; background-size: 20px;">
                                    <span class="star-value" style="background-size: 20px; width: ${(totalrating / 5) * 100}%;">
                                    </span>
                                </span>
                            </div>
                        </td>

                        <td>${countemp}</td>

                        <td>${data.TotalAnsweredTicket ? data.TotalAnsweredTicket : 0}</td>

                        <td>
                            <div class="d-flex">
                                <a href="${routeUrl}" class="action-btns1"
                                data-bs-toggle="tooltip" data-bs-placement="top"
                                title="" data-bs-original-title="View"
                                aria-label="View">
                                <i class="feather feather-eye text-primary"></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('liveChatReviewTable').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")) !!};

                $('#liveChatReviewTable').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] }
                    ],
                });

                // select2 js
                $('.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($){
                $('.form-select').select2({
                    minimumResultsForSearch: Infinity,
                    width: '100%'
                });
            })(jQuery);
        });

    });

</script>


@endsection
