@extends('layouts.adminmaster')

@section('styles')
    <!-- INTERNAL Datepicker css-->
    <link href="{{asset('build/assets/plugins/modal-datepicker/datepicker.css')}}?v=<?php echo time(); ?>" rel="stylesheet" />
@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('Employee Activity') }}</span></h4>
        </div>
    </div>
    <!--End Page header-->

    <!--Reports List-->
    <div class="row">
        <div class="col-xl-9" id="activityList">
            @php
                $today = \Carbon\Carbon::parse(now())->format('Y-m-d');
                $yesterday = \Carbon\Carbon::yesterday()->format('Y-m-d');

                // Group activities by date
                $groupedActivities = $activity->groupBy(function ($item) use ($today, $yesterday) {
                    $createdat = \Carbon\Carbon::parse($item->created_at)->format('Y-m-d');
                    if ($createdat == $today) {
                        return 'Today';
                    } elseif ($createdat == $yesterday) {
                        return 'Yesterday';
                    } else {
                        return $createdat;
                    }
                });
            @endphp

            @foreach($groupedActivities as $dateLabel => $activities)
                @if ($dateLabel == 'Today' || $dateLabel == 'Yesterday')
                    <div class="fw-semibold fs-16 mb-3">{{ lang($dateLabel) }}</div>
                @else
                    <div class="fw-semibold fs-16 mb-3">{{ \Carbon\Carbon::parse($dateLabel)->timezone(setting('default_timezone'))->format(setting('date_format')) }}</div>
                @endif


                @forelse($activities as $activiti)
                    <div class="card mb-3 border-0">
                        <div class="d-flex p-3">
                            <div class="d-flex align-items-top">
                                @if ($activiti->user->image == null)
                                    <img src="{{ asset('uploads/profile/user-profile.png') }}" class="avatar-lg rounded-circle me-3 my-auto" alt="">
                                @else
                                    <img src="{{ asset('uploads/profile/' . $activiti->user->image) }}" class="avatar-lg rounded-circle me-3 my-auto" alt="">
                                @endif
                                <div class="d-flex gap-3">
                                    <a href="javascript:void(0);" class="font-weight-semibold">{{ $activiti->user->name }}</a>
                                    <span class="font-weight-bold text-dark">{{ lang($activiti->activity_type) }}</span>
                                    @if($activiti->ticket_id)
                                        <span class="font-weight-semibold">{{ 'SPG-'. $activiti->ticket_id }}</span>
                                    @endif
                                    <span class="">{{ $activiti->created_at->timezone(setting('default_timezone'))->format('d,M Y') }}</span>
                                    <span class="text-muted ">{{ $activiti->created_at->timezone(setting('default_timezone'))->format('h:i:sA') }}</span>
                                    <a href="javascript:void(0);" class="text-primary ">{{ $activiti->ip_address }}</a>
                                    @if ($activiti->browser)
                                        <span class="text-muted ms-2">{{ $activiti->browser }}</span>
                                    @endif
                                    @if ($activiti->device)
                                        <span class="text-muted ms-2">{{ $activiti->device }}</span>
                                    @endif
                                </div>
                            </div>
                        </div>
                    </div>
                @endforeach
            @endforeach

            {{ $activity->links('admin.notificationpagination') }}
        </div>


        <div class="col-xl-3 col-md-12 col-lg-4 mt-5 mt-lg-0">
            <div class="card">
                <div class="card-header border-0">
                    <h4 class="card-title">{{ lang('Filter Employee Activity') }}</h4>
                </div>

                <div class="search-container m-2">
                    <input type="text" id="searchInput" placeholder="Search..." class="form-control" />
                </div>

                <div class="search-container m-2">
                    <input class="form-control fc-datepicker" placeholder="YYYY-MM-DD" type="text" id="datesearchInput" autocomplete="off" />
                </div>

            </div>
        </div>
    </div>
    <!--End Reports List-->
@endsection


@section('scripts')
    <script src="{{asset('build/assets/plugins/jquery/jquery-ui.js')}}?v=<?php echo time(); ?>"></script>

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

        document.addEventListener('DOMContentLoaded', function() {
            let activity = @json($jsempactivity);
            const searchInput = document.getElementById('searchInput');
            const dateSearchInput = document.getElementById('datesearchInput');
            const activityList = document.getElementById('activityList');
            var SITEURL = '{{ url('') }}';

            function renderActivities(activities) {
                // Clear the previous list
                activityList.innerHTML = '';

                // Check if there are any activities to display
                if (activities.length === 0) {
                    const noResultsCard = document.createElement('div');
                    noResultsCard.className = 'text-center mt-3';
                    noResultsCard.innerHTML = `
                        <span class="font-weight-bold text-dark">{{ lang('No results found') }}</span>
                    `;
                    activityList.appendChild(noResultsCard);
                    return;
                }

                // Render each activity card
                activities.forEach(activityData => {
                    const card = document.createElement('div');
                    card.className = 'card mb-3 border-0';
                    card.innerHTML = `
                        <div class="d-flex p-3">
                            <div class="d-flex align-items-top">
                                <img src="${activityData.user.image ? SITEURL + '/uploads/profile/' + activityData.user.image : SITEURL + '/uploads/profile/user-profile.png'}" class="avatar-lg rounded-circle me-3 my-auto" alt="">
                                <div class="d-flex gap-3">
                                    <a href="javascript:void(0);" class="font-weight-semibold">${activityData.user.name}</a>
                                    <span class="font-weight-bold text-dark">${activityData.activity_type}</span>
                                    ${activityData.ticket_id ? `<span class="font-weight-semibold">${'SPG-' + activityData.ticket_id}</span>` : ''}
                                    <span class="">${dateTime(activityData.created_at)}</span>
                                    <span class="text-muted">${new Date(activityData.created_at).toLocaleTimeString()}</span>
                                    <a href="javascript:void(0);" class="text-primary">${activityData.ip_address}</a>
                                    ${activityData.browser ? `<span class="text-muted ms-2">${activityData.browser}</span>` : ''}
                                    ${activityData.device ? `<span class="text-muted ms-2">${activityData.device}</span>` : ''}
                                </div>
                            </div>
                        </div>
                    `;
                    activityList.appendChild(card);
                });
            }

            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 filterActivities() {
                const filterText = searchInput.value.toLowerCase();
                const selectedDate = dateSearchInput.value; // Format: YYYY-MM-DD

                if(!filterText && !selectedDate){
                    // location.reload();
                    renderActivities(activity);
                }

                const filteredActivities = activity.filter(activityData => {

                    const activityType = activityData.activity_type.toLowerCase();
                    const browser = activityData.browser ? activityData.browser.toLowerCase() : '';
                    const userName = activityData.user.name.toLowerCase();
                    const ticketId = activityData.ticket_id;

                    // Date comparison
                    const activityDate = new Date(activityData.created_at).toISOString().split('T')[0]; // Get YYYY-MM-DD

                    // Check against both text filter and date filter
                    const matchesTextFilter =
                        activityType.indexOf(filterText) > -1 ||
                        browser.indexOf(filterText) > -1 ||
                        userName.indexOf(filterText) > -1 ||
                        (ticketId !== null && ticketId !== undefined && ticketId.toString().indexOf(filterText) > -1);

                    const matchesDateFilter = selectedDate === '' || activityDate === selectedDate;

                    return matchesTextFilter && matchesDateFilter;
                });

                // Render filtered activities
                renderActivities(filteredActivities);
            }

            // Debounce function
            function debounce(func, delay) {
                let timeout;
                return function(...args) {
                    clearTimeout(timeout);
                    timeout = setTimeout(() => func.apply(this, args), delay);
                };
            }

            // Event listeners for search input and date input
            const debouncedFilterActivities = debounce(filterActivities, 500);
            searchInput.addEventListener('keyup', debouncedFilterActivities);
            // dateSearchInput.addEventListener('change', filterActivities);

            $('#datesearchInput').datepicker({
                dateFormat: 'yy-mm-dd',
                prevText: '<i class="fa fa-angle-left"></i>',
                nextText: '<i class="fa fa-angle-right"></i>',
                firstDay: {{ setting('start_week') }},
                onSelect: function() {
                    filterActivities();
                }
            });
        });

    </script>
@endsection
