"fail", "message" => "Method not allowed."])); } $sessionCookie = $_COOKIE['sessionid'] ?? ''; if (empty($sessionCookie) || strpos($sessionCookie, 'nostolga_sess_') !== 0) { http_response_code(401); die(json_encode(["status" => "fail", "message" => "Unauthorized session context."])); } $userId = (int)str_replace('nostolga_sess_', '', $sessionCookie); $db = getDB(); try { // Check for the most recent message exchanged by this user $stmt = $db->prepare("SELECT * FROM direct_messages WHERE sender_id = ? OR recipient_id = ? ORDER BY id DESC LIMIT 1"); $stmt->execute([$userId, $userId]); $lastMsg = $stmt->fetch(); $threads = []; if ($lastMsg) { // Active conversation exists -> Determine the opposing chatter's profile $otherUserId = ($lastMsg['sender_id'] == $userId) ? $lastMsg['recipient_id'] : $lastMsg['sender_id']; $userStmt = $db->prepare("SELECT id, username, full_name, profile_pic FROM users WHERE id = ?"); $userStmt->execute([$otherUserId]); $otherUser = $userStmt->fetch(); if ($otherUser) { $threads[] = [ "thread_id" => "thread_" . $otherUser['id'], "users" => [[ "pk" => (int)$otherUser['id'], "username" => $otherUser['username'], "full_name" => $otherUser['full_name'], "profile_pic_url" => $otherUser['profile_pic'] ?? 'https://picsum.photos/150/150' ]], "last_activity_at" => (int)$lastMsg['created_at'] * 1000000, "items" => [[ "item_id" => (string)$lastMsg['id'], "user_id" => (int)$lastMsg['sender_id'], "timestamp" => (int)$lastMsg['created_at'] * 1000000, "item_type" => "text", "text" => $lastMsg['message_text'] ]], "canonical" => true, "named" => false ]; } } else { // Fallback welcoming chat thread $threads[] = [ "thread_id" => "thread_999", "users" => [[ "pk" => 999, "username" => "nostolga_support", "full_name" => "System Direct Engine", "profile_pic_url" => "https://picsum.photos/150/150" ]], "last_activity_at" => time() * 1000000, "items" => [[ "item_id" => "mock_msg_001", "user_id" => 999, "timestamp" => time() * 1000000, "item_type" => "text", "text" => "Welcome to Direct Messages! Your chat nodes are active. Broadcast a message to test." ]], "canonical" => true, "named" => false ]; } http_response_code(200); echo json_encode([ "inbox" => [ "threads" => $threads, "unseen_count" => 0, "unseen_count_ts" => time() * 1000000 ], "status" => "ok" ]); exit; } catch (PDOException $e) { http_response_code(500); die(json_encode(["status" => "fail", "message" => "Inbox matrix retrieval failure."])); }