@extends('layouts.adminmaster')
@section('styles')
    <link href="{{asset('build/assets/plugins/sweet-alert/sweetalert.css')}}?v=<?php echo time(); ?>" rel="stylesheet" />
<style>
    .checkforactive {
        cursor: pointer;
    }
    .dark-mode .main-chart-wrapper .chat-info {
        background-color: #191d43 !important
    }
    .dark-mode .main-chart-wrapper .chat-info ul li.checkforactive {
        border: 1px solid rgba(255, 255, 255, 0.1);
    }
    .dark-mode .checkforactive.active,
    .dark-mode .chat-reply-area {
        background-color: #191d43 !important
    }
    .chat-content li {
        border: 0 !important;
    }
    .dark-mode .main-chart-wrapper .main-chat-area .chat-content .main-chat-msg div p {
        color: #f1f4fb;
    }
    .dark-mode .main-chart-wrapper .main-chat-area .chat-content .chat-item-start .main-chat-msg div {
        background-color: rgb(37 38 74);
    }

    .file-img {
        position: relative;
    }
    .file-img button {
        position: absolute;
        inset-block-start: -4px;
        inset-inline-end: -4px;
        height: 20px;
        width: 20px;
        padding: 0px;
        border: 0;
    }
    .liveChatImageViewer{
        display: block;
        position: fixed;
        z-index: 9999999999;
        padding-top: 100px;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        overflow: auto;
        background-color: rgba(0,0,0,0.9);
    }

    .liveChatImageClose{
        position: absolute;
        top: 15px;
        right: 35px;
        color: #f1f1f1;
        font-size: 40px;
        font-weight: bold;
        transition: 0.3s;
        border: 1px solid;
        padding: 0px 20px;
        border-radius: 50%;
        cursor: pointer;
    }

    .liveChatImageTag{
        margin: auto;
        display: block;
        /* width: 80vh; */
        height: 80vh;
        /* max-width: 403px; */
        border-radius: 10px;
        display: flex;
        -webkit-box-align: center;
        align-items: center;
        -webkit-box-pack: center;
        justify-content: center;
    }

    .tickets-chat-head {
        position: relative;
    }
    .tickets-chat-head .data-table-btn1 {
        position: absolute;
        right: 55px;
    }
    .tickets-chat-head .data-table-btn3 {
        position: absolute;
        right: 15px;
    }
    .main-chart-wrapper .chat-info ul li.checkforactive:hover .ticket-select-check{
        display: block
    }
    .ticket-select-check {
        position: absolute;
        inset-inline-start: 10px;
        inset-block-start: 6px;
        display: none;
        z-index: 100;
    }

    ul.show-checks li.checkforactive .ticket-select-check {
        display: block;
    }

    .editable-container {
        position: relative;
        width: 100%;
        height: auto;
    }

    .editable-container::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        padding: 8px;
        color: #aaa;
        pointer-events: none;
        user-select: none;
        transition: opacity 0.2s ease;
    }

    .editable-container div[contenteditable]:empty::before {
        content: 'Type message';
        opacity: 0.6;
    }

    .editable-container div[contenteditable]:not(:empty)::before {
        content: '';
    }

    .editable-container div[contenteditable] {
        padding: 8px;
        box-sizing: border-box;
    }

    .is-loading .agent-detail .font-weight-semibold,
    .is-loading .agent-detail .text-muted,
    .is-loading .agent-detail .avatar,
    .is-loading .agent-detail .name-email-container {
        background: linear-gradient(110deg, #ececec 8%, #f5f5f5 18%, #ececec 33%);
        border-radius: 5px;
        background-size: 200% 100%;
        /* Remove !important */
    }

    /* Adjust animation properties */
    @keyframes shine {
        to {
            background-position-x: 200%;
            /* Adjust direction */
        }
    }

    /* Apply animation to the elements */
    .is-loading .agent-detail .font-weight-semibold,
    .is-loading .agent-detail .text-muted,
    .is-loading .agent-detail .avatar,
    .is-loading .agent-detail .name-email-container {
        animation: shine 1.5s linear infinite;
    }


    .is-loading .agent-detail .avatar,
    .is-loading .agent-detail .name-email-container {
        background-image: linear-gradient(110deg, #ececec 8%, #f5f5f5 18%, #ececec 33%) !important;
        border-radius: 5px
    }

    .is-loading .agent-detail .onlineOfflineIndicator {
        display: none
    }

    .is-loading .agent-detail .font-weight-semibold,
    .is-loading .agent-detail .text-muted {
        opacity: 0;
    }

    .is-loading#main-chat-content .avatar,
    .is-loading#main-chat-content .operator-conversation-Info .flex-fill,
    .is-loading#main-chat-content .avatar,
    .is-loading#main-chat-content .chatnameperson,
    .is-loading#main-chat-content .chatting-user-info,
    .is-loading#main-chat-content .chat-day-label span,
    .is-loading#main-chat-content .chat-list-inner .main-chat-msg div {
        background-image: linear-gradient(110deg, #ececec 8%, #f5f5f5 18%, #ececec 33%) !important;
        border-radius: 5px;
        animation: shine 1.5s linear infinite;
        background: linear-gradient(110deg, #ececec 8%, #f5f5f5 18%, #ececec 33%);
        border-radius: 5px;
        background-size: 200% 100%;
    }

    .is-loading#main-chat-content .chat-day-label span {
        padding: 0.188rem 3.5rem !important
    }

    .is-loading#main-chat-content .chatnameperson,
    .is-loading#main-chat-content .chat-item-end .chatting-user-info {
        padding: 0.188rem 3.5rem;
        font-size: 0.7rem;
        background-color: rgba(51, 102, 255, 0.1);
        border-radius: 0.3rem;
        color: var(--primary);
    }
    .is-loading ul{
        background-image: url(https://laravelui.spruko.com/dayone/assets/images/svgs/loader.svg);
        display: block !important;
        background-position: center !important;
        background-repeat: no-repeat !important;
        padding: 2.5rem !important;
        background-size: auto !important;
        background-attachment: inherit !important;
    }

    .is-loading ul li{
        display: none !important;
    }

    .is-loading #operator-conversation-Info, .is-loading .chat-footer{
        display: none !important;
    }

    .search-input {
        flex-grow: 1;
        margin-inline-start: 19px;
    }

    .search-container{
        position: absolute !important;
        inset-inline-end: 10px;
        top: 7px;
        width: 100%;
        transition: 0.3s;
        display: flex !important;
        justify-content: end !important;
    }

    /* spell check and suggestion */
    #auto-expand {
        position: relative;
        border: 1px solid #ccc;
        padding: 10px;
        min-height: 40px;
        width: 100%;
        font-size: 16px;
        /* height: 100% !important; */
    }

    #suggestionText {
        padding: 4px 8px;
        font-size: 14px;
        color: #333;
        pointer-events: none;
        opacity: 0.5;
        z-index: 999;
        white-space: nowrap;
    }

    .misspelled {
        text-decoration: underline wavy red;
        cursor: pointer;
        position: relative;
    }

    .correctedtooltip {
        padding: 5px 10px;
        border-radius: 5px;
        color: #333;
        font-size: 12px;
        white-space: nowrap;
        z-index: 100000;
        cursor: pointer;
    }

    /* start text to speach */
    .msg-send-dropdown{
        display: none;
        position: absolute;
        position: absolute;
        inset-inline-end: 17px;
        inset-block-start: 9px;
    }
    .chat-list-inner{
        position: relative;
        /* padding: 1rem; */
        border-radius: 0.35rem;
        width:100%;
    }
    /* .chat-list-inner:hover{
        background-color: #f1f4fb;
    } */
    .chat-list-inner:hover .msg-send-dropdown {
        display: block
    }
    .chatting-user-info{
        margin-inline-end: 1.5rem;
    }
    .main-chart-wrapper .dropdown-menu li{
        margin-block-end:0px !important;
    }
    /* end text to speach */

</style>

<!-- Select2 css -->
<link href="{{asset('build/assets/plugins/select2/select2.min.css')}}" 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('Solved Chats',
                    'menu')}}</span></h4>
        </div>
    </div>
    <!--End Page header-->

    {{-- sideBar --}}
    <div class="main-chart-wrapper">
        <div class="row">
            <div class="col-xxl-3 col-xl-4 col-lg-5">
                <div class="chat-info border card">
                    <div class="d-flex align-items-center justify-content-between w-100 p-4 ps-4 border-bottom">
                        <div>
                            <h5 class="fw-semibold mb-0">{{ lang('Solved Chats') }}</h5>
                        </div>
                        <div class="search-container">
                            <div class="search-input" style="display: none;">
                            <input type="search" class="form-control" id="input-search" placeholder="{{ lang('Search here') }}">
                            </div>
                            <a href="javascript:void(0);" class="p-2 fs-16" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="Search" onclick="toggleSearch()">
                            <i class="ri-search-line align-middle"></i>
                            </a>
                        </div>
                        <button id="massdelete" class="btn btn-outline-light btn-sm btn-icon data-table-btn1" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="Delete" style="display: none;"><i class="fe fe-trash"></i> </button>
                        <span class="ms-6" id="selectallbutton" style="display: none;">
                            <input aria-label="anchor" class="form-check-input" type="checkbox" id="customCheckAll">
                            <label for="customCheckAll" class="mb-0"></label>
                        </span>
                    </div>
                    <div class="search-section">
                        <ul class="list-unstyled mb-0 chat-user-tab-list chat-users-tab overflow-auto" id="chat-msg-scroll">
                            @php
                                $emptyConversation = true;
                            @endphp

                            @foreach ($filteredLiveCust as $LiveCust)
                                @if($LiveCust && $LiveCust->lastMessage != null && !$LiveCust->lastMessage->delete)
                                {{$emptyConversation = false}}
                                <li class="checkforactive" data-id={{$LiveCust->id}}>
                                    <div class="d-flex align-items-center">
                                        <div class="me-2 lh-1">
                                            <span class="avatar brround" id="new-chat-user-bg" style="background-color: {{ $LiveCust->profile_bg_color }}">
                                                @php
                                                    $currentOnlineUsers = setting('liveChatCustomerOnlineUsers');
                                                    $onlineUsersArray = explode(',', $currentOnlineUsers);
                                                    $userOnline = in_array($LiveCust->id, $onlineUsersArray);
                                                @endphp
                                                @if($userOnline)
                                                    <span class="avatar-status bg-green"></span>
                                                @else
                                                    <span class="avatar-status "></span>
                                                @endif
                                                <span class="new-chat-user-letter">{{ strtoupper(substr($LiveCust->username, 0, 1)) }}</span>
                                                <input aria-label="anchor" aria-expanded="false" type="checkbox" name="customer_checkbox[]" class="checkall ticket-select-check live-chat-checkbox form-check-input" value="{{ encrypt($LiveCust->cust_unique_id) }}"/>
                                            </span>
                                        </div>
                                        <div class="flex-fill">
                                            <div class="mb-0 d-flex align-items-center justify-content-between">
                                                <div class="font-weight-semibold">
                                                    <a href="javascript:void(0);">{{$LiveCust->username}}</a>
                                                </div>
                                                <div class="float-end text-muted fw-normal fs-12 chat-time" data-initial-24time='{{ \Carbon\Carbon::parse($LiveCust->lastMessage->created_at)->timezone(setting('default_timezone')) }}'>{{ $LiveCust->lastMessage->created_at->diffForHumans() }}</div>
                                                <div class="dropdown chat-actions lh-1">
                                                    <a aria-label="anchor" href="javascript:void(0);" data-bs-toggle="dropdown" aria-expanded="false" class="">
                                                        <i class="fe fe-more-vertical fs-18"></i>
                                                    </a>
                                                    <ul class="dropdown-menu" style="">
                                                        <li class="conversationbarclose">
                                                            <a aria-label="anchor" class="dropdown-item" href="javascript:void(0);" onclick="slectTicket(event, {{ $LiveCust->id }})" data-id="{{ $LiveCust->id }}">
                                                                <i class="ri-mail-check-fill align-middle me-2 fs-17 text-muted chat-info-optionicon d-inline-block"></i>{{ lang('Select') }}
                                                            </a>
                                                        </li>
                                                        <li>
                                                            <a class="dropdown-item" deleteRouteLink="{{route('admin.livechatConversationDelete')}}?unqid={{$LiveCust->cust_unique_id}}"><i
                                                            class="ri-delete-bin-fill align-middle me-2 fs-17 text-muted chat-info-optionicon d-inline-block"></i>{{ lang('Delete') }}</a>
                                                        </li>
                                                    </ul>
                                                </div>
                                            </div>
                                            <div class="d-flex align-items-center justify-content-between">
                                                @if($LiveCust->unreadIndexNumber)
                                                    <span class="chat-msg text-truncate fs-13 text-default custrecentmessage font-weight-bold" data-id="{{ $LiveCust->lastMessage->id }}">
                                                        @if ($LiveCust->lastMessage->messageDeleted == '1')
                                                            <i class="bx bx-block leading-none "></i>{{ lang('This message was deleted') }}
                                                        @else
                                                            {{ str_replace('&nbsp;', ' ', strip_tags(html_entity_decode($LiveCust->lastMessage->message))) }}
                                                            {{-- {!! $LiveCust->lastMessage->message !!} --}}
                                                        @endif
                                                    </span>
                                                    <span class="ms-auto me-2 badge bg-success-transparent rounded-circle unReadIndexNumber">{{$LiveCust->unreadIndexNumber}}</span>
                                                @else
                                                    <span class="chat-msg text-truncate fs-13 text-default custrecentmessage" data-id="{{ $LiveCust->lastMessage->id }}">
                                                        @if ($LiveCust->lastMessage->messageDeleted == '1')
                                                            <i class="bx bx-block leading-none "></i>{{ lang('This message was deleted') }}
                                                        @else
                                                            {{ str_replace('&nbsp;', ' ', strip_tags(html_entity_decode($LiveCust->lastMessage->message))) }}
                                                            {{-- {!! $LiveCust->lastMessage->message !!} --}}
                                                        @endif
                                                    </span>
                                                @endif
                                            @if(json_decode($LiveCust->engage_conversation))
                                                @if(collect(json_decode($LiveCust->engage_conversation))->count() <= 2)
                                                        <div class="avatar-list avatar-list-stacked me-3">
                                                            @foreach (json_decode($LiveCust->engage_conversation) as $key =>$LiveCustmer)
                                                                @if($key < 2)
                                                                    <span class="avatar brround avatar-sm"
                                                                    style="background-image: url({{ userprofileimage($LiveCustmer) }})"
                                                                    data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="{{$LiveCustmer->name}}"
                                                                    reddy="" data-bs-original-title="" title=""></span>
                                                                @endif
                                                            @endforeach
                                                        </div>
                                                        @else
                                                            <div class="avatar-list avatar-list-stacked me-3">
                                                                @foreach (json_decode($LiveCust->engage_conversation) as $key =>$LiveCustmer)
                                                                    @if($key < 2)
                                                                        <span class="avatar brround avatar-sm"
                                                                        style="background-image: url({{ userprofileimage($LiveCustmer) }})"
                                                                        data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="{{$LiveCustmer->name}}"
                                                                        reddy="" data-bs-original-title="" title=""></span>
                                                                    @endif
                                                                @endforeach
                                                                @php
                                                                    $conversationData = json_decode($LiveCust->engage_conversation);
                                                                    $namesString = implode(', ', array_map(fn($item) => $item->firstname . ' ' . $item->lastname, $conversationData));
                                                                @endphp
                                                                    <span class="avatar brround bg-light text-dark avatar-sm" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="{{$namesString}}">+{{collect(json_decode($LiveCust->engage_conversation))->count()-2}}</span>
                                                            </div>
                                                @endif
                                            @endif
                                            </div>
                                        </div>
                                    </div>
                                </li>
                                @endif
                            @endforeach
                            @if($emptyConversation)
                            <div class="text-center mt-5 px-2 py-4 bg-warning-transparent text-default mx-auto w-90 rounded-2">
                                <span>{{ lang('As of now, there are no chat discussions in progress') }}</span>
                            </div>
                            @endif
                        </ul>
                    </div>
                </div>
            </div>
            <div class="col-xxl-6 col-xl-8 col-lg-7">
                <div class="main-chat-area main-chat-area-new bg-white card border">
                    <div id="main-chat-content">
                        <div class="card shadow-none no-articles d-none" style="
                            height: calc(100vh - 8rem);
                            background-color: transparent;
                            "
                        >
                            <div class="card-body p-8">
                                <div class="main-content text-center">
                                    <div class="notification-icon-container p-4">
                                        <img src="{{ asset('build/assets/images/noarticle.png') }}" alt="">
                                    </div>
                                    <h4 class="mb-1">{{ lang('Currently, no active chat discussions at the moment') }}</h4>
                                    <p class="text-muted">{{ lang('There are currently no ongoing chat discussions at this time.') }}</p>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="chat-footer bg-transparent shadow-none d-none border-top">
                        <div class="chat-reply-area chat-replyoptions flex-fill textareaDiv d-none">
                            <div class="form-group create-ticket d-none">
                                <label for="livechatTicketSubject" class="form-label">{{ lang('Subject') }} <span class="text-red">*</span>
                                    <small class="text-muted float-end mt-2" id="subjectmaxtextsss">{{lang('Maximum')}} <b>{{setting('TICKET_CHARACTER')}}</b> {{lang('Characters')}}</small>
                                </label>
                                <input type="text" class="form-control" id="livechatTicketSubject" placeholder="Enter Ticket Subject" maxlength="{{setting('TICKET_CHARACTER')}}">
                            </div>

                            <div class="form-group d-none">
                                <div class="row">
                                    <div class="">
                                        <label class="form-label">{{lang('Category')}} <span class="text-red">*</span></label>
                                    </div>
                                    <div class="">
                                        <select
                                            class="form-control select2-show-search  select2 @error('category') is-invalid @enderror"
                                            data-placeholder="{{lang('Select Category')}}" name="category" id="category">
                                            <option label="{{lang('Select Category')}}"></option>
                                            @foreach ($categories as $category)

                                            <option value="{{ $category->id }}" @if(old('category')) selected @endif>{{ $category->name }}</option>
                                            @endforeach

                                        </select>
                                        <span id="CategoryError" class="text-danger alert-message"></span>
                                        @error('category')

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

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

                            <div class="form-group" id="envatopurchase">
                            </div>

                            @if(setting('ENVATO_ON') == 'on')
                                <div class="row d-none mb-2" id="hideelement">
                                    <div class="">
                                        <label class="form-label mb-2 mt-2">{{lang('Envato Item Name')}}<span class="text-red">*</span></label>
                                    </div>
                                    <div class="">
                                        <input type="hidden" name="productname" id="itemname">
                                        <input type="text" id="productname" class="form-control" placeholder="Envato Project Name">

                                    </div>
                                </div>
                            @endif

                            <div class="form-group d-none" id="prioritydiv">
                                <div class="row">
                                    <div class="">
                                        <label class="form-label">{{lang('Priority')}}</label>
                                    </div>
                                    <div class="">
                                        <select class="form-control select2-show-search select2" data-placeholder="{{lang('Select Priority')}}" name="priority" id="priority">
                                            <option label="{{lang('Select Priority')}}"></option>
                                            <option value="Low">{{lang('Low')}}</option>
                                            <option value="Medium">{{lang('Medium')}}</option>
                                            <option value="High">{{lang('High')}}</option>
                                            <option value="Critical">{{lang('Critical')}}</option>
                                        </select>
                                    </div>
                                </div>
                            </div>

                            <div class="form-group d-none" id="assigneediv">
                                <div class="row">
                                    <div class="">
                                        <label class="form-label">{{lang('Assignee')}} <span class="text-red">*</span></label>
                                    </div>
                                    <div class="">
                                        <select
                                            class="form-control select2-show-search  select2 @error('assignee') is-invalid @enderror"
                                            data-placeholder="{{lang('Select Assignee')}}" name="assignee" id="assignee">

                                            <option value="unassign">{{ lang("Un Assign") }}</option>
                                            @foreach ($userdatas as $userdata)
                                                @if ($userdata->id == Auth::user()->id)
                                                    <option value="{{ $userdata->id }}" selected>{{ $userdata->name }} ({{lang('You')}})</option>
                                                @else
                                                    <option value="{{ $userdata->id }}" @if(old('assignee')) selected @endif>{{ $userdata->name }}</option>
                                                @endif
                                            @endforeach

                                        </select>
                                        <span id="assigneeError" class="text-danger alert-message"></span>
                                        @error('assignee')
                                            <span class="invalid-feedback" role="alert">
                                                <strong>{{ lang($message) }}</strong>
                                            </span>
                                        @enderror

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

                            <label for="auto-expand" class="form-label create-ticket-description d-none">
                                {{ lang('Description') }}
                            <span class="text-red">*</span>
                            </label>
                            <div class="editable-container">
                                <div contenteditable="true" id="auto-expand" name="message" class="form-control mb-2 textarea-chatoptions"></div>
                            </div>
                            <div class="image-uploaded d-flex gap-2 flex-wrap"></div>
                            <div class="d-flex align-items-center justify-content-between px-2">
                                <div data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="Canned responses">
                                    <a aria-label="anchor" class="btn-emoji" href="javascript:void(0)" onclick="openModal(event)">
                                        <i class="ri-message-line"></i>
                                    </a>
                                </div>
                                <div id="chat-btn" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="Chat">
                                    <a aria-label="anchor" class="btn-emoji" href="javascript:void(0)">
                                        <i class="ri-chat-3-line text-primary"></i>
                                    </a>
                                </div>
                                <div id="create-ticket-btn" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="Create Ticket">
                                    <a aria-label="anchor" class="btn-emoji" href="javascript:void(0)">
                                        <i class="ri-ticket-line"></i>
                                    </a>
                                </div>
                                <div class="d-flex align-items-center ms-auto gap-2">
                                    @if (setting('employeeVoiceChat') == 'on')
                                        <a aria-label="anchor" class="voiceRecorderButton" href="javascript:void(0);">
                                            <i class="ri-mic-line"></i>
                                        </a>
                                    @endif
                                    <a aria-label="anchor" class="btn-emoji allEmojisBtn dropdown" data-bs-toggle="dropdown" href="javascript:void(0)" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="Emojis" data-bs-original-title="" title="">
                                        <i class="ri-emotion-line"></i>
                                    </a>
                                    <ul class="dropdown-menu" id="emojiGrid" style="height: 200px; overflow-y: scroll;"></ul>
                                    <a aria-label="anchor" class="btn-attach {{ setting('liveChatAgentToCustFileUpload') == '1' || Auth::user()->getRoleNames()[0] == 'superadmin' ? '' : 'd-none' }}" id="agentToCustFileSetUpdate" type="file" onclick="{document.querySelector('#chat-file-upload').click()}" href="javascript:void(0)" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="Upload" data-bs-original-title="" title="">
                                        <i class="ri-attachment-line"></i>
                                    </a>
                                    <input type="file" id="chat-file-upload" class="d-none" name="chat-file-upload" accept="image/png, image/jpeg" />
                                    <button aria-label="anchor" disabled="true" id="agentSendMessage" class="btn-reply border rounded-3 btn-outline-primary agent-send-message disabled" href="javascript:void(0)">
                                        <i class="ri-send-plane-2-fill fs-20"></i>
                                    </button>
                                    <button aria-label="anchor" disabled="true" id="agentCreateTicket" class="d-none btn-reply border rounded-3 btn-outline-primary agent-send-message disabled" href="javascript:void(0)">
                                        <i class="ri-send-plane-2-fill fs-20"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                        <div class="chat-reply-area chat-replyoptions flex-fill text-center engageConversation">
                            <button type="button" class="btn btn-primary d-flex justify-content-center align-items-center mx-auto">{{ lang('Join this conversation') }} <i class="ri-discuss-line ms-1"></i></button>
                        </div>
                    </div>
                </div>
            </div>
            {{-- Chat Info div --}}
            <div class="col-xxl-3 main-chat-user-details card border">
                <div class="chat-user-details bg-transparent p-0" >
                    {{-- Customer Info div --}}
                    <div class="card d-none" id="chat-user-details">
                        <button aria-label="button" type="button" class="btn btn-icon btn-outline-light my-1 ms-2 responsive-chat-close2">
                            <i class="ri-close-line"></i>
                        </button>
                        <div class="card-header border-0 pb-0">
                            <h4 class="card-title">{{ lang('Customer Info') }}</h4>
                        </div>
                        <div class="card-body">

                        </div>
                    </div>

                    <div class="card d-none shadow-none">
                        <div class="card-header pb-4 d-flex align-items-center border-0">
                            <h6>{{ lang('File Upload Permission') }}</h6>
                            <div class="switch-toggle  ms-auto">
                                <a class="onoffswitch2 ">
                                    <input type="checkbox" id="fileUploadPermission" class="toggle-class onoffswitch2-checkbox">
                                    <label for="fileUploadPermission" class="toggle-class onoffswitch2-label"></label>
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        {{-- Re-Assign Model --}}

        <div class="modal fade" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="staticBackdropLabel">{{ lang('Reassign the conversation') }}</h5>
                    <button  class="close" data-bs-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">×</span>
                    </button>
                </div>
                <div class="modal-body">

                    <div class="form-group select2-lg">
                        <label for="form-label">{{ lang('Reassign Users') }}</label>
                        <select class="form-control select2" placeholder="..." id="reassignSelect">
                            <option></option>
                            @foreach($user as $users)
                                <option value={{$users->id}} data-kt-select2-country="{{ userprofileimage($users) }}">{{$users->name}}</option>
                            @endforeach
                        </select>
                        <span class="text-danger" id="reassignSelectError"></span>
                    </div>

                </div>
                <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">{{ lang('Close') }}</button>
                <button type="button" class="btn btn-primary" id="reassignSelectBtn">{{ lang('Reassign') }}</button>
                </div>
            </div>
            </div>
        </div>

        {{-- Canned Responses --}}
        <div class="modal fade" id="canned-responses" data-bs-backdrop="static" style="display: none;" aria-hidden="true">
            <div class="modal-dialog modal-lg modal-dialog-centered" role="document">
                <div class="modal-content tx-size-sm">
                    <div class="modal-body p-4">
                        <div class="form-group">
                            <label class="form-label">{{ lang('Canned Responses') }}<a href="" data-bs-target="#canned-add-responses" data-bs-toggle="modal" class="fw-semibold font-weight-semibold text-primary text-decoration-underline float-end"></a>
                                <button  class="close" data-bs-dismiss="modal" aria-label="Close">
                                    <span aria-hidden="true">×</span>
                                </button>
                            </label>
                            <select name="livechatPosition" id="cannedResponses" class="form-control select2 select2-show-search" required>
                            </select>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        @include('admin.superadmindashboard.texttospeachpopup')
        @include('admin.superadmindashboard.texttranslationpopup')
    </div>


@endsection

@section('scripts')

    <!-- INTERNAL Web Socket -->
    <script domainName='{{url('')}}' wsPort="{{setting('liveChatPort')}}" src="{{ asset('build/assets/plugins/livechat/web-socket.js') }}"></script>

    <!-- Select2 js -->
    @vite(['resources/assets/js/select2.js'])

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

    <script src="{{ asset('build/assets/plugins/typomaster/typojs.min.js') }}"></script>

    <script>
        // Function to update the state of the "Select All" checkbox
        function updateCustomCheckAll() {
            document.querySelector('.search-input').style.display = 'none';

            var totalCheckboxes = $('.checkall').length;
            var checkedCheckboxes = $('.checkall:checked').length;
            let chatUserTabList = document.querySelector('.chat-user-tab-list');

            if (checkedCheckboxes == 0) {
                $('#selectallbutton').hide();
                $('.search-container').show();
                chatUserTabList.classList.remove('show-checks');
            } else {
                $('#selectallbutton').show();
                $('.search-container').hide();
            }
            if (checkedCheckboxes === totalCheckboxes) {
                $('#customCheckAll').prop('checked', true);
            } else {
                $('#customCheckAll').prop('checked', false);
            }
        }

        var searchInput = document.querySelector('.search-input');
        function toggleSearch() {
            if (document.getElementById('search-chat-msg-scroll')) {
                document.getElementById('search-chat-msg-scroll').remove();
            }
            document.getElementById('chat-msg-scroll').classList.remove('d-none');
            document.getElementById('input-search').value = '';

            searchInput.style.display = (searchInput.style.display === 'none' || searchInput.style.display === '') ? 'block' : 'none';
            document.getElementById('input-search').focus();
        }

        // Live Time Update
        document.addEventListener('DOMContentLoaded', () => {

            let searchField = document.querySelector('#input-search');
            let completeData = @json($livecust);
            let debounceTimer;

            searchField.oninput = (e) =>{

                clearTimeout(debounceTimer); // Clear the previous timer if the user keeps typing

                debounceTimer = setTimeout(() => {
                    let searchValue = e.target.value.toLowerCase(); // To handle case insensitivity

                    if (searchValue.trim()) {
                        // Filter completeData based on search criteria
                        let filteredData = completeData.filter((item) => {
                            // Check if searchValue matches email or username
                            const isMatchInUser = item.email && item.email?.toLowerCase().includes(searchValue) || item.username && item.username.toLowerCase().includes(searchValue) || item.mobile_number && item.mobile_number.toLowerCase().includes(searchValue);

                            // Check if searchValue matches any message in livechatconversation array
                            const liveChatMessages = item.livechatconversation || []; // Default to empty array if livechatconversation is null or undefined
                            // Check each object in livechatconversation for a 'message' field
                            const isMatchInMessages = liveChatMessages.some(chat => {
                                if (chat && typeof chat.message === 'string') {
                                    return chat.message.toLowerCase().includes(searchValue);
                                }
                                return false;
                            });

                            // Return true if either the user or message matches the searchValue
                            return isMatchInUser || isMatchInMessages;
                        });

                        // Sort the filtered data in descending order based on the 'id' field
                        filteredData.sort((a, b) => b.id - a.id);
                        document.getElementById('chat-msg-scroll').classList.add('d-none');

                        appendFilteredData(filteredData);
                    } else {
                        document.getElementById('chat-msg-scroll').classList.remove('d-none');
                        document.getElementById('search-chat-msg-scroll').classList.add('d-none');
                    }

                }, 500); // 500ms debounce
            }

            let appendFilteredData = (data) => {
                if (document.getElementById('search-chat-msg-scroll')) {
                    document.getElementById('search-chat-msg-scroll').remove();
                }

                let createdUl = document.createElement('ul')
                createdUl.className = 'list-unstyled mb-0 chat-user-tab-list chat-users-tab overflow-auto';
                createdUl.setAttribute('id', 'search-chat-msg-scroll')

                if (data.length > 0) {
                    const listItems = data.map(item => {
                        // Extract the initials for the avatar (e.g., first letter of the username)
                        const avatarLetter = item.username.charAt(0).toUpperCase();
                        const lastMessage = item.livechatconversation && item.livechatconversation.length > 0
                            ? item.livechatconversation[item.livechatconversation.length - 1]
                            : null;

                        const lastMessageTime = lastMessage ? lastMessage.created_at : null;
                        const lastMessageMessage = lastMessage ? lastMessage.message : null;

                        // Build the inner HTML for each <li> based on your template
                        return `
                            <li class="checkforactive active" data-id="${item.id}">
                                <div class="d-flex align-items-center">
                                    <div class="me-2 lh-1">
                                        <span class="avatar brround" id="new-chat-user-bg" style="background-color: ${item.profile_bg_color}">
                                            <span class="avatar-status"></span>
                                            <span class="new-chat-user-letter">${avatarLetter}</span>
                                        </span>
                                    </div>
                                    <div class="flex-fill">
                                        <div class="mb-0 d-flex align-items-center justify-content-between">
                                            <div class="font-weight-semibold">
                                                <a href="javascript:void(0);" class="customer-name-change">${item.username}</a>
                                            </div>
                                            <div class="float-end text-muted fw-normal fs-12 chat-time" data-initial-24time="${dateTimeforappending(lastMessageTime)}">${getTimeAgo(lastMessageTime)}</div>
                                            <div class="dropdown chat-actions lh-1 d-none">
                                                <a aria-label="anchor" href="javascript:void(0);" data-bs-toggle="dropdown" aria-expanded="false">
                                                    <i class="fe fe-more-vertical fs-18"></i>
                                                </a>
                                                <ul class="dropdown-menu">
                                                    <li class="conversationbarclose">
                                                        <a aria-label="anchor" class="dropdown-item" href="javascript:void(0);" onclick="slectTicket(event, ${item.id})" data-id="${item.id}">
                                                            <i class="ri-mail-check-fill align-middle me-2 fs-17 text-muted chat-info-optionicon d-inline-block"></i>Select
                                                        </a>
                                                    </li>
                                                    <li>
                                                        <a class="dropdown-item" href="{{route('admin.bancustomer')}}?id=${item.id}">
                                                            <i class="ri-user-unfollow-fill align-middle me-2 fs-17 text-muted chat-info-optionicon d-inline-block"></i>Ban Customer
                                                        </a>
                                                    </li>
                                                    <li><a href="{{route('admin.removeUserFromUnread')}}?id=${item.id}" class="dropdown-item markAsUnreadBtn"><i class="ri-mail-unread-fill align-middle me-2 fs-17 text-muted chat-info-optionicon d-inline-block"></i>Mark As Unread</a></li>
                                                    <li><a class="dropdown-item markassolvedchange" href="javascript:void(0);" data-id="${item.id}"><i class="ri-mail-check-fill align-middle me-2 fs-17 text-muted chat-info-optionicon d-inline-block"></i>Mark As Solved</a></li>
                                                    <li custid="${item.id}" class="reAssignModalTrigger" data-bs-toggle="modal" data-bs-target="#staticBackdrop"><a class="dropdown-item" href="javascript:void(0);"><i class="ri-user-shared-fill align-middle me-2 fs-17 text-muted chat-info-optionicon d-inline-block"></i>Re-Assign</a></li>
                                                    <li>
                                                        <a class="dropdown-item" deleteroutelink="{{route('admin.livechatConversationDelete')}}?unqid=${item.cust_unique_id}">
                                                        <i class="ri-delete-bin-fill align-middle me-2 fs-17 text-muted chat-info-optionicon d-inline-block"></i>Delete</a>
                                                    </li>
                                                </ul>
                                            </div>
                                        </div>
                                        <div class="d-flex align-items-center justify-content-between">
                                            <span class="chat-msg text-truncate fs-13 text-default custrecentmessage" data-id="100">${sanitizeMessage(lastMessageMessage) || 'No recent message'}</span>
                                        </div>
                                    </div>
                                </div>
                            </li>
                        `;
                    });
                    createdUl.innerHTML = listItems.join('');
                    document.querySelector('.search-section').appendChild(createdUl);

                    const liElements = createdUl.querySelectorAll('li');
                    liElements.forEach((li) => {
                        li.onclick = () => {
                            sideMenuOpenClickFunction(li);
                        };
                    });
                } else {
                    let noResults = document.createElement('div');
                    noResults.className = 'text-center mt-5 p-3 bg-warning-transparent text-default';
                    noResults.innerHTML = '{{ lang('No results for the keyword') }}'

                    createdUl.appendChild(noResults);

                    document.querySelector('.search-section').appendChild(createdUl);
                }
            }

            function dateTimeforappending(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
                }
            }

            // Helper function to format time (e.g., "1 day ago")
            function getTimeAgo(time) {
                const timeDifference = new Date() - new Date(time);
                const days = Math.floor(timeDifference / (1000 * 60 * 60 * 24));
                return days > 0 ? `${days} day${days > 1 ? 's' : ''} ago` : 'Today';
            }

            function updateTime() {
                const timeElements = document.querySelectorAll('.chat-time');

                timeElements.forEach(element => {
                    const initialTime = element.getAttribute('data-initial-24time');
                    const initialDate = new Date(initialTime);
                    const now = new Date();

                    const diffInMinutes = Math.floor((now - initialDate) / 60000);
                    let timeText;

                    if (diffInMinutes < 1) {
                        timeText = 'Just now';
                    } else if (diffInMinutes < 60) {
                        timeText = `${diffInMinutes} minute${diffInMinutes > 1 ? 's' : ''} ago`;
                    } else {
                        const diffInHours = Math.floor(diffInMinutes / 60);
                        if (diffInHours < 24) {
                            timeText = `${diffInHours} hour${diffInHours > 1 ? 's' : ''} ago`;
                        } else {
                            const diffInDays = Math.floor(diffInHours / 24);
                            timeText = `${diffInDays} day${diffInDays > 1 ? 's' : ''} ago`;
                        }
                    }

                    element.textContent = timeText;
                });
            }

            // Update time every minute
            updateTime();
            setInterval(updateTime, 60000);
        });
    </script>

    <script>
        // store the range
        let storedRange;
        function storeRange() {
            let message = document.querySelector('#auto-expand');
            const selection = document.getSelection();
            if (selection?.rangeCount) {
                let selected = selection.getRangeAt(0).commonAncestorContainer;
                if (message.contains(selected)) {
                    // Storing the range
                    storedRange = selection.getRangeAt(0);
                } else {
                    let newRng = document.createRange();
                    newRng.setStart(message, message.childNodes.length); // Start at the end of the content
                    newRng.setEnd(message, message.childNodes.length);
                    selection.removeAllRanges();
                    selection.addRange(newRng);
                    storedRange = selection.getRangeAt(0);
                }
            } else {
                let newRng = document.createRange();
                newRng.setStart(message, message.childNodes.length); // Start at the end of the content
                newRng.setEnd(message, message.childNodes.length);
                selection.removeAllRanges();
                selection.addRange(newRng);
                storedRange = selection.getRangeAt(0);
            }
        }

        function retrieveRange() {
            // Used to retrive the stored range value
            if (storedRange) {
                return storedRange;
            }
        }

        let newVal = "";
        // Get the Emojis Values
        function insertEmoji(emoji) {
            if (!storedRange) return;

            const textNode = document.createTextNode(emoji);
            storedRange.insertNode(textNode);

            // Move the caret after the inserted emoji
            let selection = document.getSelection();
            let newRng = document.createRange();
            newRng.setStartAfter(textNode);
            newRng.setEndAfter(textNode);
            selection.removeAllRanges();
            selection.addRange(newRng);

            // Update the stored range to the new position
            storedRange = newRng;
        }

        let audioBlob;

        function startRecording() {
            const voiceRecorderButton = document.querySelector('.voiceRecorderButton');

            // Detach any existing onclick handlers to avoid duplicating handlers
            voiceRecorderButton.onclick = null;

            voiceRecorderButton.onclick = (e) => {
                navigator.mediaDevices.getUserMedia({ audio: true })
                    .then(function (stream) {
                        voiceRecorderButton.classList.toggle('btn-active')
                        let audioChunks = [];
                        let mediaRecorder = new MediaRecorder(stream, { mimeType: 'audio/webm; codecs=opus' });
                        mediaRecorder.start();

                        mediaRecorder.ondataavailable = function (event) {
                            audioChunks.push(event.data);
                        };

                        // Setup stop handling once inside the recording session
                        voiceRecorderButton.onclick = () => {
                            if (mediaRecorder && mediaRecorder.state !== "inactive") {
                                mediaRecorder.stop(); // stop recording
                            }
                        };

                        mediaRecorder.onstop = function () {
                            voiceRecorderButton.classList.toggle('btn-active')
                            audioBlob = new Blob(audioChunks, { type: 'audio/webm; codecs=opus' }); // Specify codec in Blob
                            const audioUrl = URL.createObjectURL(audioBlob);
                            let audioElement = document.createElement('div');
                            audioElement.innerHTML = `
                                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-trash text-danger cursor-pointer" viewBox="0 0 16 16">
                                    <path d="M5.5 5.5A.5.5 0 0 1 6 6v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5m2.5 0a.5.5 0 0 1 .5.5v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5m3 .5a.5.5 0 0 0-1 0v6a.5.5 0 0 0 1 0z"/>
                                    <path d="M14.5 3a1 1 0 0 1-1 1H13v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V4h-.5a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1H6a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1h3.5a1 1 0 0 1 1 1zM4.118 4 4 4.059V13a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1V4.059L11.882 4zM2.5 3h11V2h-11z"/>
                                </svg>
                                <audio id="audio-player" controls="" src="${audioUrl}"></audio>
                            `;

                            // Ensure all tracks are stopped
                            stream.getTracks().forEach(track => track.stop());

                            const existingAudioPlayer = document.querySelector('#audio-player');
                            if (existingAudioPlayer) {
                                existingAudioPlayer.parentNode.replaceChild(audioElement, existingAudioPlayer);
                                document.querySelector('.text-danger.cursor-pointer').remove();
                            } else {
                                document.querySelector('.chat-reply-area.chat-replyoptions').insertBefore(audioElement, document.querySelector('.chat-reply-area.chat-replyoptions .d-flex.align-items-center.px-2'));
                            }

                            document.querySelector('.cursor-pointer.text-danger').onclick = () => {
                                audioElement.remove();
                            }

                            // Re-attach the handler for a new recording
                            startRecording();
                        };

                        // Optionally update a UI element to indicate that recording has started
                        // document.getElementById('recording-status').innerText = "Recording...";
                    })
                    .catch(function (error) {
                        alert("Error accessing microphone. Please connect a microphone");
                        console.error("Error accessing microphone", error);
                        // Optionally update a UI element to indicate that the microphone is unavailable
                        // document.getElementById('recording-status').innerText = "Microphone access denied or unavailable.";
                    });
            };
        }

        @if (setting('employeeVoiceChat') == 'on')
            startRecording()
        @endif
        let elementToToggle = null;

        function openModal(event) {
            elementToToggle = event.target;
            $('#canned-responses').modal('show');
        }

        $('#canned-responses .modalclosecanned').on('click', function() {
            elementToToggle.checked = !elementToToggle.checked;
        })

        // Adding the Emojis
        document.addEventListener("DOMContentLoaded", function () {
            let allEmojisBtn = document.querySelector('.allEmojisBtn');
            allEmojisBtn.addEventListener('click', ()=>{
                storeRange();
            })

            const emojiGrid = document.getElementById("emojiGrid");

            // Emojis data
            const emojisData = ['😀', '😃', '😄', '😁', '😆', '😅', '😂', '🤣', '😊', '😇', '🙂', '🙃', '😉', '😌', '😍', '🥰', '😘', '😗', '😙', '😚', '😋', '😛', '😜', '🤪', '😝', '🤑', '🤗', '🤭', '🤫', '🤔', '🤐', '🤨', '😐', '😑', '😶', '😏', '😒', '🙄', '😬', '😮', '😯', '😦', '😧', '😨', '😰', '😱', '😳', '😵', '😡', '😠', '😤', '😖', '😆', '😋', '😷', '😎', '🤓', '🤠', '😸', '😺', '😻', '😼', '😽', '🙀', '😿', '😾', '👐', '🙌', '👏', '🤝', '👍', '👎', '👊', '✊', '🤛', '🤜', '🤞', '✌️', '🤘', '👌', '👈', '👉', '👆', '👇', '✋', '🤚', '🖐', '🖖', '👋', '🤙', '💪', '🖕', '✍️', '🙏', '🦶', '🦵', '💍', '💔', '❤️', '💙', '💚', '💛', '💜', '🧡', '💔', '❤️', '💕', '💞', '💓', '💗', '💖', '💘', '💝', '💟', '💤', '💢', '💣', '💥', '💫', '💦', '💨', '🕳️', '💧', '💩', '🙈', '🙉', '🙊', '💪', '👈', '👉', '👆', '👇', '🖕', '🤘', '🤞', '🤟', '🤙', '👊', '👋', '👏', '👐', '✋', '🤚', '🤝', '🙏', '💍', '💔', '❤️', '💕', '💞', '💓', '💗', '💖', '💘', '💝', '💟', '💤', '💢', '💣', '💥', '💫', '💦', '💨', '🕳️', '💧', '💩', '🙈', '🙉', '🙊', '💪', '👈', '👉', '👆', '👇', '🖕', '🤘', '🤞', '🤟', '🤙', '👊', '👋', '👏', '👐', '✋', '🤚', '🤝', '🙏', '💍', '💔', '❤️', '💕', '💞', '💓', '💗', '💖', '💘', '💝', '💟', '💤', '💢', '💣', '💥', '💫', '💦', '💨', '🕳️', '💧', '💩', '🙈', '🙉', '🙊', '💪', '👈', '👉', '👆', '👇', '🖕', '🤘', '🤞', '🤟', '🤙', '👊', '👋', '👏', '👐', '✋', '🤚', '🤝', '🙏', '💍', '💔', '❤️', '💕', '💞', '💓', '💗', '💖', '💘', '💝', '💟', '💤', '💢', '💣', '💥', '💫', '💦', '💨', '🕳️', '💧', '💩', '🙈', '🙉', '🙊', '💪', '👈', '👉', '👆', '👇', '🖕', '🤘', '🤞', '🤟', '🤙', '👊', '👋', '👏', '👐', '✋', '🤚', '🤝', '🙏', '💍', '💔', '❤️', '💕', '💞', '💓', '💗', '💖', '💘', '💝', '💟', '💤', '💢', '💣', '💥', '💫', '💦', '💨', '🕳️', '💧', '💩', '🙈', '🙉', '🙊', '💪', '👈', '👉', '👆', '👇', '🖕', '🤘', '🤞', '🤟', '🤙', '👊', '👋', '👏', '👐', '✋', '🤚', '🤝', '🙏', '💍', '💔', '❤️', '💕', '💞', '💓', '💗', '💖', '💘', '💝', '💟', '💤', '💢', '💣', '💥', '💫', '💦', '💨', '🕳️', '💧', '💩', '🙈', '🙉', '🙊', '💪', '👈', '👉', '👆', '👇', '🖕', '🤘', '🤞', '🤟', '🤙', '👊', '👋', '👏', '👐', '✋', '🤚', '🤝', '🙏', '💍', '💔', '❤️', '💕', '💞', '💓', '💗', '💖', '💘', '💝', '💟', '💤', '💢', '💣', '💥', '💫', '💦', '💨', '🕳️', '💧', '💩', '🙈', '🙉', '🙊', '💪', '👈', '👉', '👆', '👇', '🖕', '🤘', '🤞', '🤟', '🤙', '👊', '👋', '👏', '👐', '✋', '🤚', '🤝', '🙏', '💍', '💔', '❤️', '💕', '💞', '💓', '💗', '💖', '💘', '💝', '💟', '💤', '💢', '💣', '💥', '💫', '💦', '💨', '🕳️', '💧', '💩', '🙈', '🙉', '🙊', '💪', '👈', '👉', '👆', '👇', '🖕', '🤘', '🤞', '🤟', '🤙', '👊', '👋', '👏', '👐', '✋', '🤚', '🤝', '🙏', '💍', '💔', '❤️', '💕', '💞', '💓', '💗', '💖', '💘', '💝', '💟', '💤', '💢', '💣', '💥', '💫', '💦', '💨', '🕳️', '💧', '💩', '🙈', '🙉', '🙊', '💪', '👈', '👉', '👆', '👇', '🖕', '🤘', '🤞', '🤟', '🤙', '👊', '👋', '👏', '👐', '✋', '🤚', '🤝', '🙏', '💍', '💔', '❤️', '💕', '💞', '💓', '💗', '💖', '💘', '💝', '💟', '💤', '💢', '💣', '💥', '💫', '💦', '💨', '🕳️', '💧', '💩', '🙈', '🙉', '🙊', '💪', '👈', '👉', '👆', '👇', '🖕', '🤘', '🤞', '🤟', '🤙', '👊', '👋', '👏', '👐', '✋', '🤚', '🤝', '🙏', '💍', '💔', '❤️', '💕', '💞', '💓', '💗', '💖', '💘', '💝', '💟', '💤', '💢', '💣', '💥', '💫', '💦', '💨', '🕳️', '💧', '💩', '🙈', '🙉', '🙊', '💪', '👈', '👉', '👆', '👇', '🖕', '🤘', '🤞', '🤟', '🤙', '👊', '👋', '👏', '👐', '✋', '🤚', '🤝', '🙏', '💍', '💔', '❤️', '💕', '💞', '💓', '💗', '💖', '💘', '💝', '💟', '💤', '💢', '💣', '💥', '💫', '💦', '💨', '🕳️', '💧', '💩', '🙈', '🙉', '🙊', '💪', '👈', '👉', '👆', '👇', '🖕', '🤘', '🤞', '🤟', '🤙', '👊', '👋', '👏', '👐', '✋', '🤚', '🤝', '🙏', '💍', '💔', '❤️', '💕', '💞', '💓', '💗', '💖', '💘', '💝', '💟', '💤', '💢', '💣', '💥', '💫', '💦', '💨', '🕳️', '💧', '💩', '🙈'];

            let emojis = [...new Set(emojisData)]

            // Number of emojis per row
            const emojisPerRow = 8;

            // Generate emoji grid
            for (let i = 0; i < emojis.length; i++) {
                if (i % emojisPerRow === 0) {
                    // Start a new row
                    const newRow = document.createElement("li");
                    newRow.className = "d-flex";
                    emojiGrid.appendChild(newRow);
                }

                // Create emoji element
                const col = document.createElement("span");
                col.style.padding = "0.5rem"
                col.classList.add("dropdown-item",); // Adjust the grid layout as needed
                col.onclick = ()=>{
                    insertEmoji(emojis[i])
                }
                col.innerHTML = `${emojis[i]}`;

                // Append emoji to the current row
                const currentRow = emojiGrid.lastElementChild;
                document.querySelector("#agentSendMessage").disabled = false
                document.querySelector("#agentSendMessage").classList.remove('disabled')
                currentRow.appendChild(col);

            }
        })

        // Function to update the visibility of the mass delete button
        function updateMassDeleteVisibility() {
            if ($('.checkall:checked').length == 0) {
                $('#massdelete').hide();
            } else {
                $('#massdelete').show();
            }
        }

        // Handle checkbox clicks
        document.querySelectorAll(".checkall").forEach((checkbox) => {
            checkbox.addEventListener('click', function(event) {
                event.stopPropagation();
                updateCustomCheckAll();
                updateMassDeleteVisibility();

                let target = event.target;
                let li = target.closest('li.checkforactive');
                let input = li.querySelector(".chat-actions .dropdown-item");
                let chatUserTabList = document.querySelector('.chat-user-tab-list');
                var checkedCheckboxes = $('.checkall:checked').length;
                let customCheckAll = document.querySelector('#customCheckAll');
                if(input){
                    if(target.checked){
                        chatUserTabList.classList.add('show-checks');
                        input.lastChild.textContent = "Deselect";
                        customCheckAll.nextElementSibling.textContent = checkedCheckboxes + ' '  + "Selected"
                    }else{
                        input.lastChild.textContent = "Select";
                        if(checkedCheckboxes == 0){
                            customCheckAll.nextElementSibling.textContent = ""
                        }else{
                            customCheckAll.nextElementSibling.textContent = checkedCheckboxes + ' '  + "Selected"
                        }
                    }
                }
            });
        });

        $(document).ready(function() {

            $(document).on('click', '#customCheckAll', function() {
                $('.checkall').prop('checked', this.checked);
                let chatUserTabList = document.querySelector('.chat-user-tab-list');
                let inputs = document.querySelectorAll(".checkforactive .chat-actions ul");
                var checkedCheckboxes = $('.checkall:checked').length;
                let customCheckAll = document.querySelector('#customCheckAll');
                inputs.forEach(ele =>{
                    let input = ele.querySelector('.dropdown-item');
                    if(input){
                        if(this.checked){
                        customCheckAll.nextElementSibling.textContent = checkedCheckboxes + ' ' + "Selected"
                        chatUserTabList.classList.add('show-checks');
                        input.lastChild.textContent = "Deselect";
                    }else{
                            if(checkedCheckboxes == 0){
                                customCheckAll.nextElementSibling.textContent = ""
                            }else{
                                customCheckAll.nextElementSibling.textContent = checkedCheckboxes + ' '  + "Selected"
                            }
                            chatUserTabList.classList.remove('show-checks');
                            input.lastChild.textContent = "Select";
                        }
                    }
                })
                updateMassDeleteVisibility();
            });


            // Handle pagination controls
            $(document).on('click', '.pagination a', function() {
                // Assuming '.pagination a' is the selector for your pagination controls
                setTimeout(function() {
                    updateMassDeleteVisibility();
                }, 100);
            });

            // Initialize the "Select All" checkbox to unchecked
            $('#customCheckAll').prop('checked', false);

        });

        $('body').on('click', '#massdelete', function() {
            var id = [];
            var custIds = [];
            $('.checkall:checked').each(function() {
                id.push($(this).val());
                custIds.push($(this).closest('li.checkforactive').data('id'));
            });

            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('admin.ConversationMassDelete')}}",
                            method: "post",
                            data: {
                                id: id
                            },
                            success: function(data) {
                                toastr.success(data.message);

                                $('#selectallbutton').hide();
                                $('#massdelete').hide();

                                custIds.map((custId)=>{
                                    var activecustId = document.querySelector(`.checkforactive.active`)?.getAttribute("data-id");
                                    document.querySelector(`.checkforactive[data-id="${custId}"]`)?.remove()
                                    if(activecustId == custId){
                                        document.querySelector(`#operator-conversation-Info[data-id="${custId}"]`)?.remove()
                                        document.querySelector(`#operator-conversation[operator-id="${custId}"]`)?.remove()
                                        document.querySelector(".engageConversation")?.classList.add("d-none")
                                        document.querySelector(".chat-footer")?.classList.add("d-none")
                                        if(document.querySelector("#chat-msg-scroll li")?.getAttribute("data-id")){
                                            sideMenuOpenClickFunction(document.querySelector(`.checkforactive[data-id="${document.querySelector("#chat-msg-scroll li")?.getAttribute("data-id")}"]`))
                                        }else{
                                            localStorage.removeItem('livechatSolvedCustomer');

                                            let emptyconver = document.createElement("div");
                                            emptyconver.className = "text-center mt-5 px-2 py-4 bg-warning-transparent text-default mx-auto w-90 rounded-2";
                                            emptyconver.innerHTML = `<span>{{ lang('As of now, there are no chat discussions in progress') }}</span>`;
                                            document.querySelector("#chat-msg-scroll").append(emptyconver);
                                            document.querySelector(".no-articles").classList.remove("d-none");
                                        }
                                    }
                                })
                            },
                            error: function(data) {

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

    </script>

    <script>

        // For the Select2
        var optionFormat = function(item){
            if ( !item.id ) {
                return item.text;
            }

            var span = document.createElement('span');
            var imgUrl = item.element.getAttribute('data-kt-select2-country');
            var template = '';

            template += '<img src="' + imgUrl + '" class="rounded-circle h-20px me-2" alt="image"/>';
            template += item.text;

            span.innerHTML = template;

            return $(span);
        }

        $('#reassignSelect').select2({
            templateSelection: optionFormat,
            templateResult: optionFormat,
            placeholder: "Reassign to:",
            allowClear:true,
            dropdownParent: $('#staticBackdrop')
        });

        // To add option the Cannedmessages to model
        $.ajax({
            type: "get",
            url: '{{route('admin.getCannedmessages')}}',
            success: function (data) {
                if(data.success == true){
                    var selectElement = document.getElementById('cannedResponses');
                    selectElement.innerHTML = "<option></option>"

                    data.message.cannedmessages.forEach(function(option) {
                        var optionElement = document.createElement('option');
                        optionElement.value = option.messages;
                        optionElement.textContent = option.title;
                        selectElement.appendChild(optionElement);
                    });

                    $(document).ready(function() {
                        $('#cannedResponses').select2({
                            placeholder: "Canned Responses",
                            allowClear:true,
                            dropdownParent: $('#canned-responses')
                        });
                    });
                }
            },
            error: function (data) {
                console.log('Error:', data);
            }
        });

        // To add value in the text area
        document.getElementById('cannedResponses').onchange=(ele=>{
            document.querySelector("#auto-expand").innerHTML = document.querySelector("#auto-expand").innerHTML + ele.target.value
            // to remove the disabled from the Message send btn
            document.querySelector("#agentSendMessage").removeAttribute('disabled')
            document.querySelector("#agentSendMessage").classList.remove('disabled')

            // to remove the disabled from the Create Ticket btn
            if(document.querySelector("#livechatTicketSubject")?.value.trim()){
                document.querySelector("#agentCreateTicket").removeAttribute('disabled')
                document.querySelector("#agentCreateTicket").classList.remove('disabled')
            }

            // To Close the Model
            $('#canned-responses').modal('toggle');
            $('#cannedResponses').select2({
                placeholder: {
                    id: '',
                    text: 'Canned Responses'
                },
                // allowClear: true
            });

            const divcontent = document.querySelector("#auto-expand");

            divcontent.style.height = "auto";
            divcontent.style.height = Math.min(divcontent.scrollHeight, 200) + "px";
            divcontent.scrollTop = 0;

            divcontent.focus();
            let selection = window.getSelection();
            let rng = selection.getRangeAt(0);
            let newRng = document.createRange();
            newRng.setStartAfter(divcontent.lastChild)
            newRng.setEndAfter(divcontent.lastChild)
            selection.removeAllRanges();
            selection.addRange(newRng);
        })

        const textarea = document.getElementById("auto-expand");
        textarea.addEventListener("input", () => {
            textarea.style.height = "auto";
            textarea.style.height = Math.min(textarea.scrollHeight, 200) + "px";
            textarea.scrollTop = 0;
        });

        let spellCheckEnabled = @json(setting('spellCheck'));
        let suggestionsEnabled = @json(setting('wordSuggestion'));

        if (spellCheckEnabled != 'off' || suggestionsEnabled != 'off') {

            let previousContent = "";
            let debounceTime;
            let latestInput = "";
            let userText;

            // Input event to process the text
            textarea.addEventListener("input", function () {
                if(document.getElementById('suggestionText')){
                    document.getElementById('suggestionText').remove()
                }
                userText = textarea.innerText.trim();
                const currentSelection = window.getSelection();
                const cursorAtEnd = currentSelection.rangeCount > 0 && currentSelection.getRangeAt(0).endOffset > 0 && textarea.innerText.length > 0;

                // Fetch only when cursor is at the end and content has changed
                if (cursorAtEnd && userText !== previousContent) {
                    previousContent = userText;
                    clearTimeout(debounceTime);

                    debounceTime = setTimeout(() => {
                        if (userText.length > 0) {
                            fetchCombinedRequest(userText);
                        }
                    }, 1000);
                } else {
                    if(document.getElementById('suggestionText')){
                        document.getElementById('suggestionText').innerText = "";
                    }
                }
            });

            async function fetchCombinedRequest(userInput) {
                try {
                    let url = '{{ route('geminiGet') }}';
                    const response = await fetch(url, {
                        method: "POST",
                        headers: {
                            "Content-Type": "application/json",
                            'X-CSRF-TOKEN': '{{ csrf_token() }}'
                        },
                        body: JSON.stringify({ value: userInput }),
                    });

                    if (!response.ok) throw new Error("Failed to fetch");

                    const data = await response.json();

                    handleCombinedResponse(data.generated_text);
                } catch (error) {
                    console.error("Error fetching data:", error);
                }
            }

            // Function to handle combined response
            function handleCombinedResponse(responseText) {
                if (spellCheckEnabled == 'on' && suggestionsEnabled == 'on') {
                    const spellCheckResponse = parseApiResponse(responseText); // Parse spell check response
                    const suggestionsResponse = responseText.match(/suggestion:\s*([a-zA-Z\s]+)/)?.[1];
                    if (spellCheckResponse) {
                        applyCorrections(spellCheckResponse);
                        placeCaretAtEnd();
                    }

                    // Display suggestions
                    if (suggestionsResponse) {
                        displaySuggestion(suggestionsResponse);
                    }
                } else if (spellCheckEnabled == 'on' && suggestionsEnabled == 'off') {
                    const correctedText = parseApiResponse(responseText);
                    applyCorrections(correctedText);
                    placeCaretAtEnd();
                } else if (suggestionsEnabled == 'on') {
                    displaySuggestion(responseText.trim());
                }
            }

            function parseApiResponse(responseText) {
                const corrections = {};
                let formattedResponse = responseText.replace(/['"]+/g, "");
                formattedResponse = formattedResponse.replace(/\n/g, ",");
                const pairs = formattedResponse.split(",");
                pairs.forEach(pair => {
                    const [misspelled, corrected] = pair.split(":").map(s => s.trim());
                    if (misspelled && corrected && misspelled != corrected) {
                        corrections[misspelled] = corrected;
                    }
                });
                return corrections;
            }

            function applyCorrections(corrections) {
                let htmlContent = textarea.innerHTML;
                Object.entries(corrections).forEach(([misspelled, corrected]) => {
                    const regex = new RegExp(`\\b${escapeRegExp(misspelled)}\\b`, 'gi');
                    htmlContent = htmlContent.replace(regex,
                        `<span class="misspelled" data-corrected="${corrected}">${misspelled}</span>`
                    );
                });
                textarea.innerHTML = htmlContent;
                placeCaretAtEnd();
            }

            function displaySuggestion(responseApi) {
                if(document.getElementById('suggestionText')){
                    document.getElementById('suggestionText').remove();
                }

                var suggestionTextData = document.createElement('span');
                suggestionTextData.setAttribute('id','suggestionText');
                suggestionTextData.innerHTML = responseApi.trim();

                const selection = window.getSelection();
                if (!selection || !selection.rangeCount) {
                    return;
                }
                if (userText == textarea.innerText.trim()) {
                    document.getElementById('auto-expand').append(suggestionTextData)
                }
            }
            textarea.addEventListener('keydown', function (e) {
                if (e.key === "Tab") {
                    e.preventDefault();

                    const suggestionTextData = document.getElementById('suggestionText');
                    if (suggestionTextData && suggestionTextData.innerText.trim().length > 0) {
                        let userInput = textarea.innerText.trim();
                        let suggestion = suggestionTextData.innerText.trim();
                        if (userInput.endsWith(suggestion)) {
                            userInput = userInput.slice(0, -suggestion.length).trim();
                        }
                        textarea.innerText = `${userInput} ${suggestion}`;
                        suggestionTextData.innerText = '';
                        if (suggestionTextData) {
                            suggestionTextData.remove();
                        }
                        placeCaretAtEnd();
                    }
                }
            });

            function escapeRegExp(string) {
                return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
            }

            document.body.addEventListener('mouseover', function (event) {
                const element = event.target;
                if (element.classList.contains('misspelled')) {
                    showTooltip(event, element);
                }
            });

            document.body.addEventListener('mouseout', function (event) {
                const element = event.target;
                const relatedTarget = event.relatedTarget;

                if (element.classList.contains('misspelled')) {
                    if (relatedTarget && relatedTarget.classList.contains('correctedtooltip')) {
                        return;
                    }
                    hideTooltip();
                } else if (element.classList.contains('correctedtooltip')) {
                    if (relatedTarget && relatedTarget.classList.contains('misspelled')) {
                        return;
                    }
                    hideTooltip();
                }
            });

            function showTooltip(event, element) {
                const correctedWord = element.getAttribute('data-corrected');
                hideTooltip();

                const tooltip = document.createElement('span');
                tooltip.className = 'correctedtooltip';
                tooltip.textContent = correctedWord;

                // Styling
                tooltip.style.backgroundColor = '#fff';
                tooltip.style.border = '1px solid #ccc';
                tooltip.style.padding = '5px';
                tooltip.style.zIndex = '1000';
                tooltip.style.boxShadow = '0px 2px 8px rgba(0, 0, 0, 0.2)';
                tooltip.style.borderRadius = '4px';

                element.parentNode.insertBefore(tooltip, element.nextSibling);

                tooltip.onclick = (e) => {
                    e.stopPropagation();
                    replaceWord(element, correctedWord);
                };

                element.tooltip = tooltip;
            }

            function hideTooltip() {
                const existingTooltip = document.querySelector('.correctedtooltip');
                if (existingTooltip) {
                    existingTooltip.remove();
                }
            }

            function replaceWord(element, correctedWord) {
                const parent = element.parentElement;
                if(parent.classList.contains('misspelled')){
                    parent.classList.remove('misspelled');
                }
                parent.innerHTML = parent.innerHTML.replace(
                    new RegExp(`<span[^>]*>${element.textContent}</span>`, 'gi'),
                    correctedWord
                );
                hideTooltip();
                placeCaretAtEnd()
            }

            function placeCaretAtEnd() {
                setTimeout(() => {
                    textarea.focus();
                    const range = document.createRange();
                    const selection = window.getSelection();
                    range.selectNodeContents(textarea);
                    range.collapse(false);
                    selection.removeAllRanges();
                    selection.addRange(range);
                }, 1);
            }
        }

        // To open the Create ticket Form
        document.querySelector("#create-ticket-btn").onclick = (event)=>{
            event.currentTarget.querySelector("i").classList.add("text-primary")
            document.querySelector(".chat-reply-area #chat-btn i").classList.remove("text-primary")
            document.querySelector(".chat-reply-area .create-ticket").classList.remove("d-none")
            document.querySelector("#assigneediv").classList.remove("d-none")
            document.querySelector("#prioritydiv").classList.remove("d-none")
            document.querySelector(".chat-reply-area #auto-expand").classList.remove("border-0")
            document.querySelector(".chat-reply-area #auto-expand").classList.add("border-1","my-2")
            document.querySelector("#agentCreateTicket").classList.remove("d-none")
            document.querySelector("#agentSendMessage").classList.add("d-none")
            document.querySelector(".create-ticket-description").classList.remove("d-none")

            // For the category
            document.querySelector("#category").closest('.form-group').classList.remove("d-none")
            document.querySelector("#envatopurchase").classList.remove("d-none")
        }

        // For the Chat Btn
        document.querySelector("#chat-btn").onclick = ()=>{
            event.currentTarget.querySelector("i").classList.add("text-primary")
            document.querySelector(".chat-reply-area #create-ticket-btn i").classList.remove("text-primary")
            document.querySelector(".chat-reply-area .create-ticket").classList.add("d-none")
            document.querySelector("#assigneediv").classList.add("d-none")
            document.querySelector("#prioritydiv").classList.add("d-none")
            document.querySelector(".chat-reply-area #auto-expand").classList.add("border-0")
            document.querySelector(".chat-reply-area #auto-expand").classList.remove("border-1","my-2")
            document.querySelector("#agentCreateTicket").classList.add("d-none")
            document.querySelector("#agentSendMessage").classList.remove("d-none")
            document.querySelector(".create-ticket-description").classList.add("d-none")


            // For the category
            document.querySelector("#category").closest('.form-group').classList.add("d-none")
            document.querySelector("#envatopurchase").classList.add("d-none")
        }

        // Enter Subject key Upcheck
        document.getElementById('livechatTicketSubject').addEventListener('keyup', function (event) {
            let agentCreateTicketBtn = document.querySelector("#agentCreateTicket")

            let envatoId = true

            if(document.querySelector("#envato_id")){
                envatoId = document.querySelector("#envato_id").getAttribute("readonly") == 'readonly'
            }

            // To Remove the Disabled For The Ticket Create Btn
            if(document.querySelector("#auto-expand").value &&
                event.target.value &&
                document.querySelector("#category").value &&
                envatoId
            ){
                agentCreateTicketBtn.disabled = false
                agentCreateTicketBtn.classList.remove('disabled')
            }else{
                agentCreateTicketBtn.disabled = true
                agentCreateTicketBtn.classList.add('disabled')
            }

            // subject character restriction
            if(event.target.value.length == {{setting('TICKET_CHARACTER')}}){
                document.querySelector('#subjectmaxtextsss').classList.remove('text-muted');
                document.querySelector('#subjectmaxtextsss').classList.add('text-red');
            }else{
                document.querySelector('#subjectmaxtextsss').classList.remove('text-red');
                document.querySelector('#subjectmaxtextsss').classList.add('text-muted');
            }
            localStorage.setItem('adminsubject', event.target.value)
        });

        // For the category Change
        document.querySelector("#category").onchange = (ele)=>{
            let agentCreateTicketBtn = document.querySelector("#agentCreateTicket")

            let envatoId = true
            setTimeout(() => {
                if(document.querySelector("#envato_id")){
                    envatoId = document.querySelector("#envato_id").getAttribute("readonly") == 'readonly'
                }

                // To Remove the Disabled For The Ticket Create Btn
                if(document.querySelector("#auto-expand").value &&
                document.querySelector("#livechatTicketSubject").value &&
                document.querySelector("#category").value &&
                envatoId
                ){
                    agentCreateTicketBtn.disabled = false
                    agentCreateTicketBtn.classList.remove('disabled')
                }else{
                    agentCreateTicketBtn.disabled = true
                    agentCreateTicketBtn.classList.add('disabled')
                }
            }, 1000);
        }

        // For the Category
        $('#category').on('change',function(e) {
                var cat_id = e.target.value;
                $.ajax({
                    url:"{{ route('guest.subcategorylist') }}",
                    type:"POST",
                        data: {
                        cat_id: cat_id
                        },
                        cache : false,
                        async: true,
                    success:function (data) {
                        if(data.subcategoriess){
                        $('#selectssSubCategory').hide()
                        $('#subscategory').html(data.subcategoriess)
                            $('#selectssSubCategory').show()
                        } else{
                            $('#selectssSubCategory').hide();
                            $('#subscategory').html('')
                        }

                        if(data.subCatStatus.length === 0){
                            $('#selectssSubCategory').hide();
                        }

                        if(data.categorypriority){
                            $('#priority').val(data.categorypriority).trigger('change');
                        }else{
                            $('#priority').val('').trigger('change');
                        }

                        @if(setting('ENVATO_ON') == 'on')
                            //Envato Access
                            if(data.envatosuccess.length >= 1){
                                $('#envato_id')?.empty();
                                $('#envatopurchase .row')?.remove();
                                let selectDiv = document.querySelector('#envatopurchase');
                                let Divrow = document.createElement('div');
                                Divrow.setAttribute('class','row mt-4');
                                let Divcol3 = document.createElement('div');
                                Divcol3.setAttribute('class','col-md-12');
                                let selectlabel =  document.createElement('label');
                                selectlabel.setAttribute('class','form-label mb-0 mt-2')
                                selectlabel.innerHTML = "Envato Purchase Code <span class='text-red'>*</span>";
                                let divcol9 = document.createElement('div');
                                divcol9.setAttribute('class', 'col-md-12');
                                let selecthSelectTag =  document.createElement('input');
                                selecthSelectTag.setAttribute('class','form-control');
                                selecthSelectTag.setAttribute('type','search');
                                selecthSelectTag.setAttribute('id', 'envato_id');
                                selecthSelectTag.setAttribute('name', 'envato_id');
                                selecthSelectTag.setAttribute('placeholder', 'Enter Your Purchase Code');
                                let selecthSelectInput =  document.createElement('input');
                                selecthSelectInput.setAttribute('type','hidden');
                                selecthSelectInput.setAttribute('id', 'envato_support');
                                selecthSelectInput.setAttribute('name', 'envato_support');
                                selectDiv.append(Divrow);
                                Divrow.append(Divcol3);
                                Divcol3.append(selectlabel);
                                divcol9.append(selecthSelectTag);
                                divcol9.append(selecthSelectInput);
                                Divrow.append(divcol9);
                                $('.purchasecode').attr('disabled', true);

                            }else{
                                $('#hideelement').addClass('d-none');
                                $('#envato_id').val('');
                                $('#envato_id')?.empty();
                                $('#envatopurchase .row')?.remove();
                                $('.purchasecode').removeAttr('disabled');
                            }
                        @endif
                    },
                    error:(data)=>{

                    }
                });
        });

        let envatoIdStatus = ""

        $("body").on('keyup', '#envato_id', function() {
                let value = $(this).val();
                if (value != '') {
                    if(value.length == '36'){
                        var _token = $('input[name="_token"]').val();
                        $.ajax({
                            url: "{{ route('guest.envatoverify') }}",
                            method: "POST",
                            data: {data: value, _token: _token},

                            dataType:"json",

                            success: function (data) {
                                if(data.valid == 'true'){
                                    $('#envato_id').addClass('is-valid');
                                    $('#envato_id').attr('readonly', true);
                                    $('.purchasecode').removeAttr('disabled');
                                    $('#productname').val(data.name);
                                    $('#productname').attr('readonly', true);
                                    $('#itemname').val(data.name);
                                    $('#hideelement').removeClass('d-none');
                                    $('#envato_id').css('border', '1px solid #02f577');
                                    $('#envato_support').val('Supported');
                                    $('#expired_note').addClass('d-none');
                                    licensekey = data.key
                                    toastr.success(data.message);
                                    envatoIdStatus = "Supported"
                                    if(document.querySelector("#auto-expand").textContent &&
                                        document.querySelector("#category").value
                                    ){
                                        document.querySelector("#agentCreateTicket").disabled = false
                                        document.querySelector("#agentCreateTicket").classList.remove('disabled')
                                    }else{
                                        document.querySelector("#agentCreateTicket").disabled = true
                                        document.querySelector("#agentCreateTicket").classList.add('disabled')
                                    }
                                }
                                if(data.valid == 'expried'){
                                    @if(setting('ENVATO_EXPIRED_BLOCK') == 'on')

                                    $('.purchasecode').attr('disabled', true);
                                    $('#envato_id').css('border', '1px solid #e13a3a');
                                    $('#productname').val(data.name);
                                    $('#productname').attr('readonly', true);
                                    $('#itemname').val(data.name);
                                    $('#hideelement').removeClass('d-none');
                                    $('#envato_support').val('Expired');
                                    $('#expired_note').removeClass('d-none');
                                    toastr.error(data.message);
                                    document.querySelector("#agentCreateTicket").disabled = true
                                    document.querySelector("#agentCreateTicket").classList.add('disabled')
                                    @endif
                                    @if(setting('ENVATO_EXPIRED_BLOCK') == 'off')
                                    $('#envato_id').addClass('is-valid');
                                    $('#envato_id').attr('readonly', true);
                                    $('.purchasecode').removeAttr('disabled');
                                    $('#productname').val(data.name);
                                    $('#productname').attr('readonly', true);
                                    $('#itemname').val(data.name);
                                    $('#hideelement').removeClass('d-none');
                                    $('#envato_id').css('border', '1px solid #02f577');
                                    $('#expired_note123').removeClass('d-none');
                                    $('#envato_support').val('Expired');
                                    licensekey = data.key
                                    toastr.warning(data.message);
                                    envatoIdStatus = "Expired"
                                    if(document.querySelector("#auto-expand").textContent &&
                                        document.querySelector("#category").value
                                    ){
                                        document.querySelector("#agentCreateTicket").disabled = false
                                        document.querySelector("#agentCreateTicket").classList.remove('disabled')
                                    }else{
                                        document.querySelector("#agentCreateTicket").disabled = true
                                        document.querySelector("#agentCreateTicket").classList.add('disabled')
                                    }
                                    @endif

                                }
                                if(data.valid == 'false'){
                                    $('.purchasecode').attr('disabled', true);
                                    $('#envato_id').css('border', '1px solid #e13a3a');
                                    toastr.error(data.message);
                                    document.querySelector("#agentCreateTicket").disabled = true
                                    document.querySelector("#agentCreateTicket").classList.add('disabled')
                                }


                            },
                            error: function (data) {

                            }
                        });
                    }
                }else{
                    toastr.error('Purchase Code field is Required');
                    $('.purchasecode').attr('disabled', true);
                    $('#envato_id').css('border', '1px solid #e13a3a');
                }
        });

        // When User try to Delete the chat to ask the are you sure alert
        function deletingdatafunction(){
            document.querySelectorAll("[deleteroutelink]").forEach((ele)=>{
                ele.onclick = ()=>{
                    swal({
                        title: `{{lang('Are you sure you want to continue?', 'alerts')}}`,
                        text: "{{lang('The conversation will be deleted', 'alerts')}}",
                        icon: "warning",
                        buttons: true,
                        dangerMode: true,
                    }).then((res)=>{
                        if(res){
                            $.ajax({
                                type: "get",
                                url: ele.getAttribute("deleteroutelink"),
                                success: function (data) {

                                    localStorage.removeItem('livechatSolvedCustomer');
                                    toastr.success("Chat Deleted");

                                    var activecustId = document.querySelector(`.checkforactive.active`)?.getAttribute("data-id");
                                    var deletecustId = ele.closest('.checkforactive')?.getAttribute("data-id") ?? ele.closest('#operator-conversation-Info')?.getAttribute("data-id");
                                    document.querySelector(`.checkforactive[data-id="${deletecustId}"]`)?.remove()
                                    if(activecustId == deletecustId){
                                        document.querySelector(`#operator-conversation-Info[data-id="${deletecustId}"]`)?.remove()
                                        document.querySelector(`#operator-conversation[operator-id="${deletecustId}"]`)?.remove()
                                        document.querySelector(".engageConversation")?.classList.add("d-none")
                                        document.querySelector(".chat-footer")?.classList.add("d-none")
                                        if(document.querySelector("#chat-msg-scroll li")?.getAttribute("data-id")){
                                            sideMenuOpenClickFunction(document.querySelector(`.checkforactive[data-id="${document.querySelector("#chat-msg-scroll li")?.getAttribute("data-id")}"]`))
                                        }else{
                                            localStorage.removeItem('livechatSolvedCustomer');

                                            let emptyconver = document.createElement("div");
                                            emptyconver.className = "text-center mt-5 px-2 py-4 bg-warning-transparent text-default mx-auto w-90 rounded-2";
                                            emptyconver.innerHTML = `<span>{{ lang('As of now, there are no chat discussions in progress') }}</span>`;
                                            document.querySelector("#chat-msg-scroll").append(emptyconver);
                                            document.querySelector(".no-articles").classList.remove("d-none");
                                        }
                                    }
                                },
                                error: function (data) {
                                    console.log('Error:', data);
                                }
                            })
                        }
                    })
                }
            })
        }
        deletingdatafunction();
    </script>

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

    // Variables
    var SITEURL = '{{url('')}}';
    const autoID = '{{Auth::user()->id}}'
    const autoUserInfo = JSON.parse('{!! addslashes(json_encode(Auth::user())) !!}');
    const AllUserDetails = JSON.parse('{!! addslashes(json_encode($user)) !!}');

    let customerData

    var texttospeachenabled = '{{ setting('CHAT_TEXT_TO_SPEACH_ENABLE') }}';
    var texttranslateenabled = '{{ setting('CHAT_TEXT_TRANSLATE_ENABLE') }}';
    function texttospeachbtn() {
        if(event.target.closest('.ms-3').querySelector('.main-chat-msg p')){
            $('.select2_texttospeach').select2({
                dropdownParent: ".texttospeachmodal",
                minimumResultsForSearch: '',
                placeholder: "Search",
                width: '100%'
            });
            $('#texttospeachcontent').val(event.target.closest('.ms-3').querySelector('.main-chat-msg p').textContent);
            $('#texttospeachmodal').modal('show');
        }else{
            toastr.error('{{ lang('There is no text to speach.', 'alerts') }}');
        }
    }

    function langtranslatebtn() {
        var targetElement = event.target.closest('.ms-3').querySelector('.main-chat-msg p');
        if(targetElement){
            $('.select2_texttranslation').select2({
                dropdownParent: ".texttranslationmodal",
                minimumResultsForSearch: '',
                placeholder: "Search",
                width: '100%'
            });
            $('#texttranslationmodal').modal('show');

            document.querySelector('#translateButtonSave').onclick = async () =>{
                document.querySelector('#translateButtonSave').innerHTML = "{{ lang('Translating') }} ... <i class='fa fa-spinner fa-spin'></i>";
                const textInput = targetElement.innerText;
                const selectedLang = document.getElementById('translate-lang').value;

                try {
                    const translatedText = await translateText(textInput, selectedLang);
                    targetElement.innerHTML = translatedText;
                    document.querySelector('#translateButtonSave').innerHTML = "{{ lang('Translate') }}";
                    $('#texttranslationmodal').modal('hide');
                } catch (error) {
                    console.error('Error:', error);
                }
            }
        }else{
            toastr.error('{{ lang('There is no text to translate.', 'alerts') }}');
        }
    }

    function formatTime(inputTime) {
        const jsDate = new Date(inputTime);
        let timeFormat = @json(setting('time_format'));
        let formattedTime;
        switch (timeFormat) {
            case 'H:i:s': // 24-hour format with seconds
                formattedTime = jsDate.toLocaleTimeString('en-GB', {
                    hour: '2-digit',
                    minute: '2-digit',
                    second: '2-digit',
                    hour12: false
                });
                break;
            case 'h:i A': // 12-hour format with AM/PM
                formattedTime = jsDate.toLocaleTimeString('en-US', {
                    hour: '2-digit',
                    minute: '2-digit',
                    hour12: true
                });
                break;
            case 'H:i': // 24-hour format without seconds
                formattedTime = jsDate.toLocaleTimeString('en-GB', {
                    hour: '2-digit',
                    minute: '2-digit',
                    hour12: false
                });
                break;
            default:
                formattedTime = jsDate.toLocaleTimeString(); // Default format
        }

        return `${formattedTime}`;
    }

    // File Upload Permission Check Btn
    document.querySelector("#fileUploadPermission").onclick = ()=>{
        let data = {
            permission : document.querySelector("#fileUploadPermission").checked,
            custUser : document.querySelector("#fileUploadPermission").getAttribute('data-id')
        }

        $.ajax({
            type: "post",
            url: '{{route('admin.liveChatCustFileUpload')}}',
            data: data,
            success: function (data) {
                if(data.success){
                    toastr.success(data.message)
                }
            },
            error: function (data) {
                console.log('Error:', data);
            }
        });
    }

    // For the LiveChat Ticket Create
    document.querySelector("#agentCreateTicket").onclick = ()=>{

        if (document.querySelector("#auto-expand").querySelector("#suggestionText")) {
            document.querySelector("#auto-expand").querySelector("#suggestionText").remove();
        }

        if (document.querySelector("#auto-expand").querySelector(".misspelled")) {
            document.querySelector("#auto-expand").querySelectorAll(".misspelled").forEach((element) => {
                // Create a text node with the innerText of the current element
                const textNode = document.createTextNode(element.innerText);
                // Replace the misspelled element with the text node
                element.parentNode.replaceChild(textNode, element);
            });
        }

        document.querySelector("#agentCreateTicket").disabled = true
        document.querySelector("#agentCreateTicket").classList.add('disabled')
        document.querySelector("#agentCreateTicket").innerHTML = `Creating ... <i class="fa fa-spinner fa-spin"></i>`
        let data ={
            email : customerData.email,
            username : customerData.username,
            subject : document.querySelector("#livechatTicketSubject").value,
            category : document.querySelector("#category").value,
            assigneeid : document.querySelector("#assignee").value,
            productname : document.querySelector("#itemname").value,
            priority : document.querySelector("#priority").value,
            envato_id : document.querySelector("#envato_id") ? document.querySelector("#envato_id").value : "undefined",
            message : sanitizeHTML(document.querySelector("#auto-expand").textContent),
            ticket: [

            ],
        }

        // To add the subscategory
        if(document.querySelector("#subscategory")){
            data.subscategory = document.querySelector("#subscategory").value
        }

        // To add the Envato status
        if(envatoIdStatus){
            data.envato_support = envatoIdStatus
        }

        // For the Images Add
        if(document.querySelector(".image-uploaded [imageFileName]")){
            document.querySelectorAll(".image-uploaded [imageFileName]").forEach((ele)=>{
                const parts = ele.getAttribute('imageFileName').split("/");
                const filename = parts[parts.length - 1];
                data.ticket.push(filename)
                ele.closest(".file-img").remove()
            })
        }

        $.ajax({
            type: "POST",
            url: '{{route('livechat.ticketcreate')}}',
            data: data,
            success: function (responceData) {

                if(responceData?.error){
                    toastr.error(responceData.error);
                }
                if(responceData?.success){
                    toastr.success(responceData.success);
                    // To send the Ticket Created message
                    let PresentTimeFormatted = `${((new Date().getHours() + 11) % 12) + 1}:${new Date().getMinutes()}${new Date().getHours() >= 12 ? "PM" : "AM"}`;
                    let data ={
                        message : `\n ${responceData.success}. Please check your email to information and reply for this ticket in your mail directly.`,
                        cust_id :customerData.id,
                        customerId: customerData.id,
                        userType: customerData.userType
                    }


                    let senderMessage = document.createElement("li");
                    senderMessage.className = "chat-item-start"
                    senderMessage.innerHTML = `
                        <div class="chat-list-inner">
                            <div class="chat-user-profile">
                                <span class="avatar avatar-md brround" style="background-image: url(${document.querySelector(".leading-none img").src})">
                                </span>
                            </div>
                            <div class="ms-3">
                                <span class="chatting-user-info">
                                    You
                                    <span class="msg-sent-time">
                                        ${PresentTimeFormatted}
                                        <span class="chat-read-icon align-middle d-inline-flex"><i class="ri-check-fill"></i></span>
                                    </span>
                                    ${texttospeachenabled == 'on' || texttranslateenabled == 'on' ?
                                        `<a aria-label="anchor" href="javascript:void(0);" data-bs-toggle="dropdown" aria-expanded="false" class='float-end msg-send-dropdown'>
                                            <i class="fe fe-more-vertical fs-18"></i>
                                        </a>
                                        <ul class="dropdown-menu">
                                            ${texttospeachenabled == 'on' ?
                                                `<li>
                                                    <a aria-label="anchor" class="dropdown-item" href="javascript:void(0);" onclick="texttospeachbtn()">
                                                        <i class="ri-volume-up-fill align-middle me-2 fs-17 text-muted chat-info-optionicon d-inline-block"></i>{{ lang('Text To Speach') }}
                                                    </a>
                                                </li>` : ''}
                                            ${texttranslateenabled == 'on' ?
                                                `<li>
                                                    <a aria-label="anchor" class="dropdown-item" href="javascript:void(0);" onclick="langtranslatebtn()">
                                                        <i class="ri-volume-up-fill align-middle me-2 fs-17 text-muted chat-info-optionicon d-inline-block"></i>{{ lang('Language Translate') }}
                                                    </a>
                                                </li>` : ''}
                                        </ul>`
                                        : ''
                                    }
                                </span>
                                <div class="main-chat-msg">
                                    <div style="white-space: pre-line;" class="text-start">
                                        <p class="mb-0 text-break">${data.message}</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    `
                    let operatorConversation = document.querySelector("#operator-conversation")

                    if(responceData.success){
                        if(operatorConversation.lastElementChild && operatorConversation.lastElementChild.id === "agentTyping") {
                            operatorConversation.insertBefore(senderMessage, operatorConversation.lastElementChild);
                        } else {
                            operatorConversation.appendChild(senderMessage);
                        }

                        // To Scroll Down the Conversation
                        document.querySelector("#operator-conversation").scrollBy(0, document.querySelector("#operator-conversation").scrollHeight)

                        // After message sent show the message in the top
                        document.querySelectorAll("#chat-msg-scroll > li").forEach((operatorsChat)=>{
                            if(operatorsChat.getAttribute('data-id') == document.querySelector("#operator-conversation").getAttribute('operator-id')){
                                operatorsChat.querySelector(".chat-msg").classList.remove("font-weight-bold")
                                operatorsChat.querySelector(".chat-msg").innerHTML = data.message.replace(/\n/g, ' ')
                                operatorsChat.querySelector(".chat-time").innerText = new Date().toLocaleTimeString()
                                if(operatorsChat.querySelector(".chat-msg").parentNode.querySelector('.d-inline-flex')){
                                    operatorsChat.querySelector(".chat-msg").parentNode.querySelector('.d-inline-flex').remove()
                                }
                                if(document.querySelector("#messageStatusDiv")){
                                    document.querySelector("#messageStatusDiv").remove()
                                }
                                // To remove the Make as unread button
                                if(operatorsChat.querySelector(".markAsUnreadBtn")){
                                    operatorsChat.querySelector(".markAsUnreadBtn").parentNode.remove()
                                }
                                const messageStatus = document.createElement("div");
                                messageStatus.id = "messageStatusDiv"
                                // operatorsChat.querySelector(".chat-msg").parentNode.appendChild(messageStatus)
                                document.querySelector("#chat-msg-scroll").insertBefore(operatorsChat, document.querySelector("#chat-msg-scroll > li"));
                            }
                        })

                        // To Scroll Down the Conversation
                        operatorConversation.scrollBy(0, operatorConversation.scrollHeight)
                    }

                    textarea.style.height = '49px'

                    $.ajax({
                        type: "post",
                        url: SITEURL + "/livechat/broadcast-message",
                        data: data,
                        success: function (data) {
                            if(localStorage.getItem("livechatMyopenedCustomer")){
                                localStorage.setItem("livechatSolvedCustomer",localStorage.getItem("livechatMyopenedCustomer"));
                                localStorage.removeItem("livechatMyopenedCustomer");
                            }
                            location.href = `${SITEURL}/admin/livechat/mark-as-solved?id=${customerData.id}`
                        },
                        error: function (error) {
                            if(error.responseJSON){
                                toastr.error("The message field cannot be null")
                            }
                        }
                    });
                }
            },
            error: function (data) {
                console.log('Error:', data);
                if (data.responseJSON.message){
                    toastr.error(data.responseJSON.message);
                }
                document.querySelector("#agentCreateTicket").removeAttribute('disabled')
                document.querySelector("#agentCreateTicket").classList.remove('disabled')
                document.querySelector("#agentCreateTicket").innerHTML = `
                        <i class="ri-send-plane-2-fill fs-20"></i>
                    `
            }
        });
    }

    // conversation Image Upload
    let livechatMaxFileUpload = "{{setting('AgentToCustLivechatMaxFileUpload')}}"
    let livechatFileUploadMax = "{{setting('AgentToCustLivechatFileUploadMax')}}"
    let livechatFileUploadTypes = "{{setting('AgentToCustLivechatFileUploadTypes')}}"

    // Chat Image Upload
    if(document.querySelector("#chat-file-upload")){
        document.querySelector("#chat-file-upload").addEventListener('change',()=>{
            var fileInput = document.querySelector("#chat-file-upload");
            var file = fileInput.files[0];
            fileInput.value = ""
            var ThereIsError = false

            // For check the File Upload permissions
            if(livechatMaxFileUpload <= document.querySelectorAll(".image-uploaded .file-img").length){
                ThereIsError = { errorMessage: "The maximum file upload limit has been exceeded." };
            }else if(file.size > parseInt(livechatFileUploadMax) * 1024 * 1024) {
                ThereIsError = { errorMessage: `File size exceeds ${livechatFileUploadMax} MB. Please choose a smaller file.` };
            }else if(livechatFileUploadTypes && !livechatFileUploadTypes.split(',').some(ext => file.name.toLowerCase().toLowerCase().endsWith(ext.toLowerCase().trim()))) {
                ThereIsError = { errorMessage: `Invalid file extension. Please choose a file with ${livechatFileUploadTypes} extension(s).` };
            }else{
                ThereIsError = false
            }

            // For add the Upload indication
            let uploadingIndication = document.createElement("p")
            uploadingIndication.className = "fw-lighter ms-4"
            uploadingIndication.id = "uploadingIndication"
            uploadingIndication.innerHTML = `uploading`
            // Upload The File
            if (file && !ThereIsError) {
                // Adding the Uploding indication
                document.querySelector(".image-uploaded").appendChild(uploadingIndication)


                var formData = new FormData();
                formData.append('chatFileUpload', file);

                fetch('{{route('admin.liveChatImageUpload')}}',{
                    method: 'POST',
                    body: formData,
                    headers:{
                        'X-CSRF-TOKEN': '{{ csrf_token() }}', // Include CSRF token
                    },
                })
                .then(response => response.json())
                .then(data => {
                    const imageDiv = document.createElement("div");
                    let uploadedFilename = data.uploadedfilename;
                    imageDiv.classList.add("file-img")
                    imageDiv.innerHTML = `
                        <img imageSrc="${data.imageurl}" imageFileName="${uploadedFilename}" src="${uploadedFilename.toLowerCase().endsWith(".jpg") || uploadedFilename.toLowerCase().endsWith(".png") ? `${data.imageurl}` : `${SITEURL}/build/assets/images/svgs/file.svg`}"
                            style="
                            width: 100%;
                            max-height: 55px;
                            border-radius: 5px;
                            ${uploadedFilename.toLowerCase().endsWith(".jpg") || uploadedFilename.toLowerCase().endsWith(".png") ? '' : 'height: 65px;'}"
                        >
                        <button class="btn-danger rounded-circle imageRemoveClick">
                            <i class="fe fe-x fs-12"></i>
                        </button>
                    `
                    // For the Image Remove Click
                    imageDiv.querySelector(".imageRemoveClick").onclick = (ele)=>{
                        let fileImgElement = ele.currentTarget.closest(".file-img");
                        let data ={
                            filename : uploadedFilename,
                        }

                        $.ajax({
                            type: "post",
                            url: '{{route('admin.removeChatImage')}}',
                            data: data,
                            success: function (data) {
                                // To remove the Image
                                if (fileImgElement) {
                                    fileImgElement.remove();
                                }
                            },
                            error: function (data) {
                                console.log('Error:', data);
                            }
                        });
                    }
                    // TO remove the uploading indication
                    document.querySelector("#uploadingIndication").remove()
                    document.querySelector(".image-uploaded").appendChild(imageDiv)
                    document.querySelector("#agentSendMessage").classList.remove('disabled')
                    document.querySelector("#agentSendMessage").removeAttribute('disabled')
                    document.querySelector("#auto-expand").focus()
                })
                .catch(error => {
                    console.error('Error uploading file:', error);
                });
            }else{
                toastr.error(ThereIsError.errorMessage)
            }

        })
    }

    // For the Customer Message Component
    let customerMessage = (data)=>{
        let custLi = document.createElement("li");
        custLi.className = "chat-item-start"
        if (data.messageId) {
            custLi.setAttribute("messageid", data.messageId)
        }
        custLi.innerHTML = `
            <div class="chat-list-inner">
                <div class="chat-user-profile">
                    <span class="avatar avatar-md brround" style="${data.color ? 'background-color: '+data.color : document.querySelector(`.checkforactive[data-id='${data.livechat_cust_id}'] #new-chat-user-bg`)?.getAttribute('style')}"> <span class="new-chat-user-letter">${data.livechat_username.slice(0,1).toUpperCase()}</span>
                    </span>
                </div>
                <div class="ms-3">
                    <span class="chatting-user-info">
                        <span class="chatnameperson">${data.livechat_username}</span>
                        <span class="msg-sent-time">${formatTime(data.created_at)}</span>
                        ${(texttospeachenabled == 'on' || texttranslateenabled == 'on') && (data.message_type != "image" && data.message_type != "audio") ?
                            `<a aria-label="anchor" href="javascript:void(0);" data-bs-toggle="dropdown" aria-expanded="false" class='float-end msg-send-dropdown'>
                                <i class="fe fe-more-vertical fs-18"></i>
                            </a>
                            <ul class="dropdown-menu">
                                ${texttospeachenabled == 'on' ?
                                    `<li>
                                        <a aria-label="anchor" class="dropdown-item" href="javascript:void(0);" onclick="texttospeachbtn()">
                                            <i class="ri-volume-up-fill align-middle me-2 fs-17 text-muted chat-info-optionicon d-inline-block"></i>{{ lang('Text To Speach') }}
                                        </a>
                                    </li>` : ''}
                                ${texttranslateenabled == 'on' ?
                                    `<li>
                                        <a aria-label="anchor" class="dropdown-item" href="javascript:void(0);" onclick="langtranslatebtn()">
                                            <i class="ri-volume-up-fill align-middle me-2 fs-17 text-muted chat-info-optionicon d-inline-block"></i>{{ lang('Language Translate') }}
                                        </a>
                                    </li>` : ''}
                            </ul>`
                            : ''
                        }
                    </span>
                    <div class="main-chat-msg">
                        ${data.messageDeleted == '1' ? '<div style="white-space: pre-line;background: #f4f6fb;color: #aaa;padding: 5px;font-style: italic;" class="text-start"><p class="mb-0 text-break"><i class="bx bx-block leading-none "></i>{{ lang('This message was deleted') }}</p></div>'
                        :
                        data.message_type == "image" ? `
                            <div onclick="AllFileViewer(this)" imageSrc="${data.message}" class="mt-2 ${data.message.toLowerCase().endsWith(".jpg") || data.message.toLowerCase().endsWith(".png") ? 'imageMessageLiveChat' : ''}" style="
                                background-image: url('${data.message.toLowerCase().endsWith(".jpg") || data.message.toLowerCase().endsWith(".png") ? data.message : `${SITEURL}/build/assets/images/svgs/file.svg`}');
                                background-size: cover;
                                width: ${data.message.toLowerCase().endsWith(".jpg") || data.message.toLowerCase().endsWith(".png") ?'10rem' :'8rem'};
                                aspect-ratio: 1;
                                background-repeat: no-repeat;
                                background-color: transparent;
                                background-position: center;
                            ">
                            </div>
                        ` : data.message_type == "audio" ? `<audio controls="" src="${data.message}"></audio>` : `<div style="white-space: pre-line;" class="text-start"><p class="mb-0 text-break" >${data.message}</p></div>`
                        }

                    </div>
                </div>
            </div>
        `
        return custLi
    }

    // To viewe the Pdf Files
    let AllFileViewer = (ele)=>{
        window.open(ele.getAttribute("imagesrc"))
    }

    // For the Agent Message Component
    let AgentMessage = (data)=>{
        let agentLi = document.createElement("li");
        agentLi.className = "chat-item-start"
        if(data.messageId){
            agentLi.setAttribute("messageid", data.messageId)
        }
        let statusChecker;
        if (data.status == 'seen') {
            statusChecker = '<span class="chat-read-mark align-middle d-inline-flex"><i class="ri-check-double-line"></i></span>';
        } else if (data.status == 'delivered') {
            statusChecker = '<span class="chat-read-icon align-middle d-inline-flex"><i class="ri-check-double-line"></i></span>'
        } else {
            statusChecker = '<span class="chat-read-icon align-middle d-inline-flex"><i class="ri-check-fill"></i></span>'
        }
        agentLi.innerHTML = `
                <div class="chat-list-inner">
                    <div class="chat-user-profile">
                        <span class="avatar avatar-md brround" style="background-image: url(${data.profileurl})">
                        </span>
                    </div>
                    <div class="ms-3">
                        <span class="chatting-user-info">
                            ${data.livechat_username.replace(autoUserInfo.name,'You')}
                            <span class="msg-sent-time">
                                ${formatTime(data.created_at)}
                                ${statusChecker}
                            </span>
                            ${(texttospeachenabled == 'on' || texttranslateenabled == 'on') && (data.message_type != "image" && data.message_type != "audio") ?
                                `<a aria-label="anchor" href="javascript:void(0);" data-bs-toggle="dropdown" aria-expanded="false" class='float-end msg-send-dropdown'>
                                    <i class="fe fe-more-vertical fs-18"></i>
                                </a>
                                <ul class="dropdown-menu">
                                    ${texttospeachenabled == 'on' ?
                                        `<li>
                                            <a aria-label="anchor" class="dropdown-item" href="javascript:void(0);" onclick="texttospeachbtn()">
                                                <i class="ri-volume-up-fill align-middle me-2 fs-17 text-muted chat-info-optionicon d-inline-block"></i>{{ lang('Text To Speach') }}
                                            </a>
                                        </li>` : ''}
                                    ${texttranslateenabled == 'on' ?
                                        `<li>
                                            <a aria-label="anchor" class="dropdown-item" href="javascript:void(0);" onclick="langtranslatebtn()">
                                                <i class="ri-volume-up-fill align-middle me-2 fs-17 text-muted chat-info-optionicon d-inline-block"></i>{{ lang('Language Translate') }}
                                            </a>
                                        </li>` : ''}
                                </ul>`
                                : ''
                            }
                        </span>
                        <div class="main-chat-msg">
                            ${data.message_type == "image" ? `
                            <div onclick="AllFileViewer(this)" imageSrc="${data.message}" class="mt-2 ${data.message.toLowerCase().endsWith(".jpg") || data.message.toLowerCase().endsWith(".png") ? 'imageMessageLiveChat' : ''}" style="
                                background-image: url('${data.message.toLowerCase().endsWith(".jpg") || data.message.toLowerCase().endsWith(".png") ? data.message : `${SITEURL}/build/assets/images/svgs/file.svg`}');
                                background-size: cover;
                                width: ${data.message.toLowerCase().endsWith(".jpg") || data.message.toLowerCase().endsWith(".png") ?'10rem' :'8rem'};
                                aspect-ratio: 1;
                                background-repeat: no-repeat;
                                background-color: transparent;
                                background-position: center;
                            ">
                            </div>
                            ` : data.message_type == "audio" ? `<audio controls="" src="${data.message}"></audio>` : `<div style="white-space: pre-line;" class="text-start"><p class="mb-0 text-break" >${data.message}</p></div>`
                            }
                        </div>
                    </div>
                </div>
        `
        return agentLi
    }

    // For The Comment Component
    let CommentMessage = (data)=>{
        let agentLi = document.createElement("li");
        agentLi.className = "chat-join-notify"
        agentLi.innerHTML = `<span>${data.message.replace(autoUserInfo.name,'You')} ${formatTime(data.created_at)}</span>`
        return agentLi
    }

    let FeedbackComment = (data)=>{
        data = JSON.parse(data.message)
        let agentLi = document.createElement("li");
        agentLi.className = "chat-join-notify"
        agentLi.innerHTML = `
        <span>Your chat has been rated ${data.starRating} out of 5 by the customer</span>
        `
        return agentLi
    }

    let savedData
    let hasTriggered = false;

    let addEmail = (event,id, email=null) => {
        let newField = document.createElement('input');
        newField.className = 'form-control';
        newField.value = email;
        newField.setAttribute('placeholder', '{{ lang('Enter New Email') }}');
        event.parentNode.replaceChild(newField, event);
        newField.focus();
        newField.onkeydown = async (e) => {
            if (e.key === 'Enter' && !hasTriggered) {
                hasTriggered = true;
                savedData = await saveEmail(newField.value, id);
                if (savedData?.error?.email) {
                    document.getElementById('emailErrors').innerHTML = savedData.error.email[0]
                    hasTriggered = false;
                } else if (savedData.success) {
                    let emailField = document.createElement('span');
                    emailField.innerHTML = newField.value;
                    newField.parentNode.replaceChild(emailField, newField);
                    customerData.email = newField.value;
                    hasTriggered = false;
                    emailField.onclick = (e) => {
                        addEmail(e.target, id, newField.value)
                    }
                }
            }
        }
        // Save details on focus out
        newField.onblur = async (e) => {
            if (!hasTriggered) {
                hasTriggered = true;
                savedData = await saveEmail(newField.value, id);
                if (savedData?.error?.email) {
                    document.getElementById('emailErrors').innerHTML = savedData.error.email[0]
                    hasTriggered = false;
                } else if (savedData.success) {
                    let emailField = document.createElement('span');
                    emailField.innerHTML = newField.value;
                    customerData.email = newField.value;
                    newField.parentNode.replaceChild(emailField, newField);
                    hasTriggered = false;
                    emailField.onclick = (e) => {
                        addEmail(e.target, id, newField.value)
                    }
                }
            }
        }
    }

    let saveEmail = async (email, id) => {
        document.getElementById('emailErrors').innerHTML = '';

        const url = SITEURL+ '/admin/livachat/updateEmail/'+id;
        const postdata = JSON.stringify({email: email});
        let data = await fetch(url, {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
            },
            body: postdata
        }).then(response => response.json())

        return data
    };

    let pauseAudios = () => {
        const audios = document.querySelectorAll('audio');

        // Attach event listeners to each audio element
        audios.forEach(audio => {
            audio.addEventListener('play', () => {
                // Pause all other audio elements
                audios.forEach(otherAudio => {
                    if (otherAudio !== audio) {
                        otherAudio.pause();
                        otherAudio.currentTime = 0; // Reset to the start if required
                    }
                });
            });
        });
    }

    // SideBar and Online operators loop click
    function sideMenuOpenClickFunction(ele){
        document.querySelector("#main-chat-content").classList.add('is-loading')
        document.querySelector(".chat-footer").classList.add('d-none');

        // operators Click
        $.ajax({
            type: "get",
            url: SITEURL + `/livechat/singlecustdata/${ele.getAttribute("data-id")}`,
            data : {
                author : 'agent',
            },
            success: function (data) {
                let userconversation = data.livechatdata
                customerData = data.livechatcust

                // To remove the Font Bold
                if(ele.querySelector(".chat-msg") && (ele.querySelector(".chat-msg").classList.contains('font-weight-bold') || ele.querySelector(".unReadIndexNumber"))){
                    ele.querySelector(".chat-msg").classList.remove("font-weight-bold")
                }

                if(ele.querySelector(".unReadIndexNumber")){
                    ele.querySelector(".unReadIndexNumber").remove()
                    // To Change the Make as read to Mark as unread
                    if(ele.querySelector(".markAsUnreadBtn") && ele.querySelector(".markAsUnreadBtn").innerText == 'Mark As Read'){
                        ele.querySelector('.markAsUnreadBtn').href = ele.querySelector('.markAsUnreadBtn').href.replace("markasread","markasunread")
                        ele.querySelector('.markAsUnreadBtn').innerHTML = `<i class="ri-chat-check-line align-middle me-2 fs-18"></i> Mark As Unread`
                    }
                }

                let mainChatContent = document.querySelector("#main-chat-content")
                mainChatContent.classList.remove("d-none")
                document.querySelector("#main-chat-content .no-articles").classList.add('d-none')
                if(document.querySelector("#operator-conversation")){
                    document.querySelector("#operator-conversation").remove()
                }
                if(document.querySelector("#operator-conversation-Info")){
                    document.querySelector("#operator-conversation-Info").remove()
                }

                // For thr messages conversation
                let conversation = document.createElement("ul");
                conversation.className = "list-unstyled chat-content overflow-auto"
                conversation.id = "operator-conversation"


                // For the Chat data
                function formatDateString(inputDateStr) {
                    const jsDate = new Date(inputDateStr);

                    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
                    }
                }
                conversation.setAttribute('operator-id',ele.getAttribute("data-id"))

                // For the Chat Flow Created Date
                let currentDate = null;

                // For the Chat Bot Messages
                if(!data.livechatcust.deletedMessage){
                    // For the Chat Flow Created Date
                    const messageDate = formatDateString(data.livechatcust.created_at);
                    conversation.innerHTML += `
                        <li class="chat-day-label">
                        <span>${messageDate}</span>
                        </li>
                    `;
                    currentDate = messageDate;
                    if(data.livechatcust.chat_flow_messages){
                        JSON.parse(data.livechatcust.chat_flow_messages).map((flowMes)=>{
                            let updatedFlowMes = flowMes
                            updatedFlowMes.created_at = data.livechatcust.created_at
                            updatedFlowMes.status = "seen"
                            updatedFlowMes.color = data.livechatcust.profile_bg_color
                            if(flowMes.authMessage == "agent"){
                                updatedFlowMes.livechat_username = flowMes?.username ? flowMes?.username : "chatBot";
                                conversation.appendChild(AgentMessage(updatedFlowMes))
                            }else{
                                updatedFlowMes.livechat_username = data.livechatcust.username
                                conversation.appendChild(customerMessage(updatedFlowMes))
                            }
                        })
                    }
                }

                // For the Agent Messages
                if(userconversation){
                    userconversation.map((chatdata)=>{
                    const messageDate = formatDateString(chatdata.created_at);
                    if (messageDate !== currentDate) {
                        conversation.innerHTML += `
                        <li class="chat-day-label">
                        <span>${messageDate}</span>
                        </li>
                        `;
                        currentDate = messageDate;
                    }
                    // For the Agent Messages
                    if(chatdata.livechat_cust_id && chatdata.status != 'comment' && chatdata.message_type != "feedBack"){
                        conversation.appendChild(customerMessage(chatdata))
                    }else{
                        if(chatdata.status != 'comment' && chatdata.message_type != "feedBack"){
                            conversation.appendChild(AgentMessage(chatdata))
                        }
                        if(chatdata.status == 'comment' && chatdata.message_type != "feedBack"){
                            conversation.appendChild(CommentMessage(chatdata))
                        }
                        if(chatdata.message_type == "feedBack"){
                            conversation.appendChild(FeedbackComment(chatdata))
                        }
                        }

                    })
                }

                // For the receiver Info
                let receiverInfo = document.createElement("div");
                receiverInfo.className = "d-flex align-items-center chat-conversation-Info border-bottom flex-wrap"
                receiverInfo.id = "operator-conversation-Info"
                receiverInfo.setAttribute('data-id',ele.getAttribute("data-id"))
                receiverInfo.innerHTML =`
                    <div class="me-2 lh-1">
                    <span class="avatar avatar-md brround" style="${document.querySelector(`.checkforactive[data-id='${customerData.id}'] #new-chat-user-bg`)?.getAttribute('style')}">
                        <span class="new-chat-user-letter">${customerData.username.slice(0,1).toUpperCase()}</span>

                        ${customerData.userType == 'livechat' ? `${customerData.liveChatCustomerOnlineUsers.split(',').includes(ele.getAttribute("data-id")) ?
                        '<span class="avatar-status bg-green"></span>'
                        :
                        '<span class="avatar-status"></span>'}` : ''}
                    </span>
                    </div>
                    <div class="flex-fill">
                    <p class="mb-0 fw-semibold fs-14">
                    <a href="javascript:void(0);" class="chatnameperson responsive-userinfo-open">${customerData.username}</a>
                    ${customerData.livechatTickets ? `<a class="badge badge-md bg-primary-transparent" href='{{route('admin.livechatTickets')}}?id=${customerData.gustId}'>${customerData.livechatTickets} Tickets Created</a>` : ``}
                    </p>

                    ${customerData.userType == 'livechat' ? `${customerData.liveChatCustomerOnlineUsers.split(',').includes(ele.getAttribute("data-id")) ? '<p class="text-green mb-0 chatpersonstatus">online</p>' : '<p class="text-muted mb-0 chatpersonstatus">offline</p>'}` : ''}
                    </div>
                    <div class="d-flex flex-wrap rightIcons">
                    <div class="dropdown ms-2 ">
                    <button aria-label="button" class="btn btn-icon btn-outline-light my-1 btn-wave waves-light waves-effect waves-light" type="button" data-bs-toggle="dropdown" aria-expanded="false">
                    <i class="ri-more-2-fill"></i>
                    </button>
                    <ul class="dropdown-menu">
                        ${ele.querySelector(".dropdown-menu").innerHTML}
                    </ul>
                    </div>

                    <button aria-label="button" class="btn btn-icon btn-outline-light my-1 btn-wave waves-light waves-effect waves-light responsive-userinfo-open ms-2" type="button" aria-expanded="false">
                    <i class="ri-shield-user-line"></i>
                    </button>
                    <button aria-label="button" type="button" class="btn btn-icon btn-outline-light my-1 ms-2 responsive-chat-close"> <i class="ri-close-line"></i> </button>
                    </div>
                `

                mainChatContent.appendChild(receiverInfo)
                mainChatContent.appendChild(conversation)

                // To remove the select option in the three dots click
                document.querySelector("#main-chat-content .conversationbarclose").classList.add('d-none');

                // To Scroll Down the Conversation
                document.querySelector("#operator-conversation").scrollBy(0, document.querySelector("#operator-conversation").scrollHeight)

                // Set the sidebar active
                localStorage.setItem("livechatSolvedCustomer",ele.getAttribute("data-id"))
                document.querySelectorAll(".checkforactive").forEach((lielement)=>{
                        lielement.classList.remove("active")
                        if(lielement.getAttribute("data-id") == ele.getAttribute("data-id")){
                            lielement.classList.add("active")
                        }
                })

                let chatUserDetails = document.querySelector("#chat-user-details");
                chatUserDetails.classList.remove("d-none");

                // For the Side bar client Info
                if (document.querySelector("#chat-client-info")) {
                    document.querySelector("#chat-client-info").remove();
                }

                let chatUserDetailsUl = document.createElement("ul");
                chatUserDetailsUl.className = "list-unstyled chat-client-info";
                chatUserDetailsUl.id = "chat-client-info";
                chatUserDetailsUl.innerHTML = `
                    <li>
                        <div class="d-flex gap-2 align-items-start text-break"><i class="${customerData.userType == 'livechat' ? 'ri-chat-3-line' : (customerData.userType == 'WhatsApp' ? 'ri-whatsapp-line' : 'ri-instagram-line')} font-weight-semibold flex-shrink-0 lh-1 align-middle icon-style1"></i>${customerData.userType == 'livechat' ? '{{ lang('Livechat') }}' : (customerData.userType == 'WhatsApp' ? '{{ lang('WhatsApp') }}' : '{{ lang('Instagram') }}')}</div>
                    </li>
                    <li>
                        <div class="d-flex gap-2 align-items-start text-break"><i class="ri-user-line font-weight-semibold flex-shrink-0 lh-1 align-middle icon-style1"></i>${customerData.username}</div>
                    </li>
                    ${customerData.email ? `
                        <li>
                            <div class="d-flex gap-2 align-items-start text-break"><i class="ri-mail-line font-weight-semibold flex-shrink-0 lh-1 align-middle icon-style1"></i><span>${customerData.email}</span></div>
                            <span id="emailErrors" class="text-danger"></span>
                        </li>
                    ` : `
                        <li>
                            <div class="d-flex gap-2 align-items-start text-break"><i class="ri-mail-line font-weight-semibold flex-shrink-0 lh-1 align-middle icon-style1"></i><a href="javascript:void(0)" onclick="addEmail(this,${customerData.id})">{{ lang('Add Email') }}</a></div>
                            <span id="emailErrors" class="text-danger"></span>
                        </li>
                    ` }
                    ${customerData.name ? `
                        <li>
                            <div class="d-flex gap-2 align-items-start text-break"><i class="ri-mail-line font-weight-semibold flex-shrink-0 lh-1 align-middle icon-style1"></i>${customerData.name}</div>
                        </li>
                    ` : '' }
                    ${customerData.mobile_number ? `
                        <li>
                            <div class="d-flex gap-2 align-items-start text-break"><i class="ri-phone-line font-weight-semibold flex-shrink-0 lh-1 align-middle icon-style1"></i>${customerData.mobile_number}</div>
                        </li>
                    ` : ''}
                    ${customerData.browser_info ? `
                        <li>
                            <div class="d-flex gap-2 align-items-start text-break"><i class="ri-computer-line font-weight-semibold flex-shrink-0 lh-1 align-middle icon-style1"></i>${customerData.browser_info}</div>
                        </li>
                    ` : ''}
                    ${customerData.login_ip ? `
                        <li>
                            <div class="d-flex gap-2 align-items-start text-break"><i class="ri-map-pin-range-line font-weight-semibold flex-shrink-0 lh-1 align-middle icon-style1"></i>${customerData.login_ip}</div>
                        </li>
                    ` : ''}
                    ${customerData.Login_url ? `
                        <li>
                            <div class="d-flex gap-2 align-items-start text-break"><i class="ri-earth-line font-weight-semibold flex-shrink-0 lh-1 align-middle icon-style1"></i>${customerData.Login_url}</div>
                        </li>
                    ` : ''}
                    ${(customerData.city && customerData.state && customerData.country) ? `
                        <li>
                            <div class="d-flex gap-2 align-items-start text-break"><i class="ri-map-pin-line font-weight-semibold flex-shrink-0 lh-1 align-middle icon-style1"></i>
                                ${customerData.city ? customerData.city + "," : ''} ${customerData.state ? customerData.state + "," : ''} ${customerData.country}
                            </div>
                        </li>
                    ` : ''}
                `;

                chatUserDetails.querySelector(".card-body").appendChild(chatUserDetailsUl);

                // File permission Check Btn
                if(document.querySelector('#fileUploadPermission') && customerData.userType == 'livechat'){
                    document.querySelector('#fileUploadPermission').closest('.card').classList.remove('d-none')
                    document.querySelector('#fileUploadPermission').setAttribute("data-id",ele.getAttribute("data-id"))
                    if(customerData.file_upload_permission){
                        document.querySelector('#fileUploadPermission').checked = true
                    }else{
                        document.querySelector('#fileUploadPermission').checked = false
                    }
                } else {
                    document.querySelector('#fileUploadPermission').closest('.card').classList.add('d-none')
                }

                if(document.querySelector('.voiceRecorderButton')){
                    if ((customerData.userType == 'WhatsApp' || customerData.userType == 'Instagram')) {
                        document.querySelector('.voiceRecorderButton').classList.add('d-none')
                    } else {
                        document.querySelector('.voiceRecorderButton').classList.remove('d-none')
                    }
                }

                // When User try to Delete the chat to ask the are you sure alert
                document.querySelectorAll("[deleteroutelink]").forEach((ele)=>{
                    ele.onclick = ()=>{
                        swal({
                            title: `{{lang('Are you sure you want to continue?', 'alerts')}}`,
                            text: "{{lang('The conversation will be deleted', 'alerts')}}",
                            icon: "warning",
                            buttons: true,
                            dangerMode: true,
                        }).then((res)=>{
                            if(res){
                                $.ajax({
                                        type: "get",
                                        url: ele.getAttribute("deleteroutelink"),
                                        success: function (data) {
                                            localStorage.removeItem('livechatSolvedCustomer');
                                            toastr.success("Chat Deleted");

                                            var activecustId = document.querySelector(`.checkforactive.active`)?.getAttribute("data-id");
                                            var deletecustId = ele.closest('.checkforactive')?.getAttribute("data-id") ?? ele.closest('#operator-conversation-Info')?.getAttribute("data-id");
                                            document.querySelector(`.checkforactive[data-id="${deletecustId}"]`)?.remove()
                                            if(activecustId == deletecustId){
                                                document.querySelector(`#operator-conversation-Info[data-id="${deletecustId}"]`)?.remove()
                                                document.querySelector(`#operator-conversation[operator-id="${deletecustId}"]`)?.remove()
                                                document.querySelector(".engageConversation")?.classList.add("d-none")
                                                document.querySelector(".chat-footer")?.classList.add("d-none")
                                                if(document.querySelector("#chat-msg-scroll li")?.getAttribute("data-id")){
                                                    sideMenuOpenClickFunction(document.querySelector(`.checkforactive[data-id="${document.querySelector("#chat-msg-scroll li")?.getAttribute("data-id")}"]`))
                                                }else{
                                                    localStorage.removeItem('livechatSolvedCustomer');

                                                    let emptyconver = document.createElement("div");
                                                    emptyconver.className = "text-center mt-5 px-2 py-4 bg-warning-transparent text-default mx-auto w-90 rounded-2";
                                                    emptyconver.innerHTML = `<span>{{ lang('As of now, there are no chat discussions in progress') }}</span>`;
                                                    document.querySelector("#chat-msg-scroll").append(emptyconver);
                                                    document.querySelector(".no-articles").classList.remove("d-none");
                                                }
                                            }
                                        },
                                        error: function (data) {
                                            console.log('Error:', data);
                                        }
                                    })
                            }
                        })
                    }
                })

                if (document.querySelector("#chat-btn")) {
                    document.querySelector("#chat-btn").click();
                }

                responsivechat();
                if (document.querySelector('.ri-mail-line.font-weight-semibold.flex-shrink-0.lh-1.align-middle.icon-style1').parentElement.querySelector('span')) {
                    document.querySelector('.ri-mail-line.font-weight-semibold.flex-shrink-0.lh-1.align-middle.icon-style1').parentElement.querySelector('span').onclick = (e) => {
                        addEmail(e.target, customerData.id, e.target.innerHTML);
                    }
                }

                // remove loading
                setTimeout(() => {
                    document.querySelector("#main-chat-content").classList.remove("is-loading")

                    // To Prevent the engage Conversation Btn
                    let engagedUserExist = JSON.parse(data.livechatcust.engage_conversation);
                    if(engagedUserExist.some(item => item.id == autoID)){
                        document.querySelector('.textareaDiv')?.classList.remove('d-none')
                        document.querySelector('.engageConversation')?.classList.add('d-none')
                    }else{
                        document.querySelector('.textareaDiv')?.classList.add('d-none')
                        document.querySelector('.engageConversation')?.classList.remove('d-none')
                    }

                    // Message conversation logic
                    let chatFooter = document.querySelector(".chat-footer")
                    chatFooter.classList.remove("d-none")
                }, 100);

                pauseAudios();
            },
            error: function (data) {
                console.log('Error:', data);
            }
        })
    }

    // For the Side Bar Click
    function slectTicket(event, id) {
        let target = event.currentTarget;
        if(target){
            let li = target.closest('li.checkforactive');
            let input = li.querySelector("[name='customer_checkbox[]']");
            let chatUserTabList = document.querySelector('.chat-user-tab-list');
            event.stopPropagation();
            if(input){
                if(input.checked){
                    input.checked = false;
                    target.lastChild.textContent = "Select";
                }else{
                    input.checked = true;
                    target.lastChild.textContent = "Deselect";
                }

                var checkedCheckboxes = $('.checkall:checked').length;
                let customCheckAll = document.querySelector('#customCheckAll');
                if ($('.checkall:checked').length === 0) {
                    customCheckAll.nextElementSibling.textContent = ""
                    chatUserTabList.classList.remove('show-checks');
                    $('#massdelete').hide();
                    $('#selectallbutton').hide();
                    $('.search-container').show();
                } else {
                    customCheckAll.nextElementSibling.textContent = checkedCheckboxes + ' '  + "Selected"
                    chatUserTabList.classList.add('show-checks');
                    $('#massdelete').show();
                    $('#selectallbutton').show();
                    $('.search-container').hide();
                }
            }
        }
        updateCustomCheckAll();
    }

    // For the Side Bar Click
    document.querySelectorAll(".checkforactive").forEach((ele)=>{
        ele.onclick = ()=>{
            document.querySelectorAll('.checkforactive.moveout')?.forEach(element => {
                element.classList.add('removemovedout')
            });
            setTimeout(() => {
                if(document.querySelector('.checkforactive.moveout.removemovedout')){
                    var activeuser = document.querySelector('.checkforactive.moveout.removemovedout.active');
                    document.querySelectorAll('.checkforactive.moveout.removemovedout').forEach(element => {
                        element.remove();
                    });
                    if(activeuser){
                        localStorage.removeItem('livechatSolvedCustomer');

                        if(document.querySelector("#chat-msg-scroll li")?.getAttribute("data-id")){
                            sideMenuOpenClickFunction(document.querySelector(`.checkforactive[data-id="${document.querySelector("#chat-msg-scroll li")?.getAttribute("data-id")}"]`))
                        }else{

                            if(!document.querySelector('.text-center.mt-5.p-1.bg-warning-transparent.text-default')){
                                let emptyconver = document.createElement("div");
                                emptyconver.className = "text-center mt-5 px-2 py-4 bg-warning-transparent text-default mx-auto w-90 rounded-2";
                                emptyconver.innerHTML = `<span>{{ lang('As of now, there are no chat discussions in progress') }}</span>`;
                                document.querySelector("#chat-msg-scroll").append(emptyconver);
                                document.querySelector(".no-articles").classList.remove("d-none");
                            }
                        }
                    }
                }
            }, 1500);
            sideMenuOpenClickFunction(ele)
        }
    })

    // Prevent the li loop click from the dropdown
    document.querySelectorAll('#chat-msg-scroll .chat-actions').forEach((ele)=>{
        ele.addEventListener('click', function (event) {
            event.stopPropagation();
        })

        // markAsUnreadBtn
        if(ele.querySelector('.markAsUnreadBtn')){
            ele.querySelector('.markAsUnreadBtn').addEventListener('click', function (event) {
                event.stopPropagation();
                if(localStorage.livechatSolvedCustomer == ele.closest('.checkforactive').getAttribute('data-group-uniq') || localStorage.livechatSolvedCustomer == ele.closest('.checkforactive').getAttribute('data-id')){
                    localStorage.removeItem('livechatSolvedCustomer')
                }
            })
        }

        // Delete Btn
        if(ele.querySelector('[href*="conversationdelete"]')){
            ele.querySelector('[href*="conversationdelete"]').addEventListener('click', function (event) {
                event.stopPropagation();
                if(localStorage.livechatSolvedCustomer == ele.closest('.checkforactive').getAttribute('data-group-uniq') || localStorage.livechatSolvedCustomer == ele.closest('.checkforactive').getAttribute('data-id')){
                    localStorage.removeItem('livechatSolvedCustomer')
                }
            })
        }
    })

    // Active liveChat Message
    let solvedchatcustVal = localStorage.livechatSolvedCustomer ?? document.querySelector("#chat-msg-scroll li")?.getAttribute("data-id");
    if(solvedchatcustVal){
        if(document.querySelector(`.checkforactive[data-id="${solvedchatcustVal}"]`)){
            sideMenuOpenClickFunction(document.querySelector(`.checkforactive[data-id="${solvedchatcustVal}"]`))
        }else{
            if(document.querySelector("#chat-msg-scroll li")?.getAttribute("data-id")){
                sideMenuOpenClickFunction(document.querySelector(`.checkforactive[data-id="${document.querySelector("#chat-msg-scroll li")?.getAttribute("data-id")}"]`))
            }else{
                document.querySelector(".no-articles").classList.remove("d-none");
            }
        }
    }

    if(!solvedchatcustVal || '{{ $emptyConversation }}' == 1){
        document.querySelector(".no-articles").classList.remove("d-none");
    }

    function sanitizeHTML(input) {
        const map = {
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#039;',
            '/': '&#x2F;',  // For forward slash
            '`': '&#x60;',  // Backtick
            '=': '&#x3D;'   // Equals
        };

        return input.replace(/[&<>"'/`=]/g, function (char) {
            return map[char];
        });
    }

    const now = new Date();
    const hours = now.getHours();
    const minutes = now.getMinutes();
    const period = hours >= 12 ? "PM" : "AM";

    const formattedTime = `${((hours + 11) % 12) + 1}:${minutes}${period}`;
    const autoUser = '{{Auth::user()->name}}'

    // Send Message button
    document.querySelector("#agentSendMessage").onclick = ()=>{
        afterMessageSend = false
        let operatorConversation = document.querySelector("#operator-conversation")

        if (document.querySelector("#auto-expand").querySelector("#suggestionText")) {
            document.querySelector("#auto-expand").querySelector("#suggestionText").remove();
        }

        if (document.querySelector("#auto-expand").querySelector(".misspelled")) {
            document.querySelector("#auto-expand").querySelectorAll(".misspelled").forEach((element) => {
                // Create a text node with the innerText of the current element
                const textNode = document.createTextNode(element.innerText);
                // Replace the misspelled element with the text node
                element.parentNode.replaceChild(textNode, element);
            });
        }

        // Agent Message Send
        let PresentTimeFormatted = `${((new Date().getHours() + 11) % 12) + 1}:${new Date().getMinutes()}${new Date().getHours() >= 12 ? "PM" : "AM"}`;
        let sendingData ={
            message : sanitizeHTML(document.querySelector("#auto-expand").textContent),
            cust_id :customerData.id,
            customerId: customerData.id,
            userType: customerData.userType
        }

        if(document.querySelector("#auto-expand").textContent.trim()){
            $.ajax({
                type: "post",
                url: SITEURL + "/livechat/broadcast-message",
                data: sendingData,
                success: function (data) {
                    $('#cannedResponses').select2('destroy');
                    document.querySelector("#cannedResponses").selectedIndex = null
                    $('#cannedResponses').select2({
                        placeholder: {
                            id: '',
                            text: 'Canned Responses'
                        },
                        // allowClear: true
                    });
                    // New Message will add to sidebar
                    const existingLi = Array.from(document.querySelectorAll("#chat-msg-scroll>li")).find(li => li.getAttribute('data-id') == document.querySelector("#operator-conversation").getAttribute('operator-id'));
                    if(!existingLi){
                        const newMessageLiElement = document.createElement("li");
                        newMessageLiElement.className = "checkforactive active"
                        newMessageLiElement.setAttribute("data-id",document.querySelector("#operator-conversation").getAttribute('operator-id'))
                        newMessageLiElement.innerHTML = `
                            <div class="d-flex align-items-center">
                                <div class="me-2 lh-1">
                                    <span class="avatar brround" style="${document.querySelector("#operator-conversation-Info .avatar-md").style.cssText.replace('"',"")}"></span>
                                    </div>
                                <div class="flex-fill">
                                    <div class="mb-0 d-flex align-items-center justify-content-between">
                                        <div class="font-weight-semibold">
                                            <a href="javascript:void(0);">${document.querySelector("#main-chat-content .responsive-userinfo-open").innerText}</a>

                                        </div>
                                        <div class="float-end text-muted fw-normal fs-12 chat-time">${new Date().toLocaleTimeString()}</div>
                                        <div class="dropdown chat-actions lh-1">
                                            <a aria-label="anchor" href="javascript:void(0);" data-bs-toggle="dropdown" aria-expanded="false">
                                                <i class="fe fe-more-vertical fs-18"></i>
                                            </a>
                                            <ul class="dropdown-menu">
                                                <li><a class="dropdown-item" href="operators/conversationdelete/${data.MessageSent.unique_id}"><i class="ri-chat-delete-line align-middle me-2 fs-18"></i>Delete</a></li>
                                            </ul>
                                        </div>
                                    </div>
                                    <div class="d-flex align-items-center justify-content-between">
                                        <span class="chat-msg text-truncate fs-13 text-default">${data.MessageSent.message}</span>
                                        ${messageDeliveryStatus}
                                    </div>
                                </div>
                            </div>
                        `
                        newMessageLiElement.onclick = ()=>{
                            sideMenuOpenClickFunction(newMessageLiElement);
                        }
                        document.querySelector("#chat-msg-scroll").insertBefore(newMessageLiElement, document.querySelector("#chat-msg-scroll > li"));

                    }

                    let senderMessage = document.createElement("li");
                    senderMessage.className = "chat-item-start"
                    if (data?.messageId) {
                        senderMessage.setAttribute("messageid", data.messageId)
                    }
                    senderMessage.innerHTML = `
                        <div class="chat-list-inner">
                            <div class="chat-user-profile">
                                <span class="avatar avatar-md brround" style="background-image: url(${document.querySelector(".leading-none img").src})">
                                </span>
                            </div>
                            <div class="ms-3">
                                <span class="chatting-user-info">
                                    You
                                    <span class="msg-sent-time">
                                        ${PresentTimeFormatted}
                                        <span class="chat-read-icon align-middle d-inline-flex"><i class="ri-check-fill"></i></span>
                                    </span>
                                    ${texttospeachenabled == 'on' || texttranslateenabled == 'on' ?
                                        `<a aria-label="anchor" href="javascript:void(0);" data-bs-toggle="dropdown" aria-expanded="false" class='float-end msg-send-dropdown'>
                                            <i class="fe fe-more-vertical fs-18"></i>
                                        </a>
                                        <ul class="dropdown-menu">
                                            ${texttospeachenabled == 'on' ?
                                                `<li>
                                                    <a aria-label="anchor" class="dropdown-item" href="javascript:void(0);" onclick="texttospeachbtn()">
                                                        <i class="ri-volume-up-fill align-middle me-2 fs-17 text-muted chat-info-optionicon d-inline-block"></i>{{ lang('Text To Speach') }}
                                                    </a>
                                                </li>` : ''}
                                            ${texttranslateenabled == 'on' ?
                                                `<li>
                                                    <a aria-label="anchor" class="dropdown-item" href="javascript:void(0);" onclick="langtranslatebtn()">
                                                        <i class="ri-volume-up-fill align-middle me-2 fs-17 text-muted chat-info-optionicon d-inline-block"></i>{{ lang('Language Translate') }}
                                                    </a>
                                                </li>` : ''}
                                        </ul>`
                                        : ''
                                    }
                                </span>
                                <div class="main-chat-msg">
                                    <div style="white-space: pre-line;" class="text-start">
                                        <p class="mb-0 text-break">${sendingData.message}</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    `
                    if(operatorConversation.lastElementChild && operatorConversation.lastElementChild.id === "agentTyping") {
                        operatorConversation.insertBefore(senderMessage, operatorConversation.lastElementChild);
                    } else {
                        operatorConversation.appendChild(senderMessage);
                    }

                    // To Scroll Down the Conversation
                    document.querySelector("#operator-conversation").scrollBy(0, document.querySelector("#operator-conversation").scrollHeight)

                    textarea.style.height = '49px'

                    // After message sent show the message in the top
                    document.querySelectorAll("#chat-msg-scroll > li").forEach((operatorsChat)=>{
                        if(operatorsChat.getAttribute('data-id') == document.querySelector("#operator-conversation").getAttribute('operator-id')){
                            operatorsChat.querySelector(".chat-msg").classList.remove("font-weight-bold")
                            operatorsChat.querySelector(".chat-msg").innerHTML = sendingData.message.replace(/\n/g, ' ')
                            operatorsChat.querySelector(".chat-time").innerText = new Date().toLocaleTimeString()
                            if(operatorsChat.querySelector(".chat-msg").parentNode.querySelector('.d-inline-flex')){
                                operatorsChat.querySelector(".chat-msg").parentNode.querySelector('.d-inline-flex').remove()
                            }
                            if(document.querySelector("#messageStatusDiv")){
                                document.querySelector("#messageStatusDiv").remove()
                            }
                            // To remove the Make as unread button
                            if(operatorsChat.querySelector(".markAsUnreadBtn")){
                                operatorsChat.querySelector(".markAsUnreadBtn").parentNode.remove()
                            }
                            const messageStatus = document.createElement("div");
                            messageStatus.id = "messageStatusDiv"
                            // operatorsChat.querySelector(".chat-msg").parentNode.appendChild(messageStatus)
                            document.querySelector("#chat-msg-scroll").insertBefore(operatorsChat, document.querySelector("#chat-msg-scroll > li"));
                        }
                    })

                    // To Scroll Down the Conversation
                    operatorConversation.scrollBy(0, operatorConversation.scrollHeight)
                },
                error: function (error) {
                    if(error.responseJSON){
                        toastr.error("The message field cannot be null")
                    }
                }
            });
        }

        if (document.querySelector("#audio-player")) {

            var formData = new FormData();
            formData.append('chatFileUpload', audioBlob, 'recording.webm');

            fetch(SITEURL+`/livechat/live-chat-image-upload`, {
                method: 'POST',
                body: formData,
                headers: {
                    'X-CSRF-Token': '{{ csrf_token() }}',
                    'X-Requested-With': 'XMLHttpRequest',
                    'Accept': 'application/json, text/javascript, */*; q=0.01',
                },
            })
            .then(response => {
                return response.json()
            })
            .then(resdata => {

                let data ={
                    message : `${resdata.imageurl}`,
                    cust_id :customerData.id,
                    customerId: customerData.id,
                    messageType: "audio",
                    userType: customerData.userType
                }

                let audioMessage = document.createElement("li");
                audioMessage.className = "chat-item-start"
                audioMessage.innerHTML = `
                <div class="chat-list-inner">
                    <div class="chat-user-profile">
                        <span class="avatar avatar-md brround" style="background-image: url(${document.querySelector(".leading-none img").src})">
                        </span>
                    </div>
                    <div class="ms-3">
                        <span class="chatting-user-info">
                            {{ lang('You') }}
                            <span class="msg-sent-time">
                                ${PresentTimeFormatted}
                                <span class="chat-read-icon align-middle d-inline-flex"><i class="ri-check-fill"></i></span>
                            </span>
                        </span>
                        <div class="main-chat-msg">
                            <audio controls src="${data.message}"></audio>
                        </div>
                    </div>
                </div>
                `

                // To add The Image In the Chat
                if(operatorConversation.lastElementChild && operatorConversation.lastElementChild.id === "agentTyping") {
                    operatorConversation.insertBefore(audioMessage, operatorConversation.lastElementChild);
                } else {
                    operatorConversation.appendChild(audioMessage);
                }

                // To Scroll Down the Conversation
                document.querySelector("#operator-conversation").scrollBy(0, document.querySelector("#operator-conversation").scrollHeight)
                document.querySelector("#audio-player").parentElement.remove()

                $.ajax({
                    type: "post",
                    url: SITEURL + "/livechat/broadcast-message",
                    data: data,
                    success: function (data) {
                        // To remove the Added Images
                        document.querySelector('.image-uploaded').innerHTML = ""
                    },
                    error: function (data) {
                        console.log('Error:', data);
                    }
                });
                pauseAudios();

            })
            .catch(error => {
                console.error('Error:', error);
            });
        }

        // to slow the Image Upload Message
        let imageUploadTimeout = document.querySelector("#auto-expand").textContent ? 1000 : 0
        setTimeout(() => {
            // For the Image Upload
            if(document.querySelectorAll(".image-uploaded .file-img").length){
                document.querySelectorAll(".image-uploaded .file-img img").forEach((ele)=>{
                    let data ={
                        message : ele.getAttribute('imageSrc'),
                        cust_id :customerData.id,
                        customerId: customerData.id,
                        messageType: "image"
                    }

                    let imageMessage = document.createElement("li");
                    imageMessage.className = "chat-item-start"
                    imageMessage.innerHTML = `
                        <div class="chat-list-inner">
                            <div class="chat-user-profile">
                                <span class="avatar avatar-md brround" style="background-image: url(${document.querySelector(".leading-none img").src})">
                                </span>
                            </div>
                            <div class="ms-3">
                                <span class="chatting-user-info">
                                    You
                                    <span class="msg-sent-time">
                                        ${PresentTimeFormatted}
                                        <span class="chat-read-icon align-middle d-inline-flex"><i class="ri-check-fill"></i></span>
                                    </span>
                                </span>
                                <div class="main-chat-msg">
                                    <div onclick="AllFileViewer(this)" imagesrc="${data.message}" class="mt-2 ${data.message.toLowerCase().endsWith(".jpg") || data.message.toLowerCase().endsWith(".png") ? 'imageMessageLiveChat' : ''}" style="
                                            background-image: url('${data.message.toLowerCase().endsWith(".jpg") || data.message.toLowerCase().endsWith(".png") ? data.message : `${SITEURL}/build/assets/images/svgs/file.svg`}');
                                            background-size: cover;
                                            width: ${data.message.toLowerCase().endsWith(".jpg") || data.message.toLowerCase().endsWith(".png") ?'10rem' :'8rem'};
                                            aspect-ratio: 1;
                                            background-repeat: no-repeat;
                                            background-color: transparent;
                                            background-position: center;
                                            ">
                                    </div>
                                </div>
                            </div>
                        </div>
                    `

                    // To add the image Preview Onclick
                    if(imageMessage.querySelector(".imageMessageLiveChat")){
                        // To Open the Image Viewer
                        imageMessage.querySelector(".imageMessageLiveChat").onclick = (ele)=>{
                            document.querySelector(".liveChatImageViewer").classList.remove("d-none")
                            document.querySelector(".liveChatImageViewer img").src = ele.target.getAttribute("imagesrc")
                            document.querySelector(".liveChatImageViewer .liveChatImageClose").onclick = ()=>{
                                // To Close the Image Viewer
                                document.querySelector(".liveChatImageViewer").classList.add("d-none")
                            }
                        }
                    }

                    // To add The Image In the Chat
                    if(operatorConversation.lastElementChild && operatorConversation.lastElementChild.id === "agentTyping") {
                        operatorConversation.insertBefore(imageMessage, operatorConversation.lastElementChild);
                    } else {
                        operatorConversation.appendChild(imageMessage);
                    }

                    // To Scroll Down the Conversation
                    document.querySelector("#operator-conversation").scrollBy(0, document.querySelector("#operator-conversation").scrollHeight)

                    $.ajax({
                        type: "post",
                        url: SITEURL + "/livechat/broadcast-message",
                        data: data,
                        success: function (data) {
                            // To remove the Added Images
                            document.querySelector('.image-uploaded').innerHTML = ""
                        },
                        error: function (data) {
                            console.log('Error:', data);
                        }
                    });
                })
            }
        }, imageUploadTimeout);

        document.querySelector("#auto-expand").textContent = ''

        setTimeout(() => {
            afterMessageSend = true
        }, 500);
    }

    // Enter Message Send Function
    document.getElementById('auto-expand').addEventListener('keydown', function (event) {
        if (event.key === 'Enter' && !event.shiftKey) {
            event.preventDefault();
            // document.getElementById('agentSendMessage').click();
            if(!document.querySelector("#agentSendMessage").classList.contains("d-none")){
                document.getElementById('agentSendMessage').click();
            }

            if(!document.querySelector("#agentCreateTicket").classList.contains("d-none")){
                document.querySelector("#agentCreateTicket").click();
            }
        }
    });

    // Engage Conversation button click
    document.querySelector('.engageConversation button').onclick = ()=>{
        $('.engageConversation button').html('{{ lang("Joining") }} ... <i class="fa fa-spinner fa-spin"></i>');
        $('.engageConversation button').prop('disabled', true);
        let data ={
            users : JSON.stringify([autoUserInfo]),
            custId : document.querySelector("#operator-conversation").getAttribute('operator-id')
        }
        $.ajax({
            type: "post",
            url: '{{route('admin.engageConversation')}}',
            data: data,
            success: function (data) {
                document.querySelector('.textareaDiv').classList.remove('d-none');
                document.querySelector('.engageConversation').classList.add('d-none');
                document.querySelector('.checkforactive.active')?.classList.add('moveout');
                $('.engageConversation button').html('{{ lang("Join this conversation") }} <i class="ri-discuss-line ms-1"></i>');
                $('.engageConversation button').prop('disabled', false);
            },
            error: function (data) {
                console.log('Error:', data);
            }
        });
    }

    // To add the Chat Unq Id to the Assign modal
    document.querySelectorAll(".reAssignModalTrigger").forEach((ele)=>{
        ele.onclick = ()=>{
            var custId = ele.getAttribute('custId');
            var modalElement = document.getElementById('staticBackdrop');
            modalElement.setAttribute('custId', custId);
        }
    })

    // reassign Select Submit click
    $('#reassignSelectBtn').on('click', function () {
        var selectedValue = $('#reassignSelect').val();
        let data ={
                assignUser : selectedValue,
                custId : document.querySelector('#staticBackdrop').getAttribute("custId")
            }
        $.ajax({
            type: "post",
            url: '{{route('admin.conversationReassign')}}',
            data: data,
            success: function (data) {
                document.querySelector(`.checkforactive[data-id="${data.custId}"]`).remove()
                document.querySelector(`#operator-conversation-Info[data-id="${data.custId}"]`).remove()
                document.querySelector(`#operator-conversation[operator-id="${data.custId}"]`).remove()
                document.querySelector(".chat-footer").classList.add("d-none")
            },
            error: function (data) {
                console.log('Error:', data);
                if(data?.responseJSON?.message == "notselected"){
                    document.querySelector('#reassignSelectError').innerHTML = data.responseJSON.error;
                    toastr.error(data.responseJSON.error);
                }else{
                    toastr.error("please enter the valid data.");
                }
            }
        });
    });

    // Operator typing indaction
    var debounceTimeout2;
    var afterMessageSend = true

    document.querySelector("#auto-expand").oninput = (ele)=>{
        let agentSendMessageBtn = document.querySelector("#agentSendMessage")
        let agentCreateTicketBtn = document.querySelector("#agentCreateTicket")

        // For the message Send Btn Disabled and Enabled
        if(ele.target.textContent){
            agentSendMessageBtn.disabled = false
            agentSendMessageBtn.classList.remove('disabled')
        }else{
            if (!document.querySelector(".image-uploaded .file-img")) {
                agentSendMessageBtn.disabled = true
                agentSendMessageBtn.classList.add('disabled')
            }
        }

        let envatoId = true

        if(document.querySelector("#envato_id")){
            envatoId = document.querySelector("#envato_id").getAttribute("readonly") == 'readonly'
        }

        // To Remove the Disabled For The Ticket Create Btn
        if( document.querySelector("#livechatTicketSubject").value && ele.target.textContent && document.querySelector("#category").value && envatoId ){
            agentCreateTicketBtn.disabled = false
            agentCreateTicketBtn.classList.remove('disabled')
        }else{
            agentCreateTicketBtn.disabled = true
            agentCreateTicketBtn.classList.add('disabled')
        }

        clearTimeout(debounceTimeout2);
        debounceTimeout2 = setTimeout(function() {
            if(afterMessageSend){
                let data ={
                    message : null,
                    username : autoUserInfo.name,
                    id : autoID,
                    customerId : document.querySelector("#operator-conversation").getAttribute("operator-id"),
                    typingMessage : document.querySelector("#auto-expand").textContent,
                    agentInfo : JSON.stringify(autoUserInfo)
                }


                $.ajax({
                    type: "post",
                    url: SITEURL + "/livechat/broadcast-message-typing",
                    data: data,
                    success: function (data) {

                    },
                    error: function (data) {
                        console.log('Error:', data);
                    }
                });
            }
        }, 500);
    }


    function sanitizeMessage(message) {
        const tempElement = document.createElement('div');
        tempElement.innerHTML = message;
        let plainText = tempElement.textContent || tempElement.innerText || '';
        plainText = plainText.replace(/&nbsp;/g, ' ');
        return plainText;
    }

    var debounceTimeout;
    var debounceTimeout3;
    var debounceTimeout4;
    var pastMessage = ""

    Echo.channel('liveChat').listen('ChatMessageEvent',(socket)=>{

        if(socket && socket?.messageType == 'texttospeachsettingUpdated'){
            if(socket?.custdata.enabledtexttospeach == 'on' || socket?.custdata.enabledtextranslation == 'on'){
                document.querySelectorAll('.msg-sent-time').forEach((element) => {
                    const nextAnchor = element.nextElementSibling;
                    const nextDropdown = nextAnchor?.nextElementSibling;

                    if(nextAnchor?.classList.contains('msg-send-dropdown') && nextDropdown?.classList.contains('dropdown-menu')){
                        nextAnchor.remove();
                        nextDropdown.remove();
                    }

                    const dropdownHTML = `
                    <a aria-label="anchor" href="javascript:void(0);" data-bs-toggle="dropdown" aria-expanded="false" class='float-end msg-send-dropdown'>
                        <i class="fe fe-more-vertical fs-18"></i>
                    </a>
                    <ul class="dropdown-menu">
                        ${socket?.custdata.enabledtexttospeach == 'on' ?
                            `<li>
                                <a class="dropdown-item" onclick="texttospeachbtn()">
                                    <i class="ri-volume-up-fill align-middle me-2 fs-17 text-muted chat-info-optionicon d-inline-block"></i>{{ lang('Text To Speach') }}
                                </a>
                            </li>` : ''
                        }
                        ${socket?.custdata.enabledtextranslation == 'on' ?
                            `<li>
                                <a aria-label="anchor" class="dropdown-item" href="javascript:void(0);" onclick="langtranslatebtn()">
                                    <i class="ri-volume-up-fill align-middle me-2 fs-17 text-muted chat-info-optionicon d-inline-block"></i>{{ lang('Language Translate') }}
                                </a>
                            </li>` : ''
                        }
                    </ul>
                    `;

                    element.insertAdjacentHTML('afterend', dropdownHTML);
                });
            }else{
                document.querySelectorAll('.msg-send-dropdown').forEach((element)=>{
                    element.nextElementSibling.remove();
                    element.remove();
                })
            }
        }

        if(socket && socket?.messageType == 'agentToCustomerFilesettingUpdated'){
            if(socket?.custdata == 'on' || '{{ Auth::user()->getRoleNames()[0] }}' == 'superadmin'){
                document.getElementById('agentToCustFileSetUpdate').classList.remove('d-none')
            }else{
                document.getElementById('agentToCustFileSetUpdate').classList.add('d-none')
            }
        }

        // Conversation Messages
        let liveChatConversation = document.querySelector("#operator-conversation")

        // For Customer Online Update
        if(socket.customerId && socket.onlineStatusUpdate){
            if(socket.onlineStatusUpdate == 'offline'){
                document.querySelector(`#chat-msg-scroll [data-id='${socket.customerId}'] .avatar-status`)?.classList.remove("bg-green")
                if(document.querySelector(`#operator-conversation-Info[data-id="${socket.customerId}"] .chatpersonstatus`)){
                    document.querySelector(`#operator-conversation-Info[data-id="${socket.customerId}"] .chatpersonstatus`).innerText = "offline"
                    document.querySelector(`#operator-conversation-Info[data-id="${socket.customerId}"] .avatar-status`).classList.remove("bg-green")
                    document.querySelector(`#operator-conversation-Info[data-id="${socket.customerId}"] .chatpersonstatus`).classList.remove('text-green')
                    document.querySelector(`#operator-conversation-Info[data-id="${socket.customerId}"] .chatpersonstatus`).classList.add('text-muted')
                }
            }
            if(socket.onlineStatusUpdate == 'online'){
                document.querySelector(`#chat-msg-scroll [data-id='${socket.customerId}'] .avatar-status`)?.classList.add("bg-green")
                if(document.querySelector(`#operator-conversation-Info[data-id="${socket.customerId}"] .chatpersonstatus`)){
                    document.querySelector(`#operator-conversation-Info[data-id="${socket.customerId}"] .chatpersonstatus`).innerText = "online"
                    document.querySelector(`#operator-conversation-Info[data-id="${socket.customerId}"] .avatar-status`).classList.add("bg-green")
                    document.querySelector(`#operator-conversation-Info[data-id="${socket.customerId}"] .chatpersonstatus`).classList.add('text-green')
                    document.querySelector(`#operator-conversation-Info[data-id="${socket.customerId}"] .chatpersonstatus`).classList.remove('text-muted')
                }
            }
        }

        // Update the Users in the sidebar when join, reassign, and leave. and also comments
        if(document.querySelector(`.checkforactive[data-id='${socket.customerId}']`) && socket.engageUser && socket.agentInfo && socket.comments){
            let ChatIncludeUsers = JSON.parse(socket.agentInfo);
            ChatIncludeUsers.forEach((e, i)=>{
                if(e.id == autoID){
                    if(!document.querySelector(`.checkforactive.newlyaddingli[data-id='${socket.customerId}']`)){
                        document.querySelector(`.checkforactive[data-id='${socket.customerId}']`).classList.add('moveout')
                    }

                    if (document.querySelector('.main-chart-wrapper').querySelector('#operator-conversation-Info').getAttribute('data-id') == socket.customerId) {
                        document.querySelector('.textareaDiv').classList.remove('d-none');
                        document.querySelector('.engageConversation').classList.add('d-none');
                    }
                } else {
                    let avatarDiv = document.createElement("div")
                    ChatIncludeUsers.map((ele,index)=>{
                        if(index <= 1){
                            let avatarSpan = document.createElement("span")
                            avatarSpan.className = "avatar brround avatar-sm"
                            avatarSpan.style.backgroundImage = `url(${ele.profileurl ? ele.profileurl : '../uploads/profile/user-profile.png'})`
                            avatarSpan.innerText = ""
                            avatarSpan.setAttribute("data-bs-toggle","tooltip")
                            avatarSpan.setAttribute("data-bs-placement","top")
                            avatarSpan.setAttribute("data-bs-title",ele.name)
                            avatarDiv.appendChild(avatarSpan)
                        }
                    })
                    if(ChatIncludeUsers.length > 2){
                        let avatarSpan = document.createElement("span")
                        avatarSpan.className = "avatar brround bg-light text-dark avatar-sm"
                        avatarSpan.innerText = `+${ChatIncludeUsers.length-2}`
                        avatarSpan.setAttribute("data-bs-toggle","tooltip")
                        avatarSpan.setAttribute("data-bs-placement","top")
                        let fullNames = ChatIncludeUsers.map(item => `${item.firstname} ${item.lastname}`);
                        avatarSpan.setAttribute("data-bs-title",fullNames)
                        avatarDiv.appendChild(avatarSpan)
                    }

                    // To add in the Sidebar
                    if(document.querySelector(`.checkforactive[data-id='${socket.customerId}'] .avatar-list`)){
                        document.querySelector(`.checkforactive[data-id='${socket.customerId}'] .avatar-list`).innerHTML = avatarDiv.innerHTML

                        // The Leave button Update .
                        if(avatarDiv.querySelectorAll("span").length > 1){
                            let leaveLiElement = document.createElement("li")
                            leaveLiElement.innerHTML = `
                            <a class="dropdown-item" href="{{route('admin.conversationLeave')}}?id=${socket.customerId}">
                                <i class="ri-chat-delete-line align-middle me-2 fs-18"></i>
                                Leave
                            </a>
                            `
                            document.querySelector(`.checkforactive[data-id='${socket.customerId}'] .dropdown-menu`).appendChild(leaveLiElement)
                        }else{
                            document.querySelectorAll(`.checkforactive[data-id='${socket.customerId}'] .dropdown-menu li`).forEach((element)=>{
                                if(element.textContent.replace(/\s+/g, ' ').trim() == 'Leave'){
                                    element.remove()
                                }
                            })
                        }

                        document.querySelector(`.checkforactive[data-id="${socket.customerId}"] .custrecentmessage`).innerHTML = socket.comments
                        if(!document.querySelector(`.checkforactive[data-id='${socket.customerId}']`).classList.contains("active")){
                            document.querySelector(`.checkforactive[data-id="${socket.customerId}"] .custrecentmessage`).classList.add("font-weight-bold")
                        }
                        document.querySelector(`.checkforactive[data-id="${socket.customerId}"] .chat-time`).innerHTML = formattedTime
                    }
                    // To adding comments in the conversation
                    if(document.querySelector(`#operator-conversation[operator-id="${socket.customerId}"]`)){

                        let commentMessage = document.createElement("li");
                        commentMessage.className = "chat-join-notify"
                        commentMessage.innerHTML = `
                        <span>${socket.comments.replace(autoUserInfo.name,'You')} ${((new Date().getHours() + 11) % 12) + 1}:${new Date().getMinutes()}${new Date().getHours() >= 12 ? "PM" : "AM"}</span>
                        `

                        if(document.querySelector("#typingIndication")){
                            document.querySelector("#typingIndication").remove()
                        }

                        liveChatConversation.appendChild(commentMessage)

                        // To Scroll Down the Conversation
                        document.querySelector("#operator-conversation").scrollBy(0, document.querySelector("#operator-conversation").scrollHeight)
                    }
                    $('[data-bs-toggle="tooltip"]').tooltip();
                }
            })
        }

        // To Update the Message in the Side Bar
        if(document.querySelector(`.checkforactive[data-id='${socket.customerId}']`) && socket.message){
            if(document.querySelector(`.checkforactive[data-id='${socket.customerId}']`) && typeof socket.customerId == "number"){

                var activecustId = document.querySelector(`.checkforactive.active`)?.getAttribute("data-id");
                document.querySelector(`.checkforactive[data-id="${socket.customerId}"]`)?.remove()
                if(activecustId == socket.customerId){
                    document.querySelector(`#operator-conversation-Info[data-id="${socket.customerId}"]`)?.remove()
                    document.querySelector(`#operator-conversation[operator-id="${socket.customerId}"]`)?.remove()
                    document.querySelector(".engageConversation")?.classList.add("d-none")
                    document.querySelector(".chat-footer")?.classList.add("d-none")
                    if(document.querySelector("#chat-msg-scroll li")?.getAttribute("data-id")){
                        sideMenuOpenClickFunction(document.querySelector(`.checkforactive[data-id="${document.querySelector("#chat-msg-scroll li")?.getAttribute("data-id")}"]`))
                    }else{
                        localStorage.removeItem('livechatSolvedCustomer');


                        if(!document.querySelector('.text-center.mt-5.p-1.bg-warning-transparent.text-default')){
                            let emptyconver = document.createElement("div");
                            emptyconver.className = "text-center mt-5 px-2 py-4 bg-warning-transparent text-default mx-auto w-90 rounded-2";
                            emptyconver.innerHTML = `<span>{{ lang('As of now, there are no chat discussions in progress') }}</span>`;
                            document.querySelector("#chat-msg-scroll").append(emptyconver);
                            document.querySelector(".no-articles").classList.remove("d-none");
                        }
                    }
                }
            }else{
                document.querySelector(`.checkforactive[data-id='${socket.customerId}'] .chat-msg`).innerHTML = sanitizeMessage(socket.message)
                // to update the message id in side bar
                if (socket.userMessageStatusUpdate && typeof socket.userMessageStatusUpdate == 'number') {
                    document.querySelector(`.checkforactive[data-id='${socket.customerId}'] .chat-msg`).setAttribute('data-id', socket.userMessageStatusUpdate)
                }
                document.querySelector(`.checkforactive[data-id='${socket.customerId}'] .chat-time`).innerText = formattedTime
                if(!document.querySelector(`.checkforactive[data-id='${socket.customerId}']`).classList.contains("active")){
                    document.querySelector(`.checkforactive[data-id='${socket.customerId}'] .chat-msg`).classList.add("font-weight-bold")
                }
                clearTimeout(debounceTimeout4);
                pastMessage.__proto__.customerId = ""
                // To add the Top in the Sidebar
                document.querySelector("#chat-msg-scroll").insertBefore(document.querySelector(`.checkforactive[data-id='${socket.customerId}']`), document.querySelector("#chat-msg-scroll > li"))
            }
        }

        // For the Slove the Chat remove that chat in the side bar
        if(socket.comments && socket.comments.includes('Solved') && socket.customerId){
            document.querySelector(`.checkforactive[data-id="${socket.customerId}"]`)?.remove()
            document.querySelector(`#operator-conversation-Info[data-id="${socket.customerId}"]`)?.remove()
            document.querySelector(`#operator-conversation[operator-id="${socket.customerId}"]`)?.remove()
            document.querySelector(".engageConversation")?.classList.add("d-none")
            document.querySelector(".chat-footer")?.classList.add("d-none")
        }

        // To remove the customer from the sidebar if any user join
        if(document.querySelector(`.checkforactive[data-id="${socket.customerId}"]`) && socket.engageUser && socket.id != autoID && !location.href.includes('operatorID')){
            document.querySelector(`.checkforactive[data-id="${socket.customerId}"]`)?.remove()
            document.querySelector(`#operator-conversation-Info[data-id="${socket.customerId}"]`)?.remove()
            document.querySelector(`#operator-conversation[operator-id="${socket.customerId}"]`)?.remove()
            document.querySelector(".engageConversation")?.classList.add("d-none")
        }

        // For The Message statusUpdate
        if(socket.userMessageStatusUpdate && socket.customerId){
            document.querySelectorAll(`#operator-conversation[operator-id="${socket.customerId}"] .msg-sent-time .chat-read-icon`).forEach((element)=>{
                element.classList.add('chat-read-mark')
                element.classList.remove('chat-read-icon')
                if (element.querySelector('.ri-check-fill')) {
                    element.querySelector('.ri-check-fill').className = "ri-check-double-line"
                }
            })
        }

        // For the Messages Add
        if(socket.messageType != "feedBack" && (socket.customerId == liveChatConversation?.getAttribute("operator-id") || socket.id == liveChatConversation?.getAttribute("operator-id")) && socket.message && socket.message != "newUser" && socket.id != autoID){
            let custMessage = document.createElement("li");
            if(AllUserDetails.some(obj => obj.id == socket.id && obj.name == socket.userName) || socket.messageType == "welcomeMessage"){
                custMessage.className = "chat-item-start"
                custMessage.innerHTML = `
                <div class="chat-list-inner">
                    <div class="chat-user-profile">
                        ${socket.agentInfo ? `<span class="avatar avatar-md brround" style="background-image: url(${socket.agentInfo.profileurl})"></span>` :
                                            `<span class="avatar avatar-md brround" style="background-image: url(${socket?.onlineStatusUpdate?.chatbotimage ? socket.onlineStatusUpdate.chatbotimage  : '../uploads/profile/user-profile.png'})"></span>`}
                    </div>
                    <div class="ms-3">
                        <span class="chatting-user-info">
                            ${socket.userName ? socket.userName :  (socket?.onlineStatusUpdate?.chatbotname ? socket.onlineStatusUpdate.chatbotname  : 'chatBot')}
                            <span class="msg-sent-time">
                                ${((new Date().getHours() + 11) % 12) + 1}:${new Date().getMinutes()}${new Date().getHours() >= 12 ? "PM" : "AM"}
                                <span class="chat-read-icon align-middle d-inline-flex"><i class="ri-check-fill"></i></span>
                            </span>
                            ${(texttospeachenabled == 'on' || texttranslateenabled == 'on') && (socket.messageType != "image" && socket.messageType != "audio") ?
                                `<a aria-label="anchor" href="javascript:void(0);" data-bs-toggle="dropdown" aria-expanded="false" class='float-end msg-send-dropdown'>
                                    <i class="fe fe-more-vertical fs-18"></i>
                                </a>
                                <ul class="dropdown-menu">
                                    ${texttospeachenabled == 'on' ?
                                        `<li>
                                            <a aria-label="anchor" class="dropdown-item" href="javascript:void(0);" onclick="texttospeachbtn()">
                                                <i class="ri-volume-up-fill align-middle me-2 fs-17 text-muted chat-info-optionicon d-inline-block"></i>{{ lang('Text To Speach') }}
                                            </a>
                                        </li>` : ''}
                                    ${texttranslateenabled == 'on' ?
                                        `<li>
                                            <a aria-label="anchor" class="dropdown-item" href="javascript:void(0);" onclick="langtranslatebtn()">
                                                <i class="ri-volume-up-fill align-middle me-2 fs-17 text-muted chat-info-optionicon d-inline-block"></i>{{ lang('Language Translate') }}
                                            </a>
                                        </li>` : ''}
                                </ul>`
                                : ''
                            }
                        </span>
                        <div class="main-chat-msg">
                            ${socket.messageType == "image" ? `
                                <div onclick="AllFileViewer(this)" imageSrc="${socket.message}" class="mt-2 ${socket.message.toLowerCase().endsWith(".jpg") || socket.message.toLowerCase().endsWith(".png") ? 'imageMessageLiveChat' : ''}" style="
                                    background-image: url('${socket.message.toLowerCase().endsWith(".jpg") || socket.message.toLowerCase().endsWith(".png") ? socket.message : `${SITEURL}/build/assets/images/svgs/file.svg`}');
                                    background-size: cover;
                                    width: ${socket.message.toLowerCase().endsWith(".jpg") || socket.message.toLowerCase().endsWith(".png") ?'10rem' :'8rem'};
                                    aspect-ratio: 1;
                                    background-repeat: no-repeat;
                                    background-color: transparent;
                                    background-position: center;
                                ">
                                </div>
                            ` :(socket.messageType == "audio" ? `<audio controls="" src="${socket.message}"></audio>` : `<div style="white-space: pre-line;" class="text-start"><p class="mb-0 text-break" >${socket.message}</p></div>`)
                            }
                        </div>
                    </div>
                </div>
                `
            }else{
                custMessage.className = AllUserDetails.some(obj => obj.id === socket.id) ? "chat-item-start" : "chat-item-start"
                custMessage.innerHTML = `
                    <div class="chat-list-inner">
                        <div class="chat-user-profile">
                            ${
                                socket.agentInfo ? `<span class="avatar avatar-md brround" style="background-image: url(${socket.agentInfo.profileurl ? socket.agentInfo.profileurl : '../uploads/profile/user-profile.png'})"></span>` :
                                `<span class="avatar avatar-md brround" style="background-image: url(${socket?.onlineStatusUpdate?.chatbotimage ? socket.onlineStatusUpdate.chatbotimage  : '../uploads/profile/user-profile.png'})"></span>`
                            }
                        </div>
                        <div class="ms-3">
                            <span class="chatting-user-info">
                                <span class="chatnameperson">${socket.userName}</span> <span class="msg-sent-time">${((new Date().getHours() + 11) % 12) + 1}:${new Date().getMinutes()}${new Date().getHours() >= 12 ? "PM" : "AM"}</span>
                                ${(texttospeachenabled == 'on' || texttranslateenabled == 'on') && (socket.messageType != "image" && socket.messageType != "audio") ?
                                    `<a aria-label="anchor" href="javascript:void(0);" data-bs-toggle="dropdown" aria-expanded="false" class='float-end msg-send-dropdown'>
                                        <i class="fe fe-more-vertical fs-18"></i>
                                    </a>
                                    <ul class="dropdown-menu">
                                        ${texttospeachenabled == 'on' ?
                                            `<li>
                                                <a aria-label="anchor" class="dropdown-item" href="javascript:void(0);" onclick="texttospeachbtn()">
                                                    <i class="ri-volume-up-fill align-middle me-2 fs-17 text-muted chat-info-optionicon d-inline-block"></i>{{ lang('Text To Speach') }}
                                                </a>
                                            </li>` : ''}
                                        ${texttranslateenabled == 'on' ?
                                            `<li>
                                                <a aria-label="anchor" class="dropdown-item" href="javascript:void(0);" onclick="langtranslatebtn()">
                                                    <i class="ri-volume-up-fill align-middle me-2 fs-17 text-muted chat-info-optionicon d-inline-block"></i>{{ lang('Language Translate') }}
                                                </a>
                                            </li>` : ''}
                                    </ul>`
                                    : ''
                                }
                            </span>
                            <div class="main-chat-msg">
                                ${socket.messageType == "image" ? `
                                    <div onclick="AllFileViewer(this)" imageSrc="${socket.message}" class="mt-2 ${socket.message.toLowerCase().endsWith(".jpg") || socket.message.toLowerCase().endsWith(".png") ? 'imageMessageLiveChat' : ''}" style="
                                        background-image: url('${socket.message.toLowerCase().endsWith(".jpg") || socket.message.toLowerCase().endsWith(".png") ? socket.message : `${SITEURL}/build/assets/images/svgs/file.svg`}');
                                        background-size: cover;
                                        width: ${socket.message.toLowerCase().endsWith(".jpg") || socket.message.toLowerCase().endsWith(".png") ?'10rem' :'8rem'};
                                        aspect-ratio: 1;
                                        background-repeat: no-repeat;
                                        background-color: transparent;
                                        background-position: center;
                                    ">
                                    </div>
                                ` : (socket.messageType == "audio" ? `<audio controls="" src="${socket.message}"></audio>` : `<div style="white-space: pre-line;" class="text-start"><p class="mb-0 text-break" >${socket.message}</p></div>`)
                                }
                            </div>
                        </div>
                    </div>
                `
            }

            if(document.querySelector("#typingIndication")){
                document.querySelector("#typingIndication").remove()
            }

            liveChatConversation?.appendChild(custMessage)

            // To add the seen Indaction.
            $.ajax({
                type: "get",
                url: SITEURL + `/livechat/singlecustdata/${document.querySelector("#operator-conversation")?.getAttribute("operator-id")}`,
                success: function (data) {

                },
                error: function (data) {
                    console.log('Error:', data);
                }
            });

            // To Scroll Down the Conversation
            document.querySelector("#operator-conversation")?.scrollBy(0, document.querySelector("#operator-conversation").scrollHeight)

        }

        // For the feedBack Form comment add
        if(socket.messageType == "feedBack" && socket.customerId == liveChatConversation?.getAttribute("operator-id") && socket.message){
            let FeedbackMessage = JSON.parse(socket.message)
            let agentLi = document.createElement("li");
            agentLi.className = "chat-join-notify"
            agentLi.innerHTML = `
            <span>Your chat has been rated ${FeedbackMessage.starRating} out of 5 by the customer</span>
            `

            liveChatConversation.appendChild(agentLi)
            // To Scroll Down the Conversation
            document.querySelector("#operator-conversation").scrollBy(0, document.querySelector("#operator-conversation").scrollHeight)

        }

        // To add Typing Indication for the customer
        if(socket.typingMessage && liveChatConversation?.getAttribute("operator-id") == socket.customerId && !socket.agentInfo){
            let typingIndication = document.querySelector("#typingIndication")

            if(typingIndication){
                typingIndication.remove()
            }

            let custMessage = document.createElement("li");
            custMessage.className = "chat-item-start"
            custMessage.id = "typingIndication"
            custMessage.innerHTML = `
                <div class="chat-list-inner">
                    <div class="chat-user-profile">
                        <span class="avatar avatar-md brround" style="${document.querySelector(`.checkforactive[data-id='${socket.customerId}'] #new-chat-user-bg`)?.getAttribute('style')}">
                            <span class="new-chat-user-letter">${socket.userName.slice(0,1).toUpperCase()}</span>
                        </span>
                    </div>
                    <div class="ms-3">
                        <span class="chatting-user-info">
                            <span class="chatnameperson">${socket.userName}</span> <span class="msg-sent-time">${((new Date().getHours() + 11) % 12) + 1}:${new Date().getMinutes()}${new Date().getHours() >= 12 ? "PM" : "AM"}</span>
                        </span>
                        <div class="main-chat-msg">
                            <div class="d-flex">
                                <p class="mb-0">${socket.typingMessage}</p>
                                <b class="ms-3">{{ lang('Typing...') }}</b>
                            </div>
                        </div>
                    </div>
                </div>
            `

            if(socket.typingMessage != "empty"){
                liveChatConversation.appendChild(custMessage)
            }else{
                typingIndication?.remove()
            }

            // To Scroll Down the Conversation
            document.querySelector("#operator-conversation").scrollBy(0, document.querySelector("#operator-conversation").scrollHeight)


            clearTimeout(debounceTimeout);
            debounceTimeout = setTimeout(function() {
                if(document.querySelector("#typingIndication")){
                    document.querySelector("#typingIndication").querySelector(".main-chat-msg b").innerText = "{{ lang('Typing Ended') }}"
                }
              }, 5000);
        }

        // To add Typing Indication for the Agent
        if(socket.typingMessage && liveChatConversation?.getAttribute("operator-id") == socket.customerId && socket.agentInfo && socket.id != autoID){
            let typingIndication = document.querySelector("#typingIndication")

            if(typingIndication){
                typingIndication.remove()
            }

            let agentMessage = document.createElement("li");
            agentMessage.className = "chat-item-start"
            agentMessage.id = "typingIndication"
            agentMessage.innerHTML = `
                <div class="chat-list-inner">
                    <div class="chat-user-profile">
                        <span class="avatar avatar-md brround" style="background-image: url(${JSON.parse(socket.agentInfo).profileurl ? JSON.parse(socket.agentInfo).profileurl : '../uploads/profile/user-profile.png'})"></span>
                    </div>
                    <div class="ms-3">
                        <span class="chatting-user-info">
                            <span class="chatnameperson">${socket.userName}</span> <span class="msg-sent-time">${((new Date().getHours() + 11) % 12) + 1}:${new Date().getMinutes()}${new Date().getHours() >= 12 ? "PM" : "AM"}</span>
                        </span>
                        <div class="main-chat-msg">
                            <div class="d-flex">
                                <p class="mb-0">${socket.typingMessage}</p>
                                <b class="ms-3">{{ lang('Typing...') }}</b>
                            </div>
                        </div>
                    </div>
                </div>
            `

            if(socket.typingMessage != "empty"){
                liveChatConversation.appendChild(agentMessage)
            }else{
                typingIndication?.remove()
            }

            // To Scroll Down the Conversation
            document.querySelector("#operator-conversation").scrollBy(0, document.querySelector("#operator-conversation").scrollHeight)

            clearTimeout(debounceTimeout3);
            debounceTimeout3 = setTimeout(function() {
                if(document.querySelector("#typingIndication")){
                    document.querySelector("#typingIndication").querySelector(".main-chat-msg b").innerText = "{{ lang('Typing Ended') }}"
                }
            }, 5000);
        }

        // For the Typing Indication updating in sidebar
        if(document.querySelector(`.checkforactive[data-id='${socket.customerId}']`) && socket.typingMessage && socket.id != autoID){
            if(!document.querySelector(`.checkforactive[data-id='${socket.customerId}'] .custrecentmessage`).innerText.includes('Typing ...')){
                pastMessage = document.querySelector(`.checkforactive[data-id='${socket.customerId}'] .custrecentmessage`).innerText
            }

            document.querySelector(`.checkforactive[data-id='${socket.customerId}'] .custrecentmessage`).innerText = `${socket.userName} Typing ...`


            clearTimeout(debounceTimeout4);
            debounceTimeout4 = setTimeout(function() {
                if(document.querySelector(`.checkforactive[data-id='${socket.customerId}'] .custrecentmessage`)){
                    document.querySelector(`.checkforactive[data-id='${socket.customerId}'] .custrecentmessage`).innerText = pastMessage
                }
            }, 5000)

        }

        if (socket.deliveryStatus == 'delivered' && document.querySelector(`#operator-conversation [messageid='${socket.messageId}']`)) {
            document.querySelector(`#operator-conversation [messageid='${socket.messageId}'] i`).classList.remove('ri-check-fill')
            document.querySelector(`#operator-conversation [messageid='${socket.messageId}'] i`).classList.add('ri-check-double-line')
        }

        if (socket.deliveryStatus == 'deleted') {
            if (document.querySelector(`#operator-conversation [messageid='${socket.messageId}']`)) {
                document.querySelector(`#operator-conversation [messageid='${socket.messageId}'] .main-chat-msg`).innerHTML = '<div style="white-space: pre-line;background: #f4f6fb;color: #aaa;padding: 5px;font-style: italic;" class="text-start"><p class="mb-0 text-break"><i class="bx bx-block leading-none "></i>{{ lang('This message was deleted') }}</p></div>'
                document.querySelector(`#operator-conversation [messageid='${socket.messageId}'] .main-chat-msg`).classList.remove('font-weight-bold')
            }
            if (document.querySelector(`.checkforactive[data-id='${socket.customerId}'] .custrecentmessage[data-id='${socket.messageType}']`)) {
                document.querySelector(`.checkforactive[data-id='${socket.customerId}'] .custrecentmessage[data-id='${socket.messageType}']`).innerHTML = '<i class="bx bx-block leading-none "></i>{{ lang('This message was deleted') }}';
            }
        }

        if (socket.deliveryStatus == 'read') {
            if (typeof socket.messageId == 'string' && document.querySelector(`#operator-conversation [messageid='${socket.messageId}']`)) {
                document.querySelector(`#operator-conversation [messageid='${socket.messageId}'] i`).classList.remove('ri-check-fill')
                document.querySelector(`#operator-conversation [messageid='${socket.messageId}'] i`).classList.add('ri-check-double-line')
                document.querySelector(`#operator-conversation [messageid='${socket.messageId}'] .align-middle.d-inline-flex`).classList.remove('chat-read-icon')
                document.querySelector(`#operator-conversation [messageid='${socket.messageId}'] .align-middle.d-inline-flex`).classList.add('chat-read-mark')
            } else if (typeof socket.messageId == 'number' && document.querySelector(`#main-chat-content [data-id="${socket.messageId}"]`)) {
                document.querySelectorAll('.chat-read-icon.align-middle.d-inline-flex').forEach((ele) => {
                    ele.classList.remove('chat-read-icon')
                    ele.classList.add('chat-read-mark')
                })
            }
        }

        if(socket.comments && socket.comments.includes(`${autoUser} Solved the discussion at`) && !document.querySelector(`.list-unstyled [data-id='${socket.customerId}']`)){

            if(document.querySelector('.text-center.mt-5.p-1.bg-warning-transparent.text-default')){
                document.querySelector('.text-center.mt-5.p-1.bg-warning-transparent.text-default').remove();
            }

            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 humandifrformatTime(inputTime) {
                const initialDate = new Date(inputTime);
                const now = new Date();

                const diffInMinutes = Math.floor((now - initialDate) / 60000);
                let timeText;

                if (diffInMinutes < 1) {
                    timeText = 'Just now';
                } else if (diffInMinutes < 60) {
                    timeText = `${diffInMinutes} minute${diffInMinutes > 1 ? 's' : ''} ago`;
                } else {
                    const diffInHours = Math.floor(diffInMinutes / 60);
                    if (diffInHours < 24) {
                        timeText = `${diffInHours} hour${diffInHours > 1 ? 's' : ''} ago`;
                    } else {
                        const diffInDays = Math.floor(diffInHours / 24);
                        timeText = `${diffInDays} day${diffInDays > 1 ? 's' : ''} ago`;
                    }
                }

                return timeText;
            }

            var currentOnlineUsers = '{{ setting('liveChatCustomerOnlineUsers') }}';
            var onlineUsersArray = currentOnlineUsers.split(',');
            var markAsUnreadArray = JSON.parse(socket.custdata.mark_as_unread || '[]');
            var conversDeleteRouteUrl = `{{ route('admin.livechatConversationDelete') }}?unqid=${socket.custdata.cust_unique_id}`;


            const sidebardata = document.createElement("li");
            sidebardata.className = "checkforactive newlyaddingli";
            sidebardata.setAttribute("data-id", socket.custdata.id);
            sidebardata.innerHTML =
            `
            <div class="d-flex align-items-center">
                <div class="me-2 lh-1">
                    <span class="avatar brround" id="new-chat-user-bg" style="background-color: ${socket.custdata.profile_bg_color}">
                        ${socket.custdata.userType == 'livechat' ? `<span class="avatar-status ${onlineUsersArray.includes(socket.custdata.id) ? 'bg-green' : ''}"></span>` : ''}
                        <span class="new-chat-user-letter">${socket.custdata.username.slice(0,1).toUpperCase()}</span>
                        <input aria-label="anchor" aria-expanded="false" type="checkbox" name="customer_checkbox[]" class="checkall ticket-select-check live-chat-checkbox form-check-input" value="${socket.custdata.encrypted_id}"/>
                    </span>
                </div>
                <div class="flex-fill">
                    <div class="mb-0 d-flex align-items-center justify-content-between">
                        <div class="font-weight-semibold">
                            <a href="javascript:void(0);">${socket.custdata.username}</a>
                        </div>
                        <div class="float-end text-muted fw-normal fs-12 chat-time" data-initial-24time='${dateTime(socket.custdata.solveddiscreated)}'>${humandifrformatTime(socket.custdata.solveddiscreated)}</div>
                        <div class="dropdown chat-actions lh-1">
                            <a aria-label="anchor" href="javascript:void(0);" data-bs-toggle="dropdown" aria-expanded="false" class="">
                                <i class="fe fe-more-vertical fs-18"></i>
                            </a>
                            <ul class="dropdown-menu" style="">
                                <li class="conversationbarclose">
                                    <a aria-label="anchor" class="dropdown-item" href="javascript:void(0);" onclick="slectTicket(event, ${socket.custdata.id})" data-id="${socket.custdata.id}">
                                        <i class="ri-mail-check-fill align-middle me-2 fs-17 text-muted chat-info-optionicon d-inline-block"></i>{{ lang('Select') }}
                                    </a>
                                </li>
                                <li>
                                    <a class="dropdown-item" deleteRouteLink="${conversDeleteRouteUrl}"><i
                                    class="ri-delete-bin-fill align-middle me-2 fs-17 text-muted chat-info-optionicon d-inline-block"></i>{{ lang('Delete') }}</a>
                                </li>
                            </ul>
                        </div>
                    </div>
                    <div class="d-flex align-items-center justify-content-between">
                        <span class="chat-msg text-truncate fs-13 text-default custrecentmessage" data-id="100">${socket.comments.replace(autoUserInfo.name,'You')}</span>
                        ${markAsUnreadArray.includes(autoID) ?
                            `<span class="badge bg-success-transparent rounded-circle float-end unReadIndexNumber me-1 ms-auto"></span>` : ''
                        }
                    </div>
                </div>
            </div>
            `;

            sidebardata.onclick = () => {
                if(event.target.classList.contains('fe-more-vertical') || event.target.classList.contains('dropdown-item') || event.target.classList.contains('ticket-select-check')){
                    event.stopPropagation();
                    updateCustomCheckAll();
                    updateMassDeleteVisibility();
                    deletingdatafunction();
                }else{
                    sideMenuOpenClickFunction(sidebardata);
                }
            }

            document.querySelector("#chat-msg-scroll").insertBefore(sidebardata, document.querySelector("#chat-msg-scroll > li"));
        }
        pauseAudios();
    })


    </script>

<script type="text/javascript">
    function responsivechat() {

        /* NEW JS FOR LIVE CHAT RESPONSIVE */
        document.querySelectorAll(".checkforactive").forEach((ele) => {
            ele.addEventListener("click", () => {
                document.querySelector(".main-chart-wrapper").classList.add("responsive-chat-open")
            })
        })

        document.querySelectorAll(".responsive-userinfo-open").forEach((ele) => {
            ele.addEventListener("click", () => {
                document.querySelector(".main-chat-user-details").classList.add("open");
            });
        });

        document.querySelector(".responsive-chat-close")?.addEventListener("click", () => {
            document.querySelector(".main-chart-wrapper").classList.remove("responsive-chat-open")
        })

        document.querySelector(".responsive-chat-close2")?.addEventListener("click",() =>{
            document.querySelector(".main-chat-user-details").classList.remove("open")
        })

        document.querySelector(".chat-info")?.addEventListener("click", () => {
            document.querySelector(".main-chat-user-details").classList.remove("open")
        })
        document.querySelector(".chat-content")?.addEventListener("click", () => {
            document.querySelector(".main-chat-user-details").classList.remove("open")
        })
        /* NEW JS FOR LIVE CHAT RESPONSIVE */
    }
</script>

<script>
    let voices = [];
    let arabicVoice = null;
    let defaultVoice = null;

    function loadVoices() {
        voices = speechSynthesis.getVoices();
    }

    async function translateText(text, targetLang) {
        const response = await fetch('{{ route('texttospeech.lang.translate.back') }}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
            },
            body: JSON.stringify({
                text: text,
                target_lang: targetLang
            })
        });

        if (!response.ok) {
            throw new Error('Translation failed');
        }

        const data = await response.json();
        return data.translatedText;
    }

    async function speakText() {
        const textInput = document.getElementById('texttospeachcontent').value;
        const selectedLang = document.getElementById('lang-select').value;
        try {
            const translatedText = await translateText(textInput, selectedLang);
            const utterance = new SpeechSynthesisUtterance(translatedText);
            const matchingVoice = voices.find(voice => voice.lang.startsWith(selectedLang));

            if (matchingVoice) {
                utterance.voice = matchingVoice;
                utterance.lang = selectedLang;
            } else {
                alert(`No voice is available for the selected language: ${selectedLang}. The browser will use a default voice.`);
            }

            speechSynthesis.cancel();
            speechSynthesis.speak(utterance);
        } catch (error) {
            console.error('Error:', error);
        }
    }

    function stop() {
        speechSynthesis.cancel();
    }

    function pause() {
        speechSynthesis.pause();
    }

    function resume() {
        speechSynthesis.resume();
    }

    window.addEventListener('load', () => {
        loadVoices();
        speechSynthesis.onvoiceschanged = loadVoices;
    });
    window.addEventListener('beforeunload', () => {
        if (speechSynthesis.speaking) {
            stop();
        }
    });
</script>

@endsection

