<?php

$title = 'Trang Chat - ' . $DVR->site('site_ten');
$body['header'] = '';
$body['footer'] = '';
require_once __DIR__ . '/../../../core/is_user.php';
require_once __DIR__ . '/header.php';
require_once __DIR__ . '/nav.php';
CheckLogin();

?>
<style>
    body, html {
        margin: 0;
        padding: 0;
        overflow-x: hidden;
        background-color: #f8f9fa;
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    }

    #main {
        margin-top: 20px;
        margin-bottom: 60px;
    }

    .chat-box {
        border: 1px solid #ddd;
        border-radius: 8px;
        padding: 15px;
        height: 400px;
        overflow-y: auto;
        background-color: white;
        margin-bottom: 15px;
        transition: box-shadow 0.3s ease;
        display: flex;
        flex-direction: column-reverse;
    }

    .chat-messages {
        display: flex;
        flex-direction: column-reverse;
    }

    .chat-message {
        margin-bottom: 5px;
        padding: 10px;
        border-radius: 8px;
        font-size: 14px;
        max-width: 60%;
        clear: both;
        position: relative;
    }

    .justify-content-end .chat-message {
        align-self: flex-end;
        background-color: #cfe9ff; /* Màu nền cho tin nhắn của người dùng hiện tại */
    }

    .justify-content-start .chat-message {
        align-self: flex-start;
        background-color: #f1f1f1; /* Màu nền cho tin nhắn của người dùng khác */
    }

    .chat-message .message-time {
        font-size: 12px;
        color: #888;
        position: absolute;
        bottom: 5px;
        right: 10px;
        margin-top: 5px; /* Thêm margin để tách ngày và giờ */
        display: block; /* Đảm bảo thời gian hiển thị ở dòng mới */
    }

    .input-group {
        max-width: 600px;
        margin: auto;
    }

    #chatInput {
        border-radius: 20px;
        padding: 10px 15px;
    }

    #sendBtn {
        border-radius: 20px;
        margin-left: 10px;
        font-size: 16px;
        padding: 8px 16px;
    }
</style>

<div id="app">
    <div id="main" class="main">
        <div class="container">
            <div class="row">
                <div class="col-12">
                    <div class="section-heading text-center">
                        <div class="title">CỘNG ĐỒNG <?=$DVR->site('site_ten');?></div>
                    </div>
                </div>
            </div>

            <div class="row justify-content-center">
                <div class="col-lg-8">
                    <div class="chat-box shadow-sm rounded" id="chatBox">
                        <div class="chat-messages" id="chatMessages">
                            <div v-for="msg in messages" :key="msg.msg_id" class="d-flex justify-content-start my-2">
                                <div class="p-2 bg-light rounded">
                                    <strong>{{ msg.incoming_msg_id }}:</strong> {{ msg.msg }}
                                    <div class="message-time">{{ formatDate(msg.date) }}</div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <form @submit.prevent="sendMessage">
                        <div class="input-group mt-3">
                            <input type="text" id="chatInput" class="form-control" v-model="newMessage" placeholder="Nhập tin nhắn...">
                            <button class="btn btn-primary" id="sendBtn" type="submit">
                                <i class="fas fa-paper-plane"></i> Gửi
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<script>
    new Vue({
        el: '#app',
        data: {
            messages: [],
            newMessage: '',
            outgoing_msg_id: 1, 
            incoming_msg_id: '<?php echo $getUser['username']; ?>', 
        },
        mounted() {
            this.fetchMessages();
            setInterval(this.fetchMessages, 3000); 
        },
        methods: {
            fetchMessages() {
                fetch(`/ajaxs/client/fetch.php?outgoing_msg_id=${this.outgoing_msg_id}&incoming_msg_id=${this.incoming_msg_id}`)
                    .then(response => response.json())
                    .then(data => {
                        this.messages = data;
                    });
            },
            sendMessage() {
                if (this.newMessage.trim() === '') return;

                const formData = new FormData();
                formData.append('outgoing_msg_id', this.outgoing_msg_id);
                formData.append('incoming_msg_id', this.incoming_msg_id);
                formData.append('msg', this.newMessage);

                fetch('/ajaxs/client/send.php', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.status === 'success') {
                        this.newMessage = '';
                        this.fetchMessages(); 
                    } else {
                        console.error('Send error:', data.message);
                    }
                })
                .catch(error => console.error('Fetch error:', error));
            },
            formatDate(timestamp) {
                if (!timestamp) return ''; 
                const date = new Date(timestamp * 1000); 
                return date.toLocaleString('vi-VN', { 
                    hour: '2-digit', minute: '2-digit', 
                    day: '2-digit', month: '2-digit', year: 'numeric' 
                });
            }
        }
    });
</script>

<?php require_once __DIR__ . '/footer.php'; ?>
