<?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 (AJAX and regular POST)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && (isset($_POST['send_message']) || isset($_POST['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]);

        // If AJAX request, return JSON
        if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
            header('Content-Type: application/json');
            echo json_encode(['success' => true]);
            exit;
        } else {
            // Regular POST, redirect
            redirect(SITE_URL . '/researcher/messages.php?room=' . $roomId);
        }
    }
}

include '../templates/researcher-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 id="messageForm" class="d-flex gap-2">
                                    <?php echo csrfField(); ?>
                                    <input type="hidden" name="room_id" value="<?php echo $selectedRoomId; ?>">
                                    <input type="text" id="messageInput" class="form-control" name="message"
                                           placeholder="Type your message..." required autofocus>
                                    <button type="submit" id="sendButton" 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>
            <form id="newMessageForm" method="POST" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
                <div class="modal-body">
                    <?php echo csrfField(); ?>
                    <div class="mb-3">
                        <label class="form-label">Select Researcher</label>
                        <select id="researcher-select" name="to_user_id" class="form-select" required>
                            <option value="">Loading researchers...</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Message</label>
                        <textarea id="initial-message" name="initial_message" class="form-control" rows="3" placeholder="Type your message..." required></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Send Message</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// Load researchers for the select dropdown
async function loadResearchers(selectedId) {
    const select = document.getElementById('researcher-select');
    try {
        const response = await fetch('<?php echo SITE_URL; ?>/api/search.php?q=&type=researchers&limit=50');
        const data = await response.json();
        console.log('API Response:', data); // Debugging line to log the API response
        if (data.success && data.results && Array.isArray(data.results.researchers) && data.results.researchers.length > 0) {
            select.innerHTML = '<option value="">Select a researcher...</option>' +
                data.results.researchers.map(user =>
                    `<option value="${user.id}" ${selectedId == user.id ? 'selected' : ''}>${user.first_name} ${user.last_name}</option>`
                ).join('');
        } else {
            select.innerHTML = '<option value="">No researchers found</option>';
        }
    } catch (error) {
        select.innerHTML = '<option value="">Error loading researchers</option>';
    }
}

// Auto-open modal if ?to=ID is present
document.addEventListener('DOMContentLoaded', function() {
    const urlParams = new URLSearchParams(window.location.search);
    const toId = urlParams.get('to');
    if (toId) {
        loadResearchers(toId).then(() => {
            const modal = new bootstrap.Modal(document.getElementById('newChatModal'));
            modal.show();
        });
    } else {
        loadResearchers();
    }
});
</script>

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

// Function to load messages
async function loadMessages() {
    const roomId = <?php echo $selectedRoomId; ?>;
    if (!roomId) return;

    try {
        const response = await fetch('get-messages.php?room=' + roomId);
        const html = await response.text();
        document.getElementById('messageContainer').innerHTML = html;
        // Scroll to bottom
        const container = document.getElementById('messageContainer');
        container.scrollTop = container.scrollHeight;
    } catch (error) {
        console.error('Error loading messages:', error);
    }
}

// Handle message form submission
document.getElementById('messageForm').addEventListener('submit', async function(e) {
    e.preventDefault();
    const formData = new FormData(this);
    const messageInput = document.getElementById('messageInput');
    const sendButton = document.getElementById('sendButton');

    if (!messageInput.value.trim()) return;

    sendButton.disabled = true;
    sendButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Sending...';

    try {
        const response = await fetch('', {
            method: 'POST',
            body: formData
        });

        if (response.ok) {
            messageInput.value = '';
            loadMessages(); // Refresh messages
        } else {
            alert('Error sending message');
        }
    } catch (error) {
        alert('Error sending message');
    } finally {
        sendButton.disabled = false;
        sendButton.innerHTML = '<i class="fas fa-paper-plane"></i> Send';
    }
});

// Auto-refresh messages every 5 seconds
setInterval(loadMessages, 5000);
</script>

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