<?php
/**
 * Messages/Chat Interface
 * OBGYN Research & Collaboration Platform
 */

require_once '../config/config.php';

requireLogin();
if (!isResearcher()) {
    redirect(SITE_URL . '/index.php');
}

$pageTitle = 'Messages';
$userId = getCurrentUserId();

// Get user's chat rooms
$db = getDB();
$stmt = $db->prepare("
    SELECT DISTINCT cr.*, 
           (SELECT COUNT(*) FROM messages WHERE room_id = cr.id AND is_read = 0 AND sender_id != ?) as unread_count,
           (SELECT message FROM messages WHERE room_id = cr.id ORDER BY created_at DESC LIMIT 1) as last_message,
           (SELECT created_at FROM messages WHERE room_id = cr.id ORDER BY created_at DESC LIMIT 1) as last_message_time
    FROM chat_rooms cr
    JOIN chat_participants cp ON cr.id = cp.room_id
    WHERE cp.user_id = ?
    ORDER BY last_message_time DESC
");
$stmt->execute([$userId, $userId]);
$chatRooms = $stmt->fetchAll();

// Get selected room messages
$selectedRoomId = isset($_GET['room']) ? (int)$_GET['room'] : (count($chatRooms) > 0 ? $chatRooms[0]['id'] : 0);
$messages = [];
$roomParticipants = [];

if ($selectedRoomId > 0) {
    // Get messages
    $stmt = $db->prepare("
        SELECT m.*, u.first_name, u.last_name
        FROM messages m
        JOIN users u ON m.sender_id = u.id
        WHERE m.room_id = ?
        ORDER BY m.created_at ASC
        LIMIT 100
    ");
    $stmt->execute([$selectedRoomId]);
    $messages = $stmt->fetchAll();
    
    // Get room participants
    $stmt = $db->prepare("
        SELECT u.id, u.first_name, u.last_name
        FROM chat_participants cp
        JOIN users u ON cp.user_id = u.id
        WHERE cp.room_id = ? AND u.id != ?
    ");
    $stmt->execute([$selectedRoomId, $userId]);
    $roomParticipants = $stmt->fetchAll();
    
    // Mark messages as read
    $stmt = $db->prepare("
        UPDATE messages 
        SET is_read = 1 
        WHERE room_id = ? AND sender_id != ?
    ");
    $stmt->execute([$selectedRoomId, $userId]);
}

// Handle send message
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['send_message'])) {
    validateCSRF();
    
    $message = sanitize($_POST['message'] ?? '');
    $roomId = (int)($_POST['room_id'] ?? 0);
    
    if (!empty($message) && $roomId > 0) {
        $stmt = $db->prepare("
            INSERT INTO messages (room_id, sender_id, message, message_type)
            VALUES (?, ?, ?, 'text')
        ");
        $stmt->execute([$roomId, $userId, $message]);
        
        redirect(SITE_URL . '/researcher/messages.php?room=' . $roomId);
    }
}

include '../templates/header.php';
?>

<div class="container-fluid">
    <div class="row">
        <?php include 'sidebar.php'; ?>

        <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
            <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                <h1 class="h2"><i class="fas fa-envelope"></i> Messages</h1>
                <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#newChatModal">
                    <i class="fas fa-plus"></i> New Message
                </button>
            </div>

            <div class="row">
                <!-- Chat List -->
                <div class="col-md-4 col-lg-3">
                    <div class="card shadow">
                        <div class="card-header">
                            <h6 class="mb-0">Conversations</h6>
                        </div>
                        <div class="list-group list-group-flush" style="max-height: 600px; overflow-y: auto;">
                            <?php if (empty($chatRooms)): ?>
                                <div class="list-group-item text-center text-muted py-4">
                                    <i class="fas fa-inbox fa-2x mb-2"></i>
                                    <p class="mb-0 small">No conversations yet</p>
                                </div>
                            <?php else: ?>
                                <?php foreach ($chatRooms as $room): ?>
                                <a href="?room=<?php echo $room['id']; ?>" 
                                   class="list-group-item list-group-item-action <?php echo $selectedRoomId == $room['id'] ? 'active' : ''; ?>">
                                    <div class="d-flex w-100 justify-content-between">
                                        <h6 class="mb-1">
                                            <?php echo e($room['name'] ?? 'Chat'); ?>
                                            <?php if ($room['unread_count'] > 0): ?>
                                                <span class="badge bg-danger"><?php echo $room['unread_count']; ?></span>
                                            <?php endif; ?>
                                        </h6>
                                        <small><?php echo $room['last_message_time'] ? timeAgo($room['last_message_time']) : ''; ?></small>
                                    </div>
                                    <p class="mb-0 small text-truncate">
                                        <?php echo e(substr($room['last_message'] ?? 'No messages', 0, 50)); ?>
                                    </p>
                                </a>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>

                <!-- Chat Messages -->
                <div class="col-md-8 col-lg-9">
                    <div class="card shadow">
                        <?php if ($selectedRoomId > 0): ?>
                            <div class="card-header d-flex justify-content-between align-items-center">
                                <h6 class="mb-0">
                                    <?php if (!empty($roomParticipants)): ?>
                                        <?php echo e($roomParticipants[0]['first_name'] . ' ' . $roomParticipants[0]['last_name']); ?>
                                        <?php if (count($roomParticipants) > 1): ?>
                                            and <?php echo count($roomParticipants) - 1; ?> others
                                        <?php endif; ?>
                                    <?php else: ?>
                                        Chat
                                    <?php endif; ?>
                                </h6>
                                <button class="btn btn-sm btn-outline-secondary">
                                    <i class="fas fa-ellipsis-v"></i>
                                </button>
                            </div>
                            <div class="card-body" style="height: 500px; overflow-y: auto;" id="messageContainer">
                                <?php if (empty($messages)): ?>
                                    <div class="text-center text-muted py-5">
                                        <i class="fas fa-comments fa-3x mb-3"></i>
                                        <p>No messages yet. Start the conversation!</p>
                                    </div>
                                <?php else: ?>
                                    <?php foreach ($messages as $msg): ?>
                                    <div class="mb-3 <?php echo $msg['sender_id'] == $userId ? 'text-end' : ''; ?>">
                                        <div class="d-inline-block" style="max-width: 70%;">
                                            <?php if ($msg['sender_id'] != $userId): ?>
                                                <small class="text-muted d-block mb-1">
                                                    <?php echo e($msg['first_name'] . ' ' . $msg['last_name']); ?>
                                                </small>
                                            <?php endif; ?>
                                            <div class="p-3 rounded <?php echo $msg['sender_id'] == $userId ? 'bg-primary text-white' : 'bg-light'; ?>">
                                                <?php echo nl2br(e($msg['message'])); ?>
                                            </div>
                                            <small class="text-muted d-block mt-1">
                                                <?php echo date('g:i A', strtotime($msg['created_at'])); ?>
                                            </small>
                                        </div>
                                    </div>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </div>
                            <div class="card-footer">
                                <form method="POST" action="" class="d-flex gap-2">
                                    <?php echo csrfField(); ?>
                                    <input type="hidden" name="room_id" value="<?php echo $selectedRoomId; ?>">
                                    <input type="text" class="form-control" name="message" 
                                           placeholder="Type your message..." required autofocus>
                                    <button type="submit" name="send_message" class="btn btn-primary">
                                        <i class="fas fa-paper-plane"></i> Send
                                    </button>
                                </form>
                            </div>
                        <?php else: ?>
                            <div class="card-body text-center py-5">
                                <i class="fas fa-comments fa-4x text-muted mb-3"></i>
                                <h5>Select a conversation</h5>
                                <p class="text-muted">Choose a conversation from the list or start a new one</p>
                                <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#newChatModal">
                                    <i class="fas fa-plus"></i> Start New Conversation
                                </button>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </main>
    </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">
                <h5 class="modal-title">New Message</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p class="text-muted">This feature will be available soon. You'll be able to start conversations with other researchers.</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<script>
// Auto-scroll to bottom of messages
const messageContainer = document.getElementById('messageContainer');
if (messageContainer) {
    messageContainer.scrollTop = messageContainer.scrollHeight;
}

// Auto-refresh messages every 10 seconds
setInterval(function() {
    if (<?php echo $selectedRoomId; ?> > 0) {
        location.reload();
    }
}, 10000);
</script>

<?php include '../templates/footer.php'; ?>
