<?php $__env->startSection('content'); ?>
    <body class="fix-header fix-sidebar card-no-border">
    <div id="main-wrapper">

        <div class="page-wrapper customWrap">

            <div class="container-fluid">

                <div class="row">

                    <div class="col-lg-12">
                        <div class="">
                            <div class="crdBody main-create">
                                <div class="row">
                                    <div class="col-md-3 col-lg-3">
                                        <div class="chat-message-main">
                                            <div class="chat-head">
                                                <h3>Conversation</h3>
                                            </div>
                                            <div class="chat-heig scroll4" style="    height: 697px;">

                                                <?php if(count($chatRooms) == 0): ?>
                                                    <div class="chat-tab">
                                                        <div class="row">
                                                            <p>You Haven't Start Chat Anyone Yet!! </p>
                                                        </div>
                                                    </div>
                                                <?php else: ?>
                                                    <?php $__currentLoopData = $chatRooms; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $room): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                        <div class="chat-tab"
                                                             onclick="openChat(<?php echo e($room->receiver_id == \Illuminate\Support\Facades\Auth::id() ? $room->sender_id : $room->receiver_id); ?>)">
                                                            <div class="row">
                                                                <div class="col-md-3">
                                                                    <div class="chat-active-img">
                                                                        <img src="<?php echo e(asset('images/img18.jpg')); ?>"
                                                                             class="img-responsive"
                                                                             alt="">
                                                                    </div>
                                                                </div>
                                                                <div class="col-md-9 no-pad">
                                                                    <div class="chat-user">
                                                                        <h3>
                                                                            <a> <?php echo e($room->receiver_id == \Illuminate\Support\Facades\Auth::id() ? $room->sender->name : $room->receiver->name); ?> </a>
                                                                        </h3>
                                                                        <div class="color-active"></div>
                                                                        <p><?php echo e($room->last_message ?? 'Say Hi'); ?></p>
                                                                        <span><?php echo e($room->last_message_time ?? ''); ?></span>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-9 col-lg-9">
                                        <div class="chat-message" id="messageBox" style="display: none">
                                            <div class="chat-active-name">
                                                <div class="row">
                                                    <div class="col-md-7">
                                                        <h2 id="chatterName"></h2>
                                                        <div class="color-active"></div>
                                                    </div>
                                                    <div class="col-md-5">
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="main-chat">
                                                <div class="scroll-chat-box scroll4" id="inner-main-chat" style="overflow: scroll;
    height: 610px; overflow-x: hidden;
">
                                                    
                                                    
                                                    
                                                    
                                                    
                                                    
                                                    
                                                    
                                                    
                                                    
                                                    
                                                    
                                                    
                                                    
                                                    
                                                    
                                                    
                                                    
                                                    
                                                    
                                                </div>
                                                <div class="message-send-box">
                                                    <div class="form-group">
                                                        <div class="col-md-12">
                                                            <div class="smile-icn">
                                                                <a href="#"><img src="<?php echo e(asset('images/smile.png')); ?>"
                                                                                 class="img-fluid"
                                                                                 alt="img"></a>
                                                            </div>
                                                            <input type="text" id="messageInput" name="messsage"
                                                                   class="form-control"
                                                                   placeholder="Type your message ..."
                                                                   onkeyup="checkEnter(event)">
                                                            <div class="btn-attecment">
                                                                <input class="choose-file" type="file"
                                                                       id="choose-message-file"
                                                                       required="" name="message_file"
                                                                       onchange="sendFile()">

                                                                <label for="choose-message-file"
                                                                       class="upload-file"></label>
                                                            </div>
                                                            <div class="btn-sent-chat">
                                                                <button class="btn btn-default" onclick="sendMessage()">
                                                                    <img src="<?php echo e(asset('images/paperpln.png')); ?>"
                                                                         class="img-responsive"
                                                                         alt="">
                                                                </button>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <?php $__env->stopSection(); ?>
        <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

        <script>

            const authUser = <?php echo e(\Illuminate\Support\Facades\Auth::id()); ?>;
            var openedRoomId = null;
            var roomUserId = null;

            function sendFile() {
                // You can perform any additional actions here if needed.

                // Call the sendMessage() function to send the message, including the selected file.
                sendMessage();
            }

            function checkEnter(event) {
                if (event.key === "Enter") {
                    // Call your function here
                    sendMessage();
                }
            }

            function openChat(roomUser) {
                console.log("MESSENGER OPEN", roomUser);
                roomUserId = roomUser;
                // Make the AJAX call
                $.ajax({
                    type: 'POST',
                    url: '<?php echo e(route('get.room.messages')); ?>', // Use the named route from your web.php
                    data: {
                        roomUser: roomUser, // Add the roomUser to the data object
                        _token: '<?php echo e(csrf_token()); ?>',
                    },
                    success: function (res) {
                        console.log("res", res);

                        var messageBox = document.getElementById('messageBox');
                        messageBox.style.display = "block";
                        var innerchatbox = document.getElementById('inner-main-chat');

                        $('#chatterName').text(res.room_name);
                        openedRoomId = res.room_id;

                        if (res.data.length == 0) {
                            innerchatbox.style.display = "none";
                        } else {
                            innerchatbox.style.display = "block";

                            $('#inner-main-chat').empty();

                            // Clear the chat content before appending new messages
                            res.data.forEach(function (item) {
                                console.log("tem ", item);

                                if (item.user_id == authUser) {
                                    // Clone the 'receiver' div

                                    var reciverMessage = item.message; // Replace this with your actual message data

                                    if (item.message != null && item.message.includes('uploads') !== false) {
                                        fileName = reciverMessage.replace(/uploads\//g, ''); // Remove 'uploads/' from the message
                                        var downloadUrl = '/public/storage/' + reciverMessage;
                                        var reciveMessageHtml = '<a href="' + downloadUrl + '" download style="background: #606060;' +
                                            'padding: 9px 20px;' +
                                            'border-radius: 4px; color: #fff; text-decoration: none;"><i class="fas fa-download"></i> Download ' + fileName + ' </a>';
                                    } else {
                                        var reciveMessageHtml = '<p id="reciverMessage">' + reciverMessage + '</p>';
                                    }

                                    var messaegTime = item.created_at != null ? item.created_at : "";
                                    // var imagePath = 'profile_image/' + App\Models\User::;
                                    var date = new Date(messaegTime);
                                    var formattedDate = date.toLocaleString('en-US', {day: 'numeric', month: 'short'});

                                    var reciverHtml = '<div class="recive" id="receiver">' +
                                        '<div class="chat-text">' +
                                        reciveMessageHtml +
                                        '<span id="reciverMessageTime"> ' + formattedDate + ' </span>' +
                                        '</div>' +
                                        '<div class="chat-profile">' +
                                        // '<img  src="' + imagePath + '" class="img-responsive" alt="">' +
                                        '</div>' +
                                        '</div>';

                                    $('#inner-main-chat').append(reciverHtml);
                                } else {
                                    // Clone the 'sender' div
                                    var senderMessage = item.message; // Replace this with your actual message data

                                    if (item.message != null && item.message.includes('uploads') !== false) {
                                        fileName = senderMessage.replace(/uploads\//g, ''); // Remove 'uploads/' from the message
                                        var downloadUrl = '/public/storage/' + senderMessage;
                                        var senderMessageHtml = '<a href="' + downloadUrl + '" download style="background: #e3e3e3;' +
                                            'padding: 9px 20px;' +
                                            'border-radius: 4px; color: grey; text-decoration: none;"><i class="fas fa-download"></i> Download ' + fileName + ' </a>';
                                    } else {
                                        var senderMessageHtml = '<p id="senderMessage">' + senderMessage + '</p>';
                                    }

                                    var messaegTime = item.created_at != null ? item.created_at : "";
                                    // var imagePath = 'profile_image/' + item.user_id.profile_image;
                                    var date = new Date(messaegTime);
                                    var formattedDate = date.toLocaleString('en-US', {day: 'numeric', month: 'short'});

                                    var senderHtml = '<div class="send" id="sender">' +
                                        '<div class="chat-profile">' +
                                        // '<img  src="' + imagePath + '" class="img-responsive" alt="">' +
                                        '</div>' +
                                        '<div class="chat-text">' +
                                        senderMessageHtml +
                                        '<span id="senderMessageTime"> ' + formattedDate + ' </span>' +
                                        '</div>' +
                                        '</div>';


                                    $('#inner-main-chat').append(senderHtml);
                                }

                            });

                            var innerMainChat = $("#inner-main-chat")[0];
                            innerMainChat.scrollTop = innerMainChat.scrollHeight;

                        }

                    },
                    error: function (xhr, status, error) {
                        // Handle any errors that occur during the AJAX request
                    },
                });
            };

            function sendMessage() {
                var message = $("#messageInput").val();
                var messageFile = document.getElementById('choose-message-file').files[0];

                console.log("openedRoomId", openedRoomId, roomUserId, messageFile);

                var formData = new FormData();
                formData.append('message', message);
                formData.append('message_file', messageFile);
                formData.append('room_id', openedRoomId);
                formData.append('_token', '<?php echo e(csrf_token()); ?>');

                $.ajax({
                    url: '<?php echo e(route('send.message')); ?>', // Use the named route from your web.php
                    method: "POST",
                    data: formData,
                    processData: false, // Important! Prevents jQuery from processing the data
                    contentType: false, // Important! Prevents jQuery from setting the content type
                    success: function (response) {
                        if (response.status == 200) {
                            console.log("Message sent successfully:", response);
                            openChat(roomUserId);
                        }
                    },
                    error: function (error) {
                        // Handle the error if the request fails
                        console.error("Error sending message:", error);
                    }
                });

                // Clear the input field after sending the message
                $("#messageInput").val("");
            }


        </script>

<?php echo $__env->make('layout.dashboard-app', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH /home/servicedemoweb/public_html/global-man-cave/resources/views/dashboard/messenger.blade.php ENDPATH**/ ?>