<?php
session_start();
if (!isset($_SESSION['nurse_id'])) {
    header("Location: login.php");
    exit();
}
include '../include/config.php';

$nurse_id = $_SESSION['nurse_id'];
$nurse_name = $_SESSION['nurse_name'];

// Get all conversations for this nurse
$conversations = $conn->query("
    SELECT DISTINCT 
        CASE 
            WHEN cm.sender_id = $nurse_id AND cm.sender_type = 'nurse' THEN cm.receiver_id
            WHEN cm.receiver_id = $nurse_id AND cm.receiver_type = 'nurse' THEN cm.sender_id
            ELSE NULL
        END as other_person_id,
        CASE 
            WHEN cm.sender_id = $nurse_id AND cm.sender_type = 'nurse' THEN cm.receiver_type
            WHEN cm.receiver_id = $nurse_id AND cm.receiver_type = 'nurse' THEN cm.sender_type
            ELSE NULL
        END as other_person_type,
        (SELECT message FROM chat_messages 
         WHERE ((sender_id = cm.sender_id AND receiver_id = cm.receiver_id AND sender_type = cm.sender_type AND receiver_type = cm.receiver_type)
             OR (sender_id = cm.receiver_id AND receiver_id = cm.sender_id AND sender_type = cm.receiver_type AND receiver_type = cm.sender_type))
         ORDER BY created_at DESC LIMIT 1) as last_message,
        (SELECT created_at FROM chat_messages 
         WHERE ((sender_id = cm.sender_id AND receiver_id = cm.receiver_id AND sender_type = cm.sender_type AND receiver_type = cm.receiver_type)
             OR (sender_id = cm.receiver_id AND receiver_id = cm.sender_id AND sender_type = cm.receiver_type AND receiver_type = cm.sender_type))
         ORDER BY created_at DESC LIMIT 1) as last_message_time,
        (SELECT COUNT(*) FROM chat_messages 
         WHERE receiver_id = $nurse_id 
         AND receiver_type = 'nurse' 
         AND sender_id = other_person_id 
         AND sender_type = other_person_type
         AND is_read = 0) as unread_count
    FROM chat_messages cm
    WHERE (cm.sender_id = $nurse_id AND cm.sender_type = 'nurse')
       OR (cm.receiver_id = $nurse_id AND cm.receiver_type = 'nurse')
    ORDER BY last_message_time DESC
");

// Get online staff/doctors/nurses for new chat
$online_doctors = $conn->query("
    SELECT doctor_id as id, name as display_name, 'doctor' as type, profile_pic 
    FROM doctors WHERE status = 'active'
");
$online_staff = $conn->query("
    SELECT staff_id as id, CONCAT(first_name, ' ', last_name) as display_name, 'staff' as type, profile_pic 
    FROM staff WHERE status = 'active'
");
$online_nurses = $conn->query("
    SELECT nurse_id as id, CONCAT(first_name, ' ', last_name) as display_name, 'nurse' as type, profile_pic 
    FROM nurses WHERE nurse_id != $nurse_id AND status = 'active'
");
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chat Center - Nurse Portal</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.6.0/css/all.min.css">
    <style>
        body { background: #f0f2f5; font-family: 'Segoe UI', sans-serif; }
        .chat-container { max-width: 1400px; margin: 0 auto; }
        .conversations-list { background: white; border-radius: 10px; height: 80vh; overflow-y: auto; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
        .chat-area { background: white; border-radius: 10px; height: 80vh; display: flex; flex-direction: column; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
        .messages-area { flex: 1; overflow-y: auto; padding: 20px; }
        .message { margin-bottom: 15px; display: flex; align-items: flex-start; }
        .message.sent { justify-content: flex-end; }
        .message.received { justify-content: flex-start; }
        .message-bubble { max-width: 70%; padding: 10px 15px; border-radius: 18px; position: relative; }
        .message.sent .message-bubble { background: #064e3b; color: white; border-bottom-right-radius: 4px; }
        .message.received .message-bubble { background: #e4e6eb; color: #050505; border-bottom-left-radius: 4px; }
        .message-time { font-size: 11px; margin-top: 5px; opacity: 0.7; display: block; }
        .chat-header { padding: 15px 20px; border-bottom: 1px solid #dee2e6; background: #064e3b; color: white; border-radius: 10px 10px 0 0; }
        .conversation-item { padding: 15px; border-bottom: 1px solid #dee2e6; cursor: pointer; transition: 0.2s; }
        .conversation-item:hover { background: #f8f9fa; }
        .conversation-item.active { background: #e8f5e9; border-left: 3px solid #064e3b; }
        .profile-pic { width: 50px; height: 50px; border-radius: 50%; object-fit: cover; background: #064e3b; color: white; display: flex; align-items: center; justify-content: center; font-size: 20px; }
        .small-pic { width: 40px; height: 40px; font-size: 16px; }
        .online-status { width: 12px; height: 12px; border-radius: 50%; background: #4caf50; border: 2px solid white; position: absolute; bottom: 0; right: 0; }
        .typing-indicator { padding: 10px; color: #666; font-style: italic; font-size: 13px; display: none; }
        .unread-badge { background: #dc3545; color: white; border-radius: 10px; padding: 2px 6px; font-size: 11px; margin-left: 5px; }
        .input-area { padding: 15px; border-top: 1px solid #dee2e6; }
        .emoji-picker { position: absolute; bottom: 70px; right: 20px; display: none; background: white; border: 1px solid #ddd; border-radius: 10px; padding: 10px; z-index: 1000; }
        .emoji { cursor: pointer; font-size: 20px; margin: 5px; display: inline-block; }
        @media (max-width: 768px) {
            .conversations-list { height: 60vh; margin-bottom: 15px; }
            .chat-area { height: 60vh; }
        }
    </style>
</head>
<body>
<nav class="navbar navbar-dark bg-success mb-3">
    <div class="container-fluid">
        <span class="navbar-brand"><i class="fas fa-comments"></i> Nurse Chat Center</span>
        <div>
            <span class="text-white me-3"><i class="fas fa-user-circle"></i> <?= htmlspecialchars($nurse_name) ?></span>
            <a href="dashboard.php" class="btn btn-light btn-sm">Back to Dashboard</a>
        </div>
    </div>
</nav>

<div class="container chat-container">
    <div class="row g-3">
        <!-- Conversations List -->
        <div class="col-md-4">
            <div class="conversations-list">
                <div class="p-3 bg-light border-bottom">
                    <h6 class="mb-0"><i class="fas fa-users"></i> All Conversations</h6>
                </div>
                <div id="conversationsList">
                    <?php while($conv = $conversations->fetch_assoc()): 
                        $other_id = $conv['other_person_id'];
                        $other_type = $conv['other_person_type'];
                        $other_name = '';
                        $profile_pic = '';
                        
                        if($other_type == 'doctor') {
                            $doc = $conn->query("SELECT name, profile_pic FROM doctors WHERE doctor_id = $other_id")->fetch_assoc();
                            $other_name = $doc['name'];
                            $profile_pic = $doc['profile_pic'];
                        } elseif($other_type == 'staff') {
                            $staff = $conn->query("SELECT CONCAT(first_name, ' ', last_name) as name, profile_pic FROM staff WHERE staff_id = $other_id")->fetch_assoc();
                            $other_name = $staff['name'];
                            $profile_pic = $staff['profile_pic'];
                        } else {
                            $nurse = $conn->query("SELECT CONCAT(first_name, ' ', last_name) as name, profile_pic FROM nurses WHERE nurse_id = $other_id")->fetch_assoc();
                            $other_name = $nurse['name'];
                            $profile_pic = $nurse['profile_pic'];
                        }
                    ?>
                        <div class="conversation-item" data-other-id="<?= $other_id ?>" data-other-type="<?= $other_type ?>" data-other-name="<?= htmlspecialchars($other_name) ?>" onclick="loadChat('<?= $other_id ?>', '<?= $other_type ?>', '<?= htmlspecialchars($other_name) ?>')">
                            <div class="d-flex align-items-center">
                                <div class="position-relative me-3">
                                    <?php if($profile_pic && file_exists("../uploads/" . $profile_pic)): ?>
                                        <img src="../uploads/<?= $profile_pic ?>" class="profile-pic small-pic">
                                    <?php else: ?>
                                        <div class="profile-pic small-pic bg-secondary">
                                            <i class="fas fa-user"></i>
                                        </div>
                                    <?php endif; ?>
                                    <div class="online-status" id="status_<?= $other_id ?>"></div>
                                </div>
                                <div class="flex-grow-1">
                                    <div class="d-flex justify-content-between">
                                        <strong><?= htmlspecialchars($other_name) ?></strong>
                                        <small class="text-muted"><?= date('H:i', strtotime($conv['last_message_time'])) ?></small>
                                    </div>
                                    <div class="small text-muted">
                                        <?= htmlspecialchars(substr($conv['last_message'], 0, 30)) ?>
                                        <?php if($conv['unread_count'] > 0): ?>
                                            <span class="unread-badge"><?= $conv['unread_count'] ?></span>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endwhile; ?>
                </div>
                
                <!-- New Chat Button -->
                <div class="p-3 border-top">
                    <button class="btn btn-success w-100" data-bs-toggle="modal" data-bs-target="#newChatModal">
                        <i class="fas fa-plus-circle"></i> New Chat
                    </button>
                </div>
            </div>
        </div>
        
        <!-- Chat Area -->
        <div class="col-md-8">
            <div class="chat-area">
                <div class="chat-header" id="chatHeader">
                    <div class="d-flex align-items-center">
                        <div class="profile-pic small-pic me-2" id="chatProfilePic">
                            <i class="fas fa-user"></i>
                        </div>
                        <div>
                            <h6 class="mb-0" id="chatPartnerName">Select a conversation</h6>
                            <small id="typingStatus" class="typing-indicator" style="display: none;">Typing...</small>
                        </div>
                    </div>
                </div>
                <div class="messages-area" id="messagesArea">
                    <div class="text-center text-muted mt-5">
                        <i class="fas fa-comments fa-3x mb-3"></i>
                        <p>Select a conversation to start chatting</p>
                    </div>
                </div>
                <div class="input-area">
                    <div class="input-group">
                        <input type="text" id="messageInput" class="form-control" placeholder="Type your message..." autocomplete="off">
                        <button class="btn btn-outline-secondary" onclick="toggleEmoji()"><i class="far fa-smile"></i></button>
                        <button class="btn btn-success" onclick="sendMessage()"><i class="fas fa-paper-plane"></i> Send</button>
                    </div>
                    <div id="emojiPicker" class="emoji-picker">
                        <span class="emoji" onclick="addEmoji('😊')">😊</span>
                        <span class="emoji" onclick="addEmoji('😂')">😂</span>
                        <span class="emoji" onclick="addEmoji('❤️')">❤️</span>
                        <span class="emoji" onclick="addEmoji('👍')">👍</span>
                        <span class="emoji" onclick="addEmoji('👋')">👋</span>
                        <span class="emoji" onclick="addEmoji('🙏')">🙏</span>
                        <span class="emoji" onclick="addEmoji('😅')">😅</span>
                        <span class="emoji" onclick="addEmoji('🎉')">🎉</span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- New Chat Modal -->
<div class="modal fade" id="newChatModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-success text-white">
                <h5 class="modal-title"><i class="fas fa-users"></i> Start New Chat</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <ul class="nav nav-tabs" id="chatTabs">
                    <li class="nav-item"><button class="nav-link active" data-bs-toggle="tab" data-bs-target="#doctors">Doctors</button></li>
                    <li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#staff">Staff</button></li>
                    <li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#nurses">Nurses</button></li>
                </ul>
                <div class="tab-content mt-3">
                    <div class="tab-pane active" id="doctors">
                        <?php while($doc = $online_doctors->fetch_assoc()): ?>
                            <div class="contact-item p-2 border-bottom" onclick="startChat('<?= $doc['id'] ?>', 'doctor', '<?= htmlspecialchars($doc['display_name']) ?>')">
                                <div class="d-flex align-items-center">
                                    <div class="profile-pic small-pic me-2">
                                        <i class="fas fa-user-md"></i>
                                    </div>
                                    <div>
                                        <strong><?= htmlspecialchars($doc['display_name']) ?></strong><br>
                                        <small>Doctor</small>
                                    </div>
                                </div>
                            </div>
                        <?php endwhile; ?>
                    </div>
                    <div class="tab-pane" id="staff">
                        <?php while($staff = $online_staff->fetch_assoc()): ?>
                            <div class="contact-item p-2 border-bottom" onclick="startChat('<?= $staff['id'] ?>', 'staff', '<?= htmlspecialchars($staff['display_name']) ?>')">
                                <div class="d-flex align-items-center">
                                    <div class="profile-pic small-pic me-2">
                                        <i class="fas fa-user-tie"></i>
                                    </div>
                                    <div>
                                        <strong><?= htmlspecialchars($staff['display_name']) ?></strong><br>
                                        <small>Staff</small>
                                    </div>
                                </div>
                            </div>
                        <?php endwhile; ?>
                    </div>
                    <div class="tab-pane" id="nurses">
                        <?php while($nurse = $online_nurses->fetch_assoc()): ?>
                            <div class="contact-item p-2 border-bottom" onclick="startChat('<?= $nurse['id'] ?>', 'nurse', '<?= htmlspecialchars($nurse['display_name']) ?>')">
                                <div class="d-flex align-items-center">
                                    <div class="profile-pic small-pic me-2">
                                        <i class="fas fa-user-nurse"></i>
                                    </div>
                                    <div>
                                        <strong><?= htmlspecialchars($nurse['display_name']) ?></strong><br>
                                        <small>Nurse</small>
                                    </div>
                                </div>
                            </div>
                        <?php endwhile; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
let currentChatId = null;
let currentChatType = null;
let lastMessageId = 0;
let typingTimeout = null;

function loadChat(otherId, otherType, otherName) {
    currentChatId = otherId;
    currentChatType = otherType;
    
    // Update header
    $('#chatPartnerName').text(otherName);
    $('#typingStatus').hide();
    
    // Mark messages as read
    $.post('chat_actions.php', {
        action: 'mark_read',
        other_id: otherId,
        other_type: otherType
    });
    
    // Load messages
    loadMessages();
    
    // Update active conversation highlight
    $('.conversation-item').removeClass('active');
    $(`[data-other-id="${otherId}"]`).addClass('active');
    
    // Remove unread badge
    $(`[data-other-id="${otherId}"] .unread-badge`).remove();
    
    // Clear input
    $('#messageInput').val('');
}

function loadMessages() {
    if (!currentChatId) return;
    
    $.post('chat_actions.php', {
        action: 'get_messages',
        other_id: currentChatId,
        other_type: currentChatType,
        last_id: lastMessageId
    }, function(response) {
        if (response.messages) {
            if (lastMessageId === 0) {
                $('#messagesArea').html('');
            }
            
            response.messages.forEach(function(msg) {
                displayMessage(msg);
                if (msg.id > lastMessageId) lastMessageId = msg.id;
            });
            
            // Scroll to bottom
            $('#messagesArea').scrollTop($('#messagesArea')[0].scrollHeight);
        }
    }, 'json');
}

function displayMessage(msg) {
    const isSent = (msg.sender_id == <?= $nurse_id ?> && msg.sender_type == 'nurse');
    const messageClass = isSent ? 'sent' : 'received';
    const time = new Date(msg.created_at).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
    
    const messageHtml = `
        <div class="message ${messageClass}" data-message-id="${msg.id}">
            <div class="message-bubble">
                ${escapeHtml(msg.message)}
                <span class="message-time">${time}</span>
            </div>
        </div>
    `;
    
    $('#messagesArea').append(messageHtml);
}

function sendMessage() {
    const message = $('#messageInput').val().trim();
    if (!message || !currentChatId) return;
    
    $.post('chat_actions.php', {
        action: 'send',
        other_id: currentChatId,
        other_type: currentChatType,
        message: message
    }, function(response) {
        if (response.success) {
            $('#messageInput').val('');
            loadMessages();
        }
    }, 'json');
}

function startChat(id, type, name) {
    $('#newChatModal').modal('hide');
    loadChat(id, type, name);
}

function toggleEmoji() {
    $('#emojiPicker').toggle();
}

function addEmoji(emoji) {
    $('#messageInput').val($('#messageInput').val() + emoji);
    $('#emojiPicker').hide();
}

function escapeHtml(text) {
    return text.replace(/[&<>]/g, function(m) {
        if (m === '&') return '&amp;';
        if (m === '<') return '&lt;';
        if (m === '>') return '&gt;';
        return m;
    });
}

// Auto-refresh messages every 3 seconds
setInterval(function() {
    if (currentChatId) {
        loadMessages();
    }
}, 3000);

// Typing indicator
$('#messageInput').on('keydown', function() {
    if (currentChatId) {
        $.post('chat_actions.php', {
            action: 'typing',
            other_id: currentChatId,
            other_type: currentChatType
        });
    }
});

// Check for typing status
setInterval(function() {
    if (currentChatId) {
        $.post('chat_actions.php', {
            action: 'check_typing',
            other_id: currentChatId,
            other_type: currentChatType
        }, function(response) {
            if (response.is_typing) {
                $('#typingStatus').show();
            } else {
                $('#typingStatus').hide();
            }
        }, 'json');
    }
}, 2000);

// Send message on Enter key
$('#messageInput').keypress(function(e) {
    if (e.which == 13 && !e.shiftKey) {
        e.preventDefault();
        sendMessage();
    }
});

// Click outside emoji picker
$(document).click(function(event) {
    if (!$(event.target).closest('.emoji-picker, .fa-smile').length) {
        $('#emojiPicker').hide();
    }
});
</script>
</body>
</html>