<?php $this->include('rs/utils.php')?>
<?= $this->extend('rs/template-user'); ?>
<?= $this->section('content'); ?>

  
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.css" rel="stylesheet">

<style>
    @media (max-width: 768px) {
        #thread-sidebar {
            height: 50vh;
            overflow-y: auto;
        }
        #chat-window {
            height: 50vh;
        }
    }

    @media (min-width: 768px) {
        #thread-sidebar {
            height: 100%;
        }
        #chat-window {
            height: 100%;
        }
    }

    #chat-body {
        height: calc(100vh - 130px); /* Dynamically adjust for header/footer */
        overflow-y: auto;
    }




    /* Button styling */
    button.toggle-sidebar {
        border: none;
        background-color: transparent;
        font-size: 1.5rem;
        display: flex;
        align-items: center;
        justify-content: center;
        width: 40px;
        height: 40px;
        margin: auto;
        transition: transform 0.3s ease-in-out;
    }

    button.toggle-sidebar i {
        transition: transform 0.3s ease-in-out;
    }

    button.toggle-sidebar.collapsed i {
        transform: rotate(180deg); /* Up arrow when collapsed */
    }
    .badge {
    min-width: 20px;
    height: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
}

.list-group-item {
    transition: background-color 0.2s;
    word-wrap: break-word;
    overflow-wrap: break-word;
}

.list-group-item:hover {
    background-color: rgba(0,0,0,0.03);
}
.latest-message {
    max-width: 200px;
}

</style>
<div class="container-fluid mb-3">
    <div class="row">
        <!-- Toggle Button for Conversations Bar (Small Screens) -->
        <button class="btn btn-light d-md-none my-2 p-0 toggle-sidebar" data-bs-toggle="collapse" data-bs-target="#thread-sidebar" aria-expanded="true" aria-label="Toggle Conversations">
            <i class="bi bi-chevron-up"></i>
        </button>

        <!-- Sidebar -->
        <div class="col-md-3 collapse show d-md-block border-end bg-light overflow-auto p-2" id="thread-sidebar">
            <h5 class="mb-3">Conversations</h5>
            <ul class="list-group list-group-flush">
                <?php if (!empty($threads)): ?>
                    <?php foreach ($threads as $thread): ?>
                        <li class="list-group-item list-group-item-action py-2 thread-item" data-thread-id="<?= $thread['thread_id'] ?>">
                            <div class="d-flex justify-content-between align-items-start w-100">
                                <div class="d-flex flex-grow-1 flex-column w-100">
                                    <strong class="text-truncate"><?= $thread['other_user_name'] ?></strong>
                                    <small class="text-truncate text-muted latest-message"><?= $thread['latest_message'] ?></small>
                                    <small class="text-muted latest-message-time"><?= $thread['latest_message_time'] ?></small>
                                </div>
                                <?php if ($thread['unread_messages'] > 0): ?>
                                    <span class="badge rounded-pill bg-danger px-2 py-1" style="font-size: 0.75rem;"><?= $thread['unread_messages'] ?></span>
                                <?php endif; ?>
                            </div>
                        </li>
                    <?php endforeach; ?>
                <?php else: ?>
                    <p class="text-muted">No conversations found.</p>
                <?php endif; ?>
            </ul>
        </div>
        <!-- Chat Window -->
        <div class="col-md-9 col-12 p-2 bg-white d-flex flex-column" id="chat-window">
            <div id="chat-header" class="border-bottom p-3 bg-white shadow-sm">
                <h4 id="chat-title" class="mb-0">Select a conversation</h4>
            </div>
            <div id="chat-body" class="flex-grow-1 overflow-auto p-3">
                <p class="text-center text-muted mt-4">Select a conversation to view messages</p>
            </div>
            <div id="chat-footer" class="border-top p-3 bg-white">
                <form id="sendMessageForm" class="d-flex w-100">
                    <input type="hidden" name="thread_id" id="thread_id">
                    <textarea name="message" id="message" class="form-control me-2 flex-grow-1" rows="1" placeholder="Type your message..." required></textarea>
                    <button type="submit" class="btn btn-primary">Send</button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- If the controller sends a thread ID, set it as active -->
<?php if (isset($active_thread)): ?>
    <script>
        $('body').data('active-thread', <?= $active_thread ?>);
        console.log(<?= $active_thread ?>);
    </script>
<?php endif; ?>

<script>
$(document).ready(function () {


    function getMessagesAndSetUI(threadId) {
        $.ajax({
            url: '/messages/getMessages',
            type: 'GET',
            data: { thread_id: threadId },
            success: function (response) {
                if (response.status === 'success') {
                    const messages = response.messages;
                    $('#chat-title').text('Conversation with ' + response.other_user_name);
                    $('#chat-body').html('');

                    messages.forEach(message => {
                        const isCurrentUser = message.sender_id === response.current_user_id;
                        $('#chat-body').append(`
                            <div class="d-flex mb-3 ${isCurrentUser ? 'justify-content-start' : 'justify-content-end'}">
                                <div class="d-inline-block p-2 rounded ${isCurrentUser ? 'bg-primary text-white' : 'bg-light'}">
                                    <strong>${isCurrentUser ? 'You' : response.other_user_name}:</strong>
                                    <p class="mb-1">${message.message}</p>
                                    <small class="${isCurrentUser ? 'text-white-50' : 'text-muted'}">${message.created_at}</small>
                                </div>
                            </div>
                        `);
                    });

                    $('#chat-body').scrollTop($('#chat-body')[0].scrollHeight);
                } else {
                    alert('Failed to load messages');
                }
            },
            error: function () {
                alert('An error occurred while loading the conversation.');
            }
        });

        $('.thread-item').removeClass('active bg-primary text-white');
        $(`[data-thread-id="${threadId}"]`).addClass('active bg-primary text-white');
    }

    $('.thread-item').on('click', function () {
        const threadId = $(this).data('thread-id');
        $('#thread_id').val(threadId);

        getMessagesAndSetUI(threadId);
    });

    // If a conversation is already active, fetch and display its messages
    const activeThread = $('body').data('active-thread');
    if (activeThread) {
        
        $('#thread_id').val(activeThread);
        getMessagesAndSetUI(activeThread);
    }

    $('#sendMessageForm').on('submit', function (e) {
        e.preventDefault();
        
        const formData = {
            thread_id: $('#thread_id').val(),
            message: $('#message').val().trim()
        };

        if (!formData.thread_id || !formData.message) {
            alert('Please select a conversation and enter a message');
            return;
        }

        $.ajax({
            url: '/messages/sendMessage',
            type: 'POST',
            data: formData,
            dataType: 'json',
            success: function (response) {
                if (response.status === 'success') {
                    const newMessage = response.message;
                    $('#chat-body').append(`
                        <div class="d-flex mb-3 justify-content-start">
                            <div class="d-inline-block p-2 rounded bg-primary text-white">
                                <strong>You:</strong>
                                <p class="mb-1">${newMessage.message}</p>
                                <small class="text-white-50">${newMessage.created_at}</small>
                            </div>
                        </div>
                    `);
                    $('#message').val('');
                    $('#chat-body').scrollTop($('#chat-body')[0].scrollHeight);
                } else {
                    alert('Error: ' + JSON.stringify(response.errors));
                }
            },
            error: function (xhr) {
                alert('An error occurred while sending the message.');
                console.log(xhr.responseText);
            }
        });
    });

        // Send Message on Enter Key Press
    $('#message').on('keypress', function (e) {
        if (e.which === 13 && !e.shiftKey) { // Enter without Shift
            e.preventDefault();
            $('#sendMessageForm').submit();
        }
    });
});
</script>


<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.8/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.min.js"></script>
<!--   
	  <div class="card shadow mb-4">
		<div class="card-header py-3">
		<h4 class="m-0 font-weight-bold text-primary">Messages</h4>
			In construction. Comming soon.
		</div>
		<div class="card-body">
						
			
		</div>
	</div> -->

			
		<!-- /.container-fluid -->

		
		<!-- End of Main Content -->

		<!-- Footer -->
		

<?= $this->endsection(); ?>