<?php
require_once 'db_connection.php';

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'User is not logged in.']);
    exit();
}

$userId = $_SESSION['user_id'];

try {
    $stmt = $pdo->prepare("
        SELECT 
            c.id AS conversation_id,
            c.name AS conversation_name,
            c.is_group
        FROM conversations c
        WHERE c.id IN (
            SELECT conversation_id 
            FROM conversation_participants 
            WHERE user_id = :user_id
        )
    ");
    $stmt->execute(['user_id' => $userId]);

    $chats = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($chats as &$chat) {
        if (!$chat['is_group']) {
            $participantStmt = $pdo->prepare("
                SELECT e.username 
                FROM emails_v e
                JOIN conversation_participants cp ON e.id = cp.user_id
                WHERE cp.conversation_id = :conversation_id AND e.id != :user_id
                LIMIT 1
            ");
            $participantStmt->execute([
                'conversation_id' => $chat['conversation_id'],
                'user_id' => $userId,
            ]);

            $participant = $participantStmt->fetch(PDO::FETCH_ASSOC);
            $chat['participant_name'] = $participant['username'] ?? 'Unknown';
        }

        $unreadStmt = $pdo->prepare("
            SELECT COUNT(*) AS unread_count
            FROM messages
            WHERE conversation_id = :conversation_id
              AND sender_id != :user_id
              AND `read` = 0
        ");
        $unreadStmt->execute([
            'conversation_id' => $chat['conversation_id'],
            'user_id' => $userId,
        ]);

        $unreadCount = $unreadStmt->fetch(PDO::FETCH_ASSOC);
        $chat['unread_count'] = $unreadCount['unread_count'] ?? 0;
    }

    echo json_encode(['success' => true, 'chats' => $chats]);
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'Error fetching chats: ' . $e->getMessage()]);
}
?>
