<?php
require_once('../includes/functions.php');
if (!isset($_SESSION['user_id']) || $_SESSION['role'] != 'employee') {
    header("Location: ../login.php");
    exit();
}
$userId = $_SESSION['user_id'];
$user = getUserById($userId);
$chatGroups = getChatGroups();
?>
<?php include('../includes/header.php'); ?>
<style>
    .chat-container {
        display: flex;
        flex-direction: column;
        height: 65vh;
        background: white;
        border-radius: 20px;
        border: 1px solid #e2cfb3;
        overflow: hidden;
    }
    .chat-sidebar {
        background: #faf3e8;
        border-bottom: 1px solid #e2cfb3;
        padding: 12px;
        display: flex;
        overflow-x: auto;
        gap: 8px;
    }
    .group-btn {
        background: #ede3d4;
        border: 1px solid #d4bc9a;
        padding: 8px 16px;
        border-radius: 40px;
        cursor: pointer;
        white-space: nowrap;
        font-size: 0.85rem;
        transition: 0.2s;
    }
    .group-btn.active {
        background: #6b1d2f;
        color: #f9e4c2;
        border-color: #c9a87c;
    }
    .chat-messages {
        flex: 1;
        overflow-y: auto;
        padding: 16px;
        background: #fefcf8;
        display: flex;
        flex-direction: column;
        gap: 12px;
    }
    .message {
        max-width: 80%;
        padding: 8px 12px;
        border-radius: 18px;
        background: white;
        border: 1px solid #e2cfb3;
        align-self: flex-start;
    }
    .message-mine {
        background: #e3d9cd;
        align-self: flex-end;
        border-color: #c9a87c;
    }
    .message-name {
        font-weight: bold;
        color: #6b1d2f;
        font-size: 0.75rem;
        margin-bottom: 4px;
    }
    .message-text {
        font-size: 0.9rem;
        word-break: break-word;
    }
    .message-time {
        font-size: 0.65rem;
        color: #8b7355;
        text-align: right;
        margin-top: 4px;
    }
    .message-file {
        margin-top: 6px;
    }
    .message-file a {
        color: #6b1d2f;
        text-decoration: none;
        background: #f8efe5;
        padding: 4px 8px;
        border-radius: 20px;
        font-size: 0.75rem;
        display: inline-block;
    }
    .chat-input-area {
        padding: 12px;
        background: #faf3e8;
        border-top: 1px solid #e2cfb3;
        display: flex;
        gap: 8px;
        flex-wrap: wrap;
    }
    .chat-input-area input[type="text"] {
        flex: 1;
        margin: 0;
        padding: 10px;
        border-radius: 40px;
        border: 1px solid #d4bc9a;
    }
    .chat-input-area input[type="file"] {
        display: none;
    }
    .file-label {
        background: #c9a87c;
        color: #2c1e12;
        padding: 10px 15px;
        border-radius: 40px;
        cursor: pointer;
        font-size: 0.85rem;
    }
    .send-btn {
        background: #6b1d2f;
        color: #f9e4c2;
        border: none;
        padding: 10px 20px;
        border-radius: 40px;
        cursor: pointer;
    }
    @media (max-width: 640px) {
        .message { max-width: 90%; }
        .group-btn { font-size: 0.75rem; padding: 6px 12px; }
    }
</style>
<div class="sidebar">
    <h3>✈️ Crew Menu</h3>
    <a href="dashboard.php" class="btn">🏠 Dashboard</a>
    <a href="view_memos.php" class="btn">📝 Memos</a>
    <a href="take_quiz.php" class="btn">📚 Quizzes</a>
    <a href="safety_report.php" class="btn">⚠️ Safety Report</a>
    <a href="my_reports.php" class="btn">📋 My Reports</a>
    <a href="chat.php" class="btn active">💬 Group Chat</a>
    <a href="profile.php" class="btn">👤 Profile</a>
    <a href="view_manual.php" class="btn">📘 Maintenance Manual</a>
</div>
<div class="content">
    <h2>💬 Group Chat</h2>
    <div class="chat-container">
        <div class="chat-sidebar" id="groupSidebar">
            <?php foreach($chatGroups as $display => $code): ?>
                <button class="group-btn" data-group="<?php echo $display; ?>"><?php echo $display; ?></button>
            <?php endforeach; ?>
        </div>
        <div class="chat-messages" id="chatMessages">
            <div class="message">Select a group to start chatting</div>
        </div>
        <div class="chat-input-area" id="chatInput" style="display: none;">
            <input type="text" id="messageInput" placeholder="Type your message...">
            <label class="file-label">📎 Attach<input type="file" id="fileInput" accept="image/*,application/pdf,.txt"></label>
            <button class="send-btn" id="sendBtn">Send</button>
        </div>
    </div>
</div>
<script>
    let currentGroup = null;
    let lastMessageId = 0;
    let pollingInterval = null;
    
    function selectGroup(group) {
        currentGroup = group;
        document.querySelectorAll('.group-btn').forEach(btn => {
            btn.innerText === group ? btn.classList.add('active') : btn.classList.remove('active');
        });
        document.getElementById('chatInput').style.display = 'flex';
        document.getElementById('chatMessages').innerHTML = '<div class="message">Loading messages...</div>';
        lastMessageId = 0;
        loadMessages();
        if (pollingInterval) clearInterval(pollingInterval);
        pollingInterval = setInterval(loadMessages, 3000);
    }
    
    function loadMessages() {
        if (!currentGroup) return;
        fetch(`../chat_api.php?action=fetch&group=${encodeURIComponent(currentGroup)}&last_id=${lastMessageId}`)
            .then(res => res.json())
            .then(data => {
                if (data.messages && data.messages.length > 0) {
                    const container = document.getElementById('chatMessages');
                    data.messages.forEach(msg => {
                        lastMessageId = Math.max(lastMessageId, msg.id);
                        const isMine = (msg.display_name === '<?php echo !empty($user['amo_stamp_number']) ? $user['amo_stamp_number'] : $user['username']; ?>');
                        const msgDiv = document.createElement('div');
                        msgDiv.className = `message ${isMine ? 'message-mine' : ''}`;
                        let fileHtml = '';
                        if (msg.file) {
                            const fileUrl = `../${msg.file}`;
                            const isImage = /\.(jpg|jpeg|png|gif|webp)$/i.test(msg.file);
                            if (isImage) {
                                fileHtml = `<div class="message-file"><a href="${fileUrl}" target="_blank">📷 View Image</a></div>`;
                            } else {
                                fileHtml = `<div class="message-file"><a href="${fileUrl}" target="_blank">📎 Download Attachment</a></div>`;
                            }
                        }
                        msgDiv.innerHTML = `
                            <div class="message-name">${msg.display_name}</div>
                            <div class="message-text">${msg.message}</div>
                            ${fileHtml}
                            <div class="message-time">${msg.timestamp}</div>
                        `;
                        container.appendChild(msgDiv);
                    });
                    container.scrollTop = container.scrollHeight;
                }
            });
    }
    
    document.getElementById('groupSidebar').addEventListener('click', (e) => {
        if (e.target.classList.contains('group-btn')) {
            selectGroup(e.target.innerText);
        }
    });
    
    document.getElementById('sendBtn').addEventListener('click', () => {
        if (!currentGroup) return alert('Select a group first');
        const messageInput = document.getElementById('messageInput');
        const fileInput = document.getElementById('fileInput');
        const message = messageInput.value.trim();
        if (!message && !fileInput.files.length) return;
        
        const formData = new FormData();
        formData.append('action', 'send');
        formData.append('group', currentGroup);
        formData.append('message', message);
        if (fileInput.files[0]) formData.append('file', fileInput.files[0]);
        
        fetch('../chat_api.php', { method: 'POST', body: formData })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    messageInput.value = '';
                    fileInput.value = '';
                    loadMessages();
                } else {
                    alert('Error: ' + data.error);
                }
            });
    });
    
    document.getElementById('messageInput').addEventListener('keypress', (e) => {
        if (e.key === 'Enter') document.getElementById('sendBtn').click();
    });
</script>
<div class="clearfix"></div>
<?php include('../includes/footer.php'); ?>