<?php
/**
 * Debug Conversations - Check chat rooms and messages
 * OBGYN Research & Collaboration Platform
 */

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

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

$userId = getCurrentUserId();
$db = getDB();

// Get user's chat rooms
$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();

echo "<h1>Debug: Conversations for User ID $userId</h1>";
echo "<h2>Chat Rooms:</h2>";
if (empty($chatRooms)) {
    echo "<p>No chat rooms found.</p>";
} else {
    echo "<ul>";
    foreach ($chatRooms as $room) {
        echo "<li>Room ID: {$room['id']}, Name: {$room['name']}, Unread: {$room['unread_count']}, Last Message: {$room['last_message']}</li>";
    }
    echo "</ul>";
}

// Check total chat rooms in DB
$stmt = $db->query("SELECT COUNT(*) FROM chat_rooms");
$totalRooms = $stmt->fetchColumn();
echo "<p>Total chat rooms in DB: $totalRooms</p>";

// Check total participants
$stmt = $db->query("SELECT COUNT(*) FROM chat_participants");
$totalParticipants = $stmt->fetchColumn();
echo "<p>Total participants in DB: $totalParticipants</p>";

// Check total messages
$stmt = $db->query("SELECT COUNT(*) FROM messages");
$totalMessages = $stmt->fetchColumn();
echo "<p>Total messages in DB: $totalMessages</p>";
?>