<?php

namespace BitApps\PiPro\src\Integrations\BuddyBoss;

use BitApps\Pi\Helpers\MixInputHandler;
use BitApps\Pi\Helpers\Utility;
use BitApps\Pi\src\Flow\NodeInfoProvider;
use BitApps\PiPro\src\Integrations\BuddyBoss\helper\BuddyBossHelper;
use BP_Suspend_Member;

if (!\defined('ABSPATH')) {
    exit;
}

final class BuddyBossService
{
    private NodeInfoProvider $nodeInfoProvider;

    public function __construct(NodeInfoProvider $nodeInfoProvider)
    {
        $this->nodeInfoProvider = $nodeInfoProvider;
    }

    public function addPostToActivityFeed(): array
    {
        $fieldMappings = $this->nodeInfoProvider->getFieldMapData();

        $rules = [
            'author_email'     => ['required', 'email'],
            'activity_content' => ['required', 'string']
        ];

        if ($errors = BuddyBossHelper::validateFieldMap($fieldMappings, $rules)) {
            return $errors;
        }

        return self::handlePostActivityFeedActions($fieldMappings);
    }

    public function addPostToGroup(): array
    {
        $fieldMappings = $this->nodeInfoProvider->getFieldMapData();
        $groupId = absint($this->nodeInfoProvider->getFieldMapConfigs('group.value'));

        $rules = [
            'author_email'     => ['required', 'email'],
            'activity_content' => ['required', 'string']
        ];

        if ($errors = BuddyBossHelper::validateFieldMap($fieldMappings, $rules)) {
            return $errors;
        }

        if (empty($groupId)) {
            return [
                'response'    => __('Group ID is required.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        return self::handlePostActivityFeedActions($fieldMappings, 'groups', $groupId);
    }

    public function addPostToUserActivityFeed(): array
    {
        $fieldMappings = $this->nodeInfoProvider->getFieldMapData();
        $userActivityId = $this->nodeInfoProvider->getFieldMapConfigs('user-activity-id.value') ?? null;

        $rules = [
            'author_email'     => ['required', 'email'],
            'activity_content' => ['required', 'string']
        ];

        if ($errors = BuddyBossHelper::validateFieldMap($fieldMappings, $rules)) {
            return $errors;
        }

        if (empty($userActivityId)) {
            return [
                'response'    => __('User Activity ID is required.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        return self::handlePostActivityFeedActions($fieldMappings, 'activity', null, $userActivityId);
    }

    public function addUserToGroup(): array
    {
        $fieldMappings = $this->nodeInfoProvider->getFieldMapData();
        $groups = $this->nodeInfoProvider->getFieldMapConfigs('group.value');

        $rules = [
            'user_email' => ['required', 'email']
        ];

        if ($errors = BuddyBossHelper::validateFieldMap($fieldMappings, $rules)) {
            return $errors;
        }

        if (empty($groups)) {
            return [
                'response'    => __('At least one group must be selected.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        $userId = email_exists($fieldMappings['user_email']);

        if ($userId === false) {
            return [
                'response'    => __('User not found with provided email.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        if (!\function_exists('groups_join_group')) {
            return [
                'response'    => __('BuddyBoss Groups join function not found.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        $groupIds = \is_array($groups) ? array_map('absint', $groups) : [absint($groups)];
        $addedGroups = [];

        foreach ($groupIds as $groupId) {
            if (groups_join_group($groupId, $userId)) {
                $addedGroups[] = $groupId;
            }
        }

        $data = [
            'user_id'         => Utility::getUserInfo($userId),
            'added_group_ids' => $addedGroups
        ];

        return [
            'response'    => $data,
            'payload'     => $fieldMappings,
            'status_code' => 200
        ];
    }

    public function changeUserMemberType(): array
    {
        $fieldMappings = $this->nodeInfoProvider->getFieldMapData();
        $profileType = $this->nodeInfoProvider->getFieldMapConfigs('profile-type.value');
        $rules = [
            'user_email' => ['required', 'email']
        ];

        if ($errors = BuddyBossHelper::validateFieldMap($fieldMappings, $rules)) {
            return $errors;
        }

        if (empty($profileType)) {
            return [
                'response'    => __('Profile type is required.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        $userId = email_exists($fieldMappings['user_email']);

        if (empty($userId)) {
            return [
                'response'    => __('User not found with provided email.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        if (!\function_exists('bp_set_member_type')) {
            return [
                'response'    => __('bp_set_member_type function not found.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        if (!bp_set_member_type($userId, $profileType)) {
            return [
                'response'    => __('Failed to set member type.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        return [
            'response'    => Utility::jsonEncodeDecode(get_userdata($userId)),
            'payload'     => $fieldMappings,
            'status_code' => 200
        ];
    }

    public function createGroup(): array
    {
        $fieldMappings = $this->nodeInfoProvider->getFieldMapData();
        $rules = [
            'group_name'          => ['required', 'string'],
            'group_status'        => ['required', 'string'],
            'group_creator_email' => ['required', 'email']
        ];

        if ($errors = BuddyBossHelper::validateFieldMap($fieldMappings, $rules)) {
            return $errors;
        }

        if (
            !\function_exists('groups_create_group')
            || !\function_exists('groups_get_group')
            || !\function_exists('bp_groups_set_group_type')
        ) {
            return [
                'response'    => __('Required BuddyBoss Groups functions do not exist.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        $groupCreator = get_user_by('email', $fieldMappings['group_creator_email']);

        if (!$groupCreator) {
            return [
                'response'    => __('Group Creator Not Found.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        $groupId = groups_create_group(
            [
                'creator_id' => $groupCreator->ID,
                'name'       => $fieldMappings['group_name'],
                'status'     => $fieldMappings['group_status']
            ]
        );

        if (is_wp_error($groupId) || !$groupId) {
            return [
                'response'    => __('There is an error on creating group.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        if (!empty($fieldMappings['group_type'])) {
            bp_groups_set_group_type($groupId, $fieldMappings['group_type']);
        }

        $groupData = groups_get_group($groupId);

        return [
            'response'    => Utility::jsonEncodeDecode($groupData),
            'payload'     => $fieldMappings,
            'status_code' => 200
        ];
    }

    public function endFriendshipWithUser(): array
    {
        $fieldMappings = $this->nodeInfoProvider->getFieldMapData();

        $rules = [
            'user_email'   => ['required', 'email'],
            'friend_email' => ['required', 'email']
        ];

        if ($errors = BuddyBossHelper::validateFieldMap($fieldMappings, $rules)) {
            return $errors;
        }

        $userId = email_exists($fieldMappings['user_email']);
        $friendId = email_exists($fieldMappings['friend_email']);

        if (!$userId || !$friendId) {
            return [
                'response'    => __('One or both users not found.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        if (!\function_exists('friends_remove_friend')) {
            return [
                'response'    => __('BuddyBoss connection module is not active.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        if (friends_remove_friend($userId, $friendId)) {
            return [
                'response'    => __('Friendship ended successfully.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 200
            ];
        }

        return [
            'response'    => __('Failed to end friendship.', 'bit-pi'),
            'payload'     => $fieldMappings,
            'status_code' => 400
        ];
    }

    public function followUser(): array
    {
        $fieldMappings = $this->nodeInfoProvider->getFieldMapData();

        $rules = [
            'follower_email' => ['required', 'email'],
            'leader_email'   => ['required', 'email']
        ];

        if ($errors = BuddyBossHelper::validateFieldMap($fieldMappings, $rules)) {
            return $errors;
        }

        $follower = get_user_by('email', $fieldMappings['follower_email']);
        $leader = get_user_by('email', $fieldMappings['leader_email']);

        if (!$follower || !$leader) {
            return [
                'response'    => __('One or both users not found.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        if ($follower->ID === $leader->ID) {
            return [
                'response'    => __('A user cannot follow themselves.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        $followFunctionName = null;

        if (\function_exists('bp_follow_start_following') && \function_exists('bp_is_active') && bp_is_active('follow')) {
            $followFunctionName = 'bp_follow_start_following';
        } elseif (\function_exists('bp_start_following')) {
            $followFunctionName = 'bp_start_following';
        }

        if (!$followFunctionName) {
            return [
                'response'    => __('BuddyBoss Follow functions not found.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        $result = $followFunctionName(
            [
                'follower_id' => $follower->ID,
                'leader_id'   => $leader->ID
            ]
        );

        if (!$result) {
            return [
                'response'    => __('User is already following.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        $data = [
            'follower' => Utility::jsonEncodeDecode($follower),
            'leader'   => Utility::jsonEncodeDecode($leader)
        ];

        return [
            'response'    => $data,
            'payload'     => $fieldMappings,
            'status_code' => 200
        ];
    }

    public function getForumSubscribers(): array
    {
        $fieldMappings = $this->nodeInfoProvider->getFieldMapData();

        $rules = [
            'forum_id' => ['required', 'integer']
        ];

        if ($errors = BuddyBossHelper::validateFieldMap($fieldMappings, $rules)) {
            return $errors;
        }

        if (!\function_exists('bbp_get_forum_subscribers')) {
            return [
                'response'    => __('Required BuddyBoss functions do not exist.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        $subscribersIds = bbp_get_forum_subscribers($fieldMappings['forum_id']);

        $subscribers = array_map(
            function (int $subscriberId) {
                return Utility::jsonEncodeDecode(get_userdata($subscriberId));
            },
            $subscribersIds
        );

        return [
            'response'    => $subscribers,
            'payload'     => $fieldMappings,
            'status_code' => 200
        ];
    }

    public function postReplyTopicForum(): array
    {
        $fieldMappings = $this->nodeInfoProvider->getFieldMapData();
        $forumId = $this->nodeInfoProvider->getFieldMapConfigs('forum-id.value');

        $topicId = MixInputHandler::replaceMixTagValue(
            $this->nodeInfoProvider->getFieldMapConfigs('topic-id.value')
        );

        $rules = [
            'reply_title'        => ['required', 'string'],
            'reply_content'      => ['required', 'string'],
            'reply_author_email' => ['required', 'email']
        ];

        if ($errors = BuddyBossHelper::validateFieldMap($fieldMappings, $rules)) {
            return $errors;
        }

        if (empty($topicId) || empty($forumId)) {
            return [
                'response'    => __('Topic ID and Forum ID are required.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        if (!\function_exists('bbp_insert_reply')) {
            return [
                'response'    => __('BuddyBoss Forum functions not found.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        $user = get_user_by('email', $fieldMappings['reply_author_email']);
        if (!$user) {
            return [
                'response'    => __('Reply author user does not exist.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        $replyId = bbp_insert_reply(
            [
                'post_parent'  => $topicId,
                'post_content' => $fieldMappings['reply_content'],
                'post_status'  => bbp_get_public_status_id(),
                'post_author'  => $user->ID
            ],
            [
                'topic_id' => $topicId,
                'forum_id' => $forumId,
            ]
        );

        if (!$replyId) {
            return [
                'response'    => __('Failed to create reply.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        $response = [
            'topic_id'    => $topicId,
            'forum_id'    => $forumId,
            'reply_id'    => $replyId,
            'forum_title' => get_the_title($forumId),
            'topic_title' => get_the_title($topicId),
            'creator'     => Utility::jsonEncodeDecode($user),
        ];

        if (\function_exists('bbp_get_topic')) {
            $response['topic'] = bbp_get_topic($topicId, ARRAY_A);
        }

        if (\function_exists('bbp_get_reply')) {
            $response['reply'] = bbp_get_reply($replyId, ARRAY_A);
        }

        return [
            'response'    => $response,
            'payload'     => $fieldMappings,
            'status_code' => 200
        ];
    }

    public function postTopicInForum(): array
    {
        $fieldMappings = $this->nodeInfoProvider->getFieldMapData();
        $forumId = $this->nodeInfoProvider->getFieldMapConfigs('forum-id.value');

        $rules = [
            'topic_title'         => ['required', 'string'],
            'topic_content'       => ['required', 'string'],
            'topic_creator_email' => ['required', 'email']
        ];

        if ($errors = BuddyBossHelper::validateFieldMap($fieldMappings, $rules)) {
            return $errors;
        }

        if (empty($forumId)) {
            return [
                'response'    => __('Forum ID is required.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        if (!\function_exists('bbp_insert_topic')) {
            return [
                'response'    => __('BuddyBoss Forum functions not found.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        $user = get_user_by('email', $fieldMappings['topic_creator_email']);

        if (!$user) {
            return [
                'response'    => __('Creator user does not exist.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        $topicId = bbp_insert_topic(
            [
                'post_parent'  => $forumId,
                'post_title'   => $fieldMappings['topic_title'],
                'post_content' => $fieldMappings['topic_content'],
                'post_status'  => bbp_get_public_status_id(),
                'post_author'  => $user->ID
            ],
            ['forum_id' => $forumId]
        );

        if (!$topicId) {
            return [
                'response'    => __('Failed to create topic.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        $response = [
            'topic_id'    => $topicId,
            'forum_id'    => $forumId,
            'forum_title' => get_the_title($forumId),
            'creator'     => Utility::jsonEncodeDecode($user),
        ];

        if (\function_exists('bbp_get_topic')) {
            $topic = bbp_get_topic($topicId, ARRAY_A);
            $response['topic'] = $topic;
        }

        return [
            'response'    => $response,
            'payload'     => $fieldMappings,
            'status_code' => 200
        ];
    }

    public function removeUserFromGroup(): array
    {
        $fieldMappings = $this->nodeInfoProvider->getFieldMapData();
        $groups = $this->nodeInfoProvider->getFieldMapConfigs('group.value');

        $rules = [
            'user_email' => ['required', 'email']
        ];

        if ($errors = BuddyBossHelper::validateFieldMap($fieldMappings, $rules)) {
            return $errors;
        }

        if (empty($groups)) {
            return [
                'response'    => __('Group ID is required.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        $userId = email_exists($fieldMappings['user_email']);

        if ($userId === false) {
            return [
                'response'    => __('User Not found.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        if (!\function_exists('groups_leave_group')) {
            return [
                'response'    => __('BuddyBoss Groups functions not found.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        $groupIds = \is_array($groups) ? array_map('absint', $groups) : [absint($groups)];

        foreach ($groupIds as $groupId) {
            if (\function_exists('groups_is_user_member') && groups_is_user_member($userId, $groupId)) {
                groups_leave_group($groupId, $userId);
            }
        }

        return [
            'response'    => __('User removed from group(s) successfully.', 'bit-pi'),
            'payload'     => $fieldMappings,
            'status_code' => 200
        ];
    }

    public function sendFriendRequestUser(): array
    {
        $fieldMappings = $this->nodeInfoProvider->getFieldMapData();

        $rules = [
            'receiver_email' => ['required', 'email'],
            'sender_email'   => ['required', 'email']
        ];

        if ($errors = BuddyBossHelper::validateFieldMap($fieldMappings, $rules)) {
            return $errors;
        }

        $receiver = get_user_by('email', $fieldMappings['receiver_email']);
        $sender = get_user_by('email', $fieldMappings['sender_email']);

        if (!$receiver || !$sender) {
            return [
                'response'    => __('One or both users not found.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        if (!\function_exists('friends_add_friend')) {
            return [
                'response'    => __('BuddyBoss connection module is not active.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        $result = friends_add_friend($sender->ID, $receiver->ID);

        if ($result === false) {
            return [
                'response'    => __('We are unable to send friendship request to selected user.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        $response = [
            'sender'   => Utility::jsonEncodeDecode($sender),
            'receiver' => Utility::jsonEncodeDecode($receiver)
        ];

        return [
            'response'    => $response,
            'payload'     => $fieldMappings,
            'status_code' => 200
        ];
    }

    public function sendMessageToGroupMembers(): array
    {
        $fieldMappings = $this->nodeInfoProvider->getFieldMapData();
        $groupId = absint($this->nodeInfoProvider->getFieldMapConfigs('group.value'));

        $rules = [
            'sender_email'    => ['required', 'email'],
            'message_subject' => ['required', 'string'],
            'message_content' => ['required', 'string']
        ];

        if ($errors = BuddyBossHelper::validateFieldMap($fieldMappings, $rules)) {
            return $errors;
        }

        if (empty($groupId)) {
            return [
                'response'    => __('Group ID is required.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        $senderId = email_exists($fieldMappings['sender_email']);

        if ($senderId === false) {
            return [
                'response'    => __('Sender user does not exist.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        if (!\function_exists('groups_get_group_members')) {
            return [
                'response'    => __('BuddyBoss Groups functions not found.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        $members = groups_get_group_members(['group_id' => $groupId]);
        $recipientIds = [];

        if (!empty($members['members'])) {
            foreach ($members['members'] as $member) {
                if ($member->ID !== $senderId) {
                    $recipientIds[] = $member->ID;
                }
            }
        }

        if (empty($recipientIds)) {
            return [
                'response'    => __('No members found in the group.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        if (!\function_exists('messages_new_message')) {
            return [
                'response'    => __('BuddyBoss message module is not active.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        $send = messages_new_message(
            [
                'sender_id'  => $senderId,
                'recipients' => $recipientIds,
                'subject'    => $fieldMappings['message_subject'],
                'content'    => $fieldMappings['message_content'],
                'error_type' => 'wp_error'
            ]
        );

        if (!$send) {
            return [
                'response'    => __('Failed to send message.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        $response = [
            'group_id'         => $groupId,
            'total_recipients' => \count($recipientIds),
            'recipients_ids'   => $recipientIds
        ];

        return [
            'response'    => $response,
            'payload'     => $fieldMappings,
            'status_code' => 200
        ];
    }

    public function sendMessageToUser(): array
    {
        $fieldMappings = $this->nodeInfoProvider->getFieldMapData();

        $rules = [
            'sender_email'    => ['required', 'email'],
            'receiver_emails' => ['required', 'string'],
            'message_subject' => ['required', 'string'],
            'message_content' => ['required', 'string']
        ];

        if ($errors = BuddyBossHelper::validateFieldMap($fieldMappings, $rules)) {
            return $errors;
        }

        $senderId = email_exists($fieldMappings['sender_email']);

        if ($senderId === false) {
            return [
                'response'    => __('Sender not found with provided email', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        $receiverEmails = array_map('trim', explode(',', $fieldMappings['receiver_emails']));
        $receiverIds = [];

        foreach ($receiverEmails as $receiverEmail) {
            if (!is_email($receiverEmail)) {
                return [
                    'response'    => __('Invalid receiver email.', 'bit-pi'),
                    'payload'     => $fieldMappings,
                    'status_code' => 400
                ];
            }

            $receiverId = email_exists($receiverEmail);
            if (!$receiverId) {
                return [
                    'response'    => __('User not found with provided email.', 'bit-pi'),
                    'payload'     => $fieldMappings,
                    'status_code' => 400
                ];
            }

            $receiverIds[] = $receiverId;
        }

        if (!\function_exists('messages_new_message')) {
            return [
                'response'    => __('BuddyBoss message module is not active.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        $isMessageSent = messages_new_message(
            [
                'sender_id'  => $senderId,
                'recipients' => $receiverIds,
                'subject'    => $fieldMappings['message_subject'],
                'content'    => $fieldMappings['message_content'],
                'error_type' => 'wp_error'
            ]
        );

        if (!$isMessageSent) {
            return [
                'response'    => __('Failed to send message.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        return [
            'response'    => __('Message sent successfully.', 'bit-pi'),
            'payload'     => $fieldMappings,
            'status_code' => 200
        ];
    }

    public function sendNotificationToAllMembersOfGroup(): array
    {
        $fieldMappings = $this->nodeInfoProvider->getFieldMapData();
        $groupId = absint($this->nodeInfoProvider->getFieldMapConfigs('group.value'));

        $rules = [
            'sender_email'         => ['required', 'email'],
            'notification_content' => ['required', 'string']
        ];

        if ($errors = BuddyBossHelper::validateFieldMap($fieldMappings, $rules)) {
            return $errors;
        }

        if (empty($groupId)) {
            return [
                'response'    => __('Group ID is required.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        $senderId = email_exists($fieldMappings['sender_email']);

        if ($senderId === false) {
            return [
                'response'    => __('Sender user does not exist.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        if (!\function_exists('groups_get_group_members') || !\function_exists('bp_notifications_add_notification')) {
            return [
                'response'    => __('BuddyBoss core functions not found.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        $members = groups_get_group_members(['group_id' => $groupId]);
        if (!empty($members['members'])) {
            foreach ($members['members'] as $member) {
                $notificationId = bp_notifications_add_notification(
                    [
                        'user_id'           => $member->ID,
                        'item_id'           => $groupId,
                        'secondary_item_id' => $senderId,
                        'component_name'    => 'bit-flows',
                        'component_action'  => 'bit-flows_bb_notification',
                        'date_notified'     => bp_core_current_time(),
                        'is_new'            => 1,
                        'allow_duplicate'   => true,
                    ],
                );

                if ($notificationId) {
                    bp_notifications_update_meta($notificationId, 'bit-pi_notification_content', $fieldMappings['notification_content']);
                    bp_notifications_update_meta($notificationId, 'bit-pi_notification_link', $fieldMappings['notification_link'] ?? '');
                }
            }
        }

        return [
            'response'    => $members,
            'payload'     => $fieldMappings,
            'status_code' => 200
        ];
    }

    public function setUserExtendedProfile(): array
    {
        $fieldMappings = $this->nodeInfoProvider->getFieldMapRepeaters('field-map.value', false, true, 'fields');
        $userEmailConfig = $this->nodeInfoProvider->getFieldMapConfigs('user-email.value');
        $userEmail = MixInputHandler::replaceMixTagValue($userEmailConfig);

        if (empty($userEmail)) {
            return [
                'response'    => __('User email is required.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        if (empty($fieldMappings)) {
            return [
                'response'    => __('At least one field mapping is required.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        $userId = email_exists($userEmail);

        if (empty($userId)) {
            return [
                'response'    => __('User not found with provided email.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        if (!\function_exists('xprofile_set_field_data')) {
            return [
                'response'    => __('xprofile_set_field_data function not found.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        $updatedFields = [];

        foreach ($fieldMappings as $fieldId => $value) {
            xprofile_set_field_data($fieldId, $userId, $value);

            if (\function_exists('xprofile_get_field_data')) {
                $updatedFields[$fieldId] = xprofile_get_field_data($fieldId, $userId);
            }
        }

        return [
            'response'    => ['updated_fields' => $updatedFields],
            'payload'     => $fieldMappings,
            'status_code' => 200
        ];
    }

    public function setUserStatus(): array
    {
        $fieldMappings = $this->nodeInfoProvider->getFieldMapData();

        $rules = [
            'user_email' => ['required', 'email'],
            'status'     => ['required', 'string']
        ];

        if ($errors = BuddyBossHelper::validateFieldMap($fieldMappings, $rules)) {
            return $errors;
        }

        if (!\function_exists('bp_is_active') || !class_exists('BP_Suspend_Member')) {
            return [
                'response'    => __('Required functions not found.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        $userId = email_exists($fieldMappings['user_email']);
        if (!$userId) {
            return [
                'response'    => __('User Not found.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        if (!bp_is_active('moderation')) {
            return [
                'response'    => __('To change members status in your network, please activate the Moderation component.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        if ($fieldMappings['status'] === 'suspend') {
            BP_Suspend_Member::suspend_user($userId);
        } elseif (\function_exists('bp_moderation_is_user_suspended') && bp_moderation_is_user_suspended($userId)) {
            BP_Suspend_Member::unsuspend_user($userId);
        }

        return [
            'response'    => Utility::jsonEncodeDecode(get_userdata($userId)),
            'payload'     => $fieldMappings,
            'status_code' => 200
        ];
    }

    public function stopFollowingUser(): array
    {
        $fieldMappings = $this->nodeInfoProvider->getFieldMapData();

        $rules = [
            'follower_email' => ['required', 'email'],
            'leader_email'   => ['required', 'email']
        ];

        if ($errors = BuddyBossHelper::validateFieldMap($fieldMappings, $rules)) {
            return $errors;
        }

        $follower = get_user_by('email', $fieldMappings['follower_email']);
        $leader = get_user_by('email', $fieldMappings['leader_email']);

        if (!$follower || !$leader) {
            return [
                'response'    => __('One or both users not found.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        $unfollowFunctionName = null;

        if (
            \function_exists('bp_follow_stop_following')
            && \function_exists('bp_is_active')
            && bp_is_active('follow')
        ) {
            $unfollowFunctionName = 'bp_follow_stop_following';
        } elseif (\function_exists('bp_stop_following')) {
            $unfollowFunctionName = 'bp_stop_following';
        }

        if (!$unfollowFunctionName) {
            return [
                'response'    => __('BuddyBoss Follow functions not available.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400,
            ];
        }

        $result = $unfollowFunctionName(
            [
                'follower_id' => $follower->ID,
                'leader_id'   => $leader->ID
            ]
        );

        return [
            'response'    => $result ? __('Stopped following successfully.', 'bit-pi') : __('Failed to stop following.', 'bit-pi'),
            'payload'     => $fieldMappings,
            'status_code' => $result ? 200 : 400
        ];
    }

    public function subscribeUserToForum(): array
    {
        $fieldMappings = $this->nodeInfoProvider->getFieldMapData();
        $forumId = $this->nodeInfoProvider->getFieldMapConfigs('forum-id.value');

        $rules = [
            'user_email' => ['required', 'email'],
        ];

        if ($errors = BuddyBossHelper::validateFieldMap($fieldMappings, $rules)) {
            return $errors;
        }

        if (empty($forumId)) {
            return [
                'response'    => __('Forum ID is required.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        $userId = email_exists($fieldMappings['user_email']);

        if ($userId === false) {
            return [
                'response'    => __('User not found with provided email.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        if (!\function_exists('bbp_add_user_forum_subscription')) {
            return [
                'response'    => __('Required BuddyBoss functions are not available.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        $result = bbp_add_user_forum_subscription($userId, $forumId);

        return [
            'response'    => $result ? __('User subscribed to forum successfully.', 'bit-pi') : __('Failed to subscribe user to forum.', 'bit-pi'),
            'payload'     => $fieldMappings,
            'status_code' => $result ? 200 : 400
        ];
    }

    /**
     * Handle posting activity feed actions.
     *
     * @param array $fieldMappings
     * @param string $component
     * @param null|int $groupId
     * @param null|int $userActivityId
     *
     * @return array
     */
    private static function handlePostActivityFeedActions($fieldMappings, $component = 'activity', $groupId = null, $userActivityId = null)
    {
        $userId = email_exists($fieldMappings['author_email']);

        if ($userId === false) {
            return [
                'response'    => __('User not found with provided email.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        if (!\function_exists('bp_activity_add')) {
            return [
                'response'    => __('BuddyBoss Activity functions not found.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        $payload = BuddyBossHelper::prepareActivityPayload($fieldMappings, $component, $userId, $groupId, $userActivityId);
        $activityId = bp_activity_add($payload);

        if (!$activityId) {
            return [
                'response'    => __('Failed to add activity.', 'bit-pi'),
                'payload'     => $fieldMappings,
                'status_code' => 400
            ];
        }

        $response = BuddyBossHelper::preparedPostActionResponse($activityId, $userId, $groupId);

        return [
            'response'    => $response,
            'payload'     => $fieldMappings,
            'status_code' => 200
        ];
    }
}
