<?php
if ($ipAddress == "127.0.0.1" || $ipAddress == "::1") {
    $conn = mysqli_connect("localhost", "root", "", "dha");
} else {
    $conn = mysqli_connect("localhost", "dzvisual_admin", "Farhan@123456", "dzvisual_homestay");
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>DzV Comm</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="style.css">
    <script>
        $(document).ready(function () {
            // Get the chatId from the URL parameters
            var urlParams = new URLSearchParams(window.location.search);
            var chatId = urlParams.get('chatId');

            if (chatId) {
                console.log('Received chatId:', chatId);
                // Call getMessageHistory function with the received chatId
                getMessageHistory(chatId);
                activeChatId = chatId;
                $('#inputChatId').val(chatId);
                $('#userName').html(chatId);
            }

            // Function to fetch data from the server
            function fetchData() {
                $.ajax({
                    url: 'fetch_data.php',
                    type: 'GET',
                    success: function (response) {
                        // Clear the existing chat list
                        $('.chat-list').empty();

                        // Loop through the response data and construct HTML for each chat item
                        response.forEach(function (chat) {
                            var statusIcon = chat.status === 'online' ? 'fa fa-circle online' : 'fa fa-circle offline';
                            var statusText = chat.status === 'online' ? 'online' : 'offline';

                            var chatItem = '<li id="' + chat.tg_chat_id + '" class="clearfix">' +
                                '<img src="https://bootdey.com/img/Content/avatar/avatar1.png" alt="avatar">' +
                                '<div class="about">' +
                                '<div class="name">' + chat.tg_chat_id + '</div>' +
                                '<div class="status"> <i class="' + statusIcon + '"></i> ' + statusText + '</div>' +
                                '</div>' +
                                '</li>';

                            // Append the constructed HTML to the chat list
                            $('.chat-list').append(chatItem);
                        });

                        // Attach click event listener to chat items
                        $('.chat-list li').click(function () {
                            var chatId = $(this).attr('id');
                            activeChatId = chatId;
                            console.log('Clicked on chat item:', chatId);
                            // Set the chatId value into the message input
                            $('#inputChatId').val(chatId);
                            $('#userName').html(chatId);

                            getMessageHistory(chatId);
                        });
                    }
                });
            }

            function getMessageHistory(chatId) {
                // Make an AJAX request to fetch chat history for the clicked chat item
                $.ajax({
                    url: 'fetch_chat_history.php', // Update with the correct URL
                    type: 'GET',
                    data: { chatId: chatId },
                    success: function (chatHistory) {
                        // Construct HTML for the chat history
                        var chatHistoryHtml = '<ul class="m-b-0">';

                        chatHistory.forEach(function (message) {
                            var messageHtml = '<li class="clearfix">' +
                                '<div class="message-data ' + (message.receive_send == 2 ? 'text-right' : '') + '">' +
                                '<span class="message-data-time">' + message.time + '</span>' +
                                '</div>' +
                                '<div class="message ' + (message.receive_send == 2 ? 'my-message float-right' : 'other-message float-left') + '">' +
                                message.content +
                                '</div>' +
                                '</li>';
                            chatHistoryHtml += messageHtml;
                        });

                        chatHistoryHtml += '</ul>';

                        // Replace the existing chat history with the new HTML
                        $('.chat-history').html(chatHistoryHtml);
                        var chatHistory2 = $('.chat-history');
                        chatHistory2.scrollTop(chatHistory2.prop("scrollHeight"));
                    }
                });
            }

            // Fetch data initially
            fetchData();

            // Fetch data every 5 seconds
            setInterval(fetchData, 500);

            // Function to fetch message history every 5 seconds
            setInterval(function () {
                // var activeChatId = $('.chat-list li.active').attr('id');
                if (activeChatId) {
                    // Fetch message history for the active chat item
                    getMessageHistory(activeChatId);
                }
            }, 500); // Adjust the interval as needed
        });

        $(document).ready(function () {
            $('#messageInput').keypress(function (event) {
                // Check if the Enter key (key code 13) is pressed
                if (event.which === 13) {
                    // Prevent the default action of the Enter key (submitting the form)
                    event.preventDefault();

                    // Get the message input value
                    var message = $('#messageInput').val();
                    // Get the chatId from the data attribute
                    var chatId = $('#inputChatId').val();

                    console.log("Sending message to Telegram:", message);
                    console.log("Chat id is ", chatId);

                    // Make an AJAX request to send the message to Telegram
                    $.ajax({
                        url: 'send_message_to_telegram.php', // Update with the correct URL
                        type: 'POST',
                        data: {
                            message: message,
                            chatId: chatId
                        },
                        success: function (response) {
                            // Handle success response if needed
                            console.log("Message sent successfully:", response);
                        },
                        error: function (xhr, status, error) {
                            // Handle error if needed
                            console.error("Error sending message:", xhr.responseText);
                        }
                    });

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

    </script>
</head>

<body>
    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
    <div class="container">
        <div class="row clearfix">
            <div class="col-lg-12">
                <div class="card chat-app">
                    <div id="plist" class="people-list">
                        <div class="input-group">
                            <div class="input-group-prepend">
                                <span class="input-group-text"><i class="fa fa-search"></i></span>
                            </div>
                            <input type="text" class="form-control" placeholder="Search...">
                        </div>
                        <ul class="list-unstyled chat-list mt-2 mb-0">
                            <li class="clearfix">
                                <img src="https://bootdey.com/img/Content/avatar/avatar1.png" alt="avatar">
                                <div class="about">
                                    <div class="name">Vincent Porter</div>
                                    <div class="status"> <i class="fa fa-circle offline"></i> left 7 mins ago </div>
                                </div>
                            </li>
                            <li class="clearfix active">
                                <img src="https://bootdey.com/img/Content/avatar/avatar2.png" alt="avatar">
                                <div class="about">
                                    <div class="name">Aiden Chavez</div>
                                    <div class="status"> <i class="fa fa-circle online"></i> online </div>
                                </div>
                            </li>
                            <li class="clearfix">
                                <img src="https://bootdey.com/img/Content/avatar/avatar3.png" alt="avatar">
                                <div class="about">
                                    <div class="name">Mike Thomas</div>
                                    <div class="status"> <i class="fa fa-circle online"></i> online </div>
                                </div>
                            </li>
                            <li class="clearfix">
                                <img src="https://bootdey.com/img/Content/avatar/avatar7.png" alt="avatar">
                                <div class="about">
                                    <div class="name">Christian Kelly</div>
                                    <div class="status"> <i class="fa fa-circle offline"></i> left 10 hours ago </div>
                                </div>
                            </li>
                            <li class="clearfix">
                                <img src="https://bootdey.com/img/Content/avatar/avatar8.png" alt="avatar">
                                <div class="about">
                                    <div class="name">Monica Ward</div>
                                    <div class="status"> <i class="fa fa-circle online"></i> online </div>
                                </div>
                            </li>
                            <li class="clearfix">
                                <img src="https://bootdey.com/img/Content/avatar/avatar3.png" alt="avatar">
                                <div class="about">
                                    <div class="name">Dean Henry</div>
                                    <div class="status"> <i class="fa fa-circle offline"></i> offline since Oct 28
                                    </div>
                                </div>
                            </li>
                        </ul>
                    </div>
                    <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="userName">Unamed</h6>
                                        <small>Last seen: 2 hours ago</small>
                                    </div>
                                </div>
                                <div class="col-lg-6 hidden-sm text-right">
                                    <a href="javascript:void(0);" class="btn btn-outline-secondary"><i
                                            class="fa fa-camera"></i></a>
                                    <a href="javascript:void(0);" class="btn btn-outline-primary"><i
                                            class="fa fa-image"></i></a>
                                    <a href="javascript:void(0);" class="btn btn-outline-info"><i
                                            class="fa fa-cogs"></i></a>
                                    <a href="javascript:void(0);" class="btn btn-outline-warning"><i
                                            class="fa fa-question"></i></a>
                                </div>
                            </div>
                        </div>
                        <div class="chat-history">
                            <ul class="m-b-0">
                                <li class="clearfix">
                                    <div class="message-data text-right">
                                        <span class="message-data-time">10:10 AM, Today</span>
                                        <img src="https://bootdey.com/img/Content/avatar/avatar7.png" alt="avatar">
                                    </div>
                                    <div class="message other-message float-right"> Hi Aiden, how are you? How is the
                                        project coming along? </div>
                                </li>
                                <li class="clearfix">
                                    <div class="message-data">
                                        <span class="message-data-time">10:12 AM, Today</span>
                                    </div>
                                    <div class="message my-message">Are we meeting today?</div>
                                </li>
                                <li class="clearfix">
                                    <div class="message-data">
                                        <span class="message-data-time">10:15 AM, Today</span>
                                    </div>
                                    <div class="message my-message">Project has been already finished and I have results
                                        to show you.</div>
                                </li>
                            </ul>
                        </div>
                        <div class="chat-message clearfix">
                            <div class="input-group mb-0">
                                <div class="input-group-prepend">
                                    <span class="input-group-text"><i class="fa fa-send"></i></span>
                                </div>
                                <input type="hidden" id="inputChatId" name="chatId" value="">
                                <input id="messageInput" type="text" class="form-control"
                                    placeholder="Enter text here...">
                            </div>
                        </div>

                    </div>
                </div>
            </div>
        </div>
    </div>
    <script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.0/dist/js/bootstrap.bundle.min.js"></script>
    <script type="text/javascript">

    </script>
</body>

</html>