<link rel="stylesheet" href="<?= base_url(); ?>assets/theme/css/chat.css" />

<script src="https://www.gstatic.com/firebasejs/5.3.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.3.0/firebase-firestore.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.3.0/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.3.0/firebase-storage.js"></script>
<link rel="stylesheet" href="<?= base_url(); ?>assets/theme/css/loading-bar.min.css" />
<script src="<?= base_url(); ?>assets/theme/js/loading-bar.min.js"></script>
<style>
    #overlay {
        position: absolute;
        display: none;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background-color: rgba(0, 0, 0, 0.3);
        z-index: 9999999;
    }

    #text {
        position: absolute;
        top: 50%;
        left: 50%;
        color: white;
        transform: translate(-50%, -50%);
        -ms-transform: translate(-50%, -50%);
    }

    .fa-user-plus {
        color: #20435A;
    }
</style>
<script>
    const firebaseConfig = {
        apiKey: "AIzaSyA6KZpE6WJvtFGorJw8qWPICaSBmi8J0mo",
        authDomain: "yahlove-6f1b3.firebaseapp.com",
        projectId: "yahlove-6f1b3",
        storageBucket: "yahlove-6f1b3.appspot.com",
        messagingSenderId: "21273045598",
        appId: "1:21273045598:web:425cdbe07b05e61f0f62cf",
        measurementId: "G-8LW1CGS161"
    };
    firebase.initializeApp(firebaseConfig);
    var db = firebase.firestore();
    db.settings({
        timestampsInSnapshots: true
    })
    var auth = firebase.auth();
    var storageRef = firebase.storage().ref();
</script>
<script>
    var singleConversationID = '';
    var myid = '<?php echo $adminId; ?>';
    var userId = '<?php echo $firstUserId; ?>';
    var allUsers = <?php echo json_encode($allUsers); ?>;
    var adminName = '<?php echo ($this->session->userdata["session_data"]["name"]); ?>';

    function fetchMessages(cid, fid) {

        if (fid == '' || fid == 0)
            return;
        $('.messages-content').empty();


        const vm = this;
        vm.conversationID = cid;

        db.collection('AdminChats').doc(cid).collection('Conversations').orderBy('timestamp').onSnapshot((querySnapshot) => {
            let allMessages = []
            querySnapshot.forEach((doc) => {
                if (doc) {
                    let data = doc.data();
                    data['mid'] = doc.id;
                    allMessages.push(data);

                }
            })
            allMessages = allMessages.filter(element => {
                return element.toID == fid || element.fromID == fid;
            });
            vm.messages = allMessages
        })

        if (vm.messages != "undefined" && vm.messages != "" && vm.messages != null) {

            let imageContent = "";
            vm.messages.forEach(function(message) {

                if (message.fromID != myid) {
                    if (message.type == 'image') {
                        $('<li class="clearfix imgmessage" style="display:block;"><a href="' + message.content + '" target="_blank"><img src="' + message.content + '" height="200"; width="200;" /></a></li>').appendTo($('.messages-content'));
                    } else {
                        if (message.content != '') {
                            $('<li class="clearfix"><div class="message-data"><span class="message-data-time">' + new Date(message.timestamp).toLocaleDateString('en-us', {
                                    hour12: true,
                                    weekday: "short",
                                    year: "numeric",
                                    month: "short",
                                    day: "numeric",
                                    hour: '2-digit',
                                    minute: '2-digit',
                                    second: '2-digit'
                                }) + '</span></div><div class="message my-message">' + message
                                .content + '</div></li>').appendTo($('.messages-content'));
                        }
                    }

                } else {
                    lastMessageId = message.mid;
                    if (message.type == 'image') {
                        $('<li class="clearfix imgmessage"><div class="text-right"><div class="float-right"><a href="' + message.content + '" target="_blank"><img src="' + message.content +
                            '" height="200"; width="200;" /></a></div></div></li>').appendTo($(
                            '.messages-content'));
                    } else {
                        if (message.content != '') {
                            $('<li class="clearfix"><div class="message-data text-right"><span class="message-data-time">' + new Date(message.timestamp).toLocaleDateString('en-us', {
                                    hour12: true,
                                    weekday: "short",
                                    year: "numeric",
                                    month: "short",
                                    day: "numeric",
                                    hour: '2-digit',
                                    minute: '2-digit',
                                    second: '2-digit'
                                }) + '</span><img src="https://bootdey.com/img/Content/avatar/avatar7.png" alt="avatar" /></div><div class="message other-message float-right"><i class="fa fa-trash chatico" onclick="deleteMessage(\'' + message.messageId + '\', \'' + vm.conversationID +
                                '\')"></i>' + message
                                .content + '</div></li>').appendTo($('.messages-content'));
                        }
                    }

                }
            });
        }


        //setDate();
    }

    async function sendMessage(messageText) {

        if (messageText.trim()) {
            var msgId = Date.now();
            const message = {
                "content": messageText,
                "timestamp": msgId,
                "messageId": msgId.toString(),
                "fromID": myid,
                "toID": userId,
                "isRead": false,
                "type": "text"
            }
            const members = {
                [myid]: true,
                [userId]: true,
            }

            await db.collection('AdminChats').doc(singleConversationID).collection('Conversations').doc(msgId.toString()).set(message);
            await db.collection('AdminChats').doc(singleConversationID).set({
                lastMessage: message,
            }, {
                merge: true
            });

            $(".chat-history").animate({
                scrollTop: $('.chat-history').prop("scrollHeight")
            });

        }

    }

    $('.message-submit').on('click', function() {
        insertMessage();
    });

    $(window).on('keydown', function(e) {
        if (e.key == 'Enter') {
            insertMessage();
            return false;
        }
    });
</script>
<div class="container-fluid">


    <!-- Page Heading -->
    <div class="d-sm-flex align-items-center justify-content-between mb-4">
        <h1 class="h3 mb-0 text-gray-800">Chat</h1>
        <!-- <a href="#" class="d-none d-sm-inline-block btn btn-sm btn-primary shadow-sm"><i class="fas fa-download fa-sm text-white-50"></i> Generate Report</a> -->
    </div>
    <div class="card chat-app">
        <div id="plist" class="people-list">
            <ul class="list-unstyled chat-list mt-2 mb-0" id="singleList">

                <li class="clearfix d-flex align-items-center" data-toggle="modal" data-target="#exampleModal" id="chatListItemOne">
                    <i class="fa fa-user-plus fa-2x mx-2"></i>
                    <div class="about">
                        <div class="name">New Chat</div>
                    </div>
                </li>

                <?php
                $formUsers = $allUsers;
                $avatarNum = 1;
                $firstUserRecord = true;
                foreach ($chatUsers as $cid => $cstaff) {
                    if ($firstUserRecord) {
                        $singleConversationID = $cstaff['conversationID'];
                    }
                ?>

                    <li data-conversationid="<?= $cstaff['conversationID'] ?>" id="clist-<?= $cid ?>" class="clearfix stafflist<?php echo ($firstUserRecord ? ' active' : ''); ?>" onclick="selectStaff('<?= $cid ?>', '<?= $cstaff['userName'] ?>', this, '<?= $cstaff['userLastLogin'] ?>', '<?= $cstaff['conversationID'] ?>');">

                        <img src="https://bootdey.com/img/Content/avatar/avatar<?= $avatarNum ?>.png" alt="avatar" />

                        <div class="about">

                            <div class="name"><?= $cstaff['userName'] ?> </div>

                            <div class="status">

                                <i class="fa fa-circle online"></i> online

                            </div>

                        </div>
                        <i class="fa fa-trash" onclick="removeChatStaff('<?= $cid ?>', '<?= $cstaff['conversationID'] ?>');" title="Remove from chat"></i>

                    </li>

                <?php
                    $notAllowedInModal[] = $cid;
                    $firstUserRecord = false;
                    $avatarNum++;
                }
                $formUsers = array_filter(
                    $formUsers,
                    function ($key) use ($notAllowedInModal) {
                        return !in_array($key, $notAllowedInModal);
                    },
                    ARRAY_FILTER_USE_KEY
                );
                ?>

            </ul>
        </div><!-- /.people-list -->
        <div class="chat">
            <div class="chat-header clearfix">

                <div class="row">

                    <div class="col-lg-6">

                        <a href="javascript:void(0);" data-toggle="modal" data-target="#view_info">

                            <img src="https://bootdey.com/img/Content/avatar/avatar2.png" alt="avatar" />

                        </a>

                        <div class="chat-about">

                            <h6 class="m-b-0" id="chatingStaff"><?= $userDisplayName ?></h6>

                            <small><span id="lastStaffLogin"></small>

                        </div>

                    </div>

                    <div class="col-lg-6 hidden-sm text-right">



                    </div>

                </div>

            </div>
            <!-- <i style="color: green;">Loading Chat...</i> -->
            <div class="chat-history">

                <ul class="m-b-0">
                    <div class="messages-content"></div>
                </ul>

            </div>
            <form id="imgform" method="post" enctype="multipart/form-data">

                <div class="chat-message clearfix">

                    <div class="input-group mb-0">

                        <div class="input-group-prepend">

                            <span class="input-group-text" onclick="insertMessage();"><i class="fa fa-paper-plane"></i></span>

                        </div>

                        <input type="text" name="message" id="textMessage" class="form-control" placeholder="Enter text here..." />
                        <input type="file" name="imgfile" id="imgupload" style="display:none" onchange="imageUpload(this.value)" />

                        <div class="input-group-append" id="OpenImgUpload">
                            <span class="input-group-text"><i class="fa fa-upload" style="color:DodgerBlue;"></i></span>
                        </div>
                    </div>

                </div>
            </form>
            <div id="overlay">
                <div id="text">
                    <div id="imgUploadProgress" data-pattern-size="150" data-preset="bubble" class="ldBar label-center"></div>
                </div>

            </div>
        </div>

    </div>
</div>
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">

    <div class="modal-dialog">

        <div class="modal-content">

            <div class="modal-header">

                <h5 class="modal-title" id="exampleModalLabel">New Chat</h5>

                <button type="button" class="btn-close" data-dismiss="modal" aria-label="Close"></button>

            </div>

            <div class="modal-body">

                <div class="">

                    <label for="" class="form-label">Select User</label>

                    <select class="form-select" name="staffSelect" id="staffSelect" aria-placeholder="Select User">
                        <?php
                        foreach ($formUsers as $frmid => $frmstaff) {
                        ?>
                            <option id="<?= $frmid ?>" value="<?= $frmid ?>@<?= $frmstaff['userLastLogin'] ?>"><?= $frmstaff['userName'] ?></option>

                        <?php } ?>
                    </select>

                </div>

            </div>

            <div class="modal-footer">

                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>

                <button type="button" class="btn btn-primary" onclick="addNewChat();" data-dismiss="modal">Proceed</button>

            </div>

        </div>

    </div>

</div>
<!-- /.container-fluid -->
<script>
    $(window).on('load', function() {
        $('#textMessage').focus();
        lastLoginDate('<?php echo ($userLastLogin); ?>');
        singleConversationID = '<?= $singleConversationID ?>';

        msgInterval = setInterval(function() {
            fetchMessages(singleConversationID, userId);
        }, 1000);

    });

    $('#OpenImgUpload').click(function() {
        $('#imgupload').trigger('click');
    });

    function imageUpload(input) {

        $("#imgform").submit();
    }

    $("#imgform").on("submit", (e) => {
        e.preventDefault();

        var exttype = $('#imgupload').val().split('.').pop().toLowerCase();
        if ($.inArray(exttype, ['png', 'jpg', 'jpeg']) == -1) {
            const Toasti = Swal.mixin({
                toast: true,
                position: 'top',
                showConfirmButton: false,
                timer: 5000
            });
            Toasti.fire({
                type: 'error',
                title: "File type not allowed",
            });
            return;
        }
        $("#overlay").show('slow');
        let file = document.getElementById("imgupload").files[0];
        let fileName = file.name;
        let nameParts = fileName.split('.');
        let ext = nameParts[nameParts.length - 1];
        let newFileName = Date.now().toString();
        newFileName = newFileName + '.' + ext;

        let uploadTask = storageRef.child('AdminChats/' + newFileName).put(file);
        let bar = new ldBar("#imgUploadProgress");


        uploadTask.on('state_changed',
            (snapshot) => {

                progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
                bar.set(progress);

            },
            (error) => {
                console.log('Error message : ' + error.message)
            },
            async () => {
                await uploadTask.snapshot.ref.getDownloadURL().then((downloadURL) => {
                    let messageId = Date.now();

                    const imageMessage = {
                        content: downloadURL,
                        messageId: messageId.toString(),
                        timestamp: messageId,
                        fromID: myid,
                        toID: userId,
                        isRead: false,
                        type: 'image'
                    }

                    db.collection('AdminChats').doc(singleConversationID.toString()).set({
                        lastMessage: imageMessage
                    }, {
                        merge: true
                    })
                    db.collection('AdminChats').doc(singleConversationID.toString()).collection('Conversations').doc(messageId.toString()).set(imageMessage);


                });
                $("#overlay").hide(3000);
                document.getElementById("imgupload").value = null;


            }
        );


    });

    async function deleteMessage(msgId, conversationID) {
        msgId = String(msgId);
        conversationID = String(conversationID);
        await db.collection('AdminChats').doc(conversationID).collection('Conversations').doc(msgId).delete();
    }

    function insertMessage() {

        let msg = $('#textMessage').val();
        if (msg.trim() == '') {
            return false;
        }
        $('#textMessage').val("");
        sendMessage(msg);
    }

    function lastLoginDate(lastLogin) {
        lastlogin = new Date(lastLogin);
        lastLogin = lastlogin.toLocaleString('en-US', {
            'weekday': 'short',
            'year': 'numeric',
            'month': 'short',
            'hour12': true,
            'day': 'numeric',
            'hour': '2-digit',
            'minute': '2-digit',
            'second': '2-digit',
        });
        document.getElementById('lastStaffLogin').innerText = 'Last seen: ' + (lastLogin != 'Invalid Date' ? lastLogin : '');
    }

    function selectStaff(stid, chatName, el, userLastLogin, conId) {
        $('.messages-content div').html('');
        userId = stid;
        singleConversationID = conId;
        lastLoginDate(userLastLogin);
        document.querySelectorAll('.stafflist').forEach(function(staffli) {
            staffli.classList.remove('active');
        });
        el.classList.add('active');

        $('#chatingStaff').html(chatName);
        $('#textMessage').focus();


    }

    async function addNewChat() {
        let chatName = $("#staffSelect option:selected").text();
        let optval = $("#staffSelect option:selected").val();
        let splittedArray = optval.split("@");
        let addStaffID = splittedArray[0];
        userId = addStaffID;
        let lastSeen = splittedArray[1];
        lastLoginDate(lastSeen);
        let chatAvatarNum = Math.floor(Math.random() * 7) + 1;
        let newConversationID = Date.now();
        singleConversationID = newConversationID.toString();

        const chatRef = await db.collection('AdminChats').doc(newConversationID.toString()).set({
            chatType: 'one',
            conversationID: newConversationID.toString(),
            participants: {
                [myid]: true,
                [addStaffID]: true
            }
        });

        let messageID = Date.now();

        const lastMessage = {
            content: `Hello ${chatName}`,
            fromID: myid,
            toID: addStaffID,
            isRead: false,
            messageId: messageID.toString(),
            timestamp: messageID,
            type: 'text'

        }

        const lastMessageRef = await db.collection('AdminChats').doc(newConversationID.toString()).set({
            lastMessage: lastMessage,
        }, {
            merge: true
        });

        const messageRef = await db.collection('AdminChats').doc(newConversationID.toString()).collection('Conversations').doc(messageID.toString()).set(lastMessage);



        document.querySelectorAll('.stafflist').forEach(function(staffli) {
            staffli.classList.remove('active');
        });

        const newChatElement = `
    <li data-conversationid="${newConversationID}" id="clist-${addStaffID}" class="clearfix stafflist active" onclick="selectStaff('${addStaffID}', '${chatName}', this, '${lastSeen}', '${newConversationID}');">

        <img src="https://bootdey.com/img/Content/avatar/avatar${chatAvatarNum}.png" alt="avatar" />

        <div class="about">

            <div class="name">${chatName}</div>

            <div class="status">

                <i class="fa fa-circle online"></i> online

            </div>

        </div>
        <i class="fa fa-trash" onclick="removeChatStaff('${addStaffID}', '${newConversationID}');" title="Remove from chat"></i>
    </li>

    `;

        $('#chatingStaff').html(chatName);

        $('#chatListItemOne').after(newChatElement);
        $("#" + addStaffID).remove();
        $('#textMessage').focus();
        // $('.modal').modal('hide');

    }

    function removeChatStaff(id, conid) {

        let thisLi = $("#clist-" + id);

        if (thisLi.siblings().length == 1) {
            userId = '';
            singleConversationID = '';

            $('.messages-content').empty();
            $('#chatingStaff').html("");
            document.getElementById('lastStaffLogin').innerText = "";


        } else if (thisLi.is(':last-child')) {
            let nextLiID = thisLi.prev('li').prop('id');
            $("#" + nextLiID).addClass('active');
            let nextStaffID = nextLiID.substring(6);
            userId = nextStaffID;
            singleConversationID = $("#" + nextLiID).attr('data-conversationid')

            let newStaffLastLogin = allUsers[nextStaffID].userLastLogin;
            lastLoginDate(newStaffLastLogin);
            let newStaffName = allUsers[nextStaffID].userName;
            $('#chatingStaff').html(newStaffName.trim());

            $('.messages-content').empty();
        } else {
            let nextLiID = thisLi.next('li').prop('id');
            $("#" + nextLiID).addClass('active');
            let nextStaffID = nextLiID.substring(6);
            userId = nextStaffID;
            singleConversationID = $("#" + nextLiID).attr('data-conversationid')


            let newStaffLastLogin = allUsers[nextStaffID].userLastLogin;
            lastLoginDate(newStaffLastLogin);
            let newStaffName = allUsers[nextStaffID].userName;
            $('#chatingStaff').html(newStaffName.trim());


            $('.messages-content').empty();
        }

        $.ajax({
            type: "POST",
            url: "<?php echo base_url(); ?>" + "chat/deletechat",
            data: {
                "chatid": conid,
            },

            success: function(res) {
                if (res) {
                    console.log(res);
                }
            }
        });


        let staffRestore = `<option id="${id}" value = "${id}@${allUsers[id]['userLastLogin']}" > ${allUsers[id]['userName']} </option>`;
        $(staffRestore).appendTo($('#staffSelect'));

        thisLi.remove();
        $('#textMessage').focus();

        const Toasti = Swal.mixin({
            toast: true,
            position: 'top',
            showConfirmButton: false,
            timer: 5000
        });
        Toasti.fire({
            type: 'success',
            title: "User chat history removed successfully"
        });

        window.event.cancelBubble = true;
    }
</script>