<?php

namespace BitApps\PiPro\src\Integrations\BuddyBoss\helper;

use BitApps\Pi\Helpers\Utility;
use BitApps\PiPro\Deps\BitApps\WPKit\Http\Response;
use BitApps\PiPro\Deps\BitApps\WPValidator\Validator;

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

final class BuddyBossHelper
{
    /**
     * Check if BuddyBoss plugin is installed.
     *
     * @return bool
     */
    public static function isPluginInstalled()
    {
        return \function_exists('buddypress') && isset(buddypress()->buddyboss) && buddypress()->buddyboss;
    }

    /**
     * Validate field map.
     *
     * @param array $fieldMappings
     * @param array $rules
     * @param array $payload
     *
     * @return null|array
     */
    public static function validateFieldMap($fieldMappings, $rules, $payload = null)
    {
        $validator = new Validator();
        $validation = $validator->make($fieldMappings, $rules);

        if ($validation->fails()) {
            return [
                'response'    => $validation->errors(),
                'payload'     => $payload ?? $fieldMappings,
                'status_code' => 400
            ];
        }
    }

    /**
     * Prepare post action response.
     *
     * @param mixed $activityId
     * @param mixed $userId
     * @param null|mixed $groupId
     *
     * @return array
     */
    public static function preparedPostActionResponse($activityId, $userId, $groupId = null)
    {
        $response = [
            'activity_id' => $activityId,
            'user_id'     => $userId,
        ];

        if ($groupId !== null) {
            $response['group_id'] = $groupId;
        }

        if (!\function_exists('bp_activity_get_specific') || !isset($response['activity_id'])) {
            return $response;
        }

        $activity = bp_activity_get_specific(['activity_ids' => $response['activity_id']]);

        if (!empty($activity['activities'])) {
            $response['activities'] = Utility::jsonEncodeDecode($activity);
        }

        return $response;
    }

    /**
     * Prepare activity payload.
     *
     * @param array $fieldMappings
     * @param mixed $component
     * @param null|mixed $userId
     * @param null|mixed $groupId
     * @param null|mixed $userActivityId
     *
     * @return array
     */
    public static function prepareActivityPayload($fieldMappings, $component = 'activity', $userId = null, $groupId = null, $userActivityId = null)
    {
        $payloadData = [
            'action'        => $fieldMappings['activity_action'] ?? '',
            'content'       => $fieldMappings['activity_content'] ?? '',
            'primary_link'  => $fieldMappings['activity_action_link'] ?? '',
            'hide_sitewide' => $fieldMappings['hide_sitewide'] ?? false,
            'component'     => $component,
            'type'          => 'activity_update',
        ];

        if ($groupId !== null) {
            $payloadData['user_id'] = $userId;
            $payloadData['item_id'] = $groupId;
        }

        if ($userActivityId !== null) {
            $payloadData['user_id'] = $userId;
            $payloadData['secondary_item_id'] = $userActivityId;
        }

        return $payloadData;
    }

    /**
     * Get BuddyBoss group types.
     *
     * @return Response
     */
    public static function getGroupsTypes()
    {
        if (!self::isPluginInstalled()) {
            return Response::error(__('BuddyBoss plugin is not active.', 'bit-pi'));
        }

        if (!\function_exists('bp_groups_get_group_types')) {
            return Response::error(__('BuddyBoss Group types functions not found.', 'bit-pi'));
        }

        $data = [];
        $types = bp_groups_get_group_types();

        foreach ($types as $key => $type) {
            $data[] = [
                'label' => $type,
                'value' => $key
            ];
        }

        return Response::success($data);
    }

    /**
     * Get all BuddyBoss groups.
     *
     * @return Response
     */
    public static function getAllGroups()
    {
        if (!self::isPluginInstalled()) {
            return Response::error(__('BuddyBoss plugin is not active.', 'bit-pi'));
        }

        if (!\function_exists('groups_get_groups')) {
            return Response::error(__('BuddyBoss Groups functions not found.', 'bit-pi'));
        }

        $groups = groups_get_groups();

        $data = [];
        if (!empty($groups['groups'])) {
            foreach ($groups['groups'] as $group) {
                $data[] = [
                    'label' => $group->name,
                    'value' => $group->id
                ];
            }
        }

        return Response::success($data);
    }

    /**
     * Get all BuddyBoss profile types.
     *
     * @return Response
     */
    public static function getAllProfileTypes()
    {
        if (!self::isPluginInstalled()) {
            return Response::error(__('BuddyBoss plugin is not active.', 'bit-pi'));
        }

        if (!\function_exists('bp_get_member_types')) {
            return Response::error(__('BuddyBoss member type functions not found.', 'bit-pi'));
        }

        $types = bp_get_member_types([]);
        $data = [];

        foreach ($types as $key => $type) {
            $data[] = [
                'label' => $type,
                'value' => $key
            ];
        }

        return Response::success($data);
    }

    /**
     * Get all BuddyBoss forums.
     *
     * @return Response
     */
    public static function getAllForums()
    {
        if (!self::isPluginInstalled()) {
            return Response::error(__('BuddyBoss plugin is not active.', 'bit-pi'));
        }

        if (!\function_exists('bbp_get_forum_post_type')) {
            return Response::error(__('BuddyBoss Forum functions not found.', 'bit-pi'));
        }

        $forums = get_posts(
            [
                'post_type'      => bbp_get_forum_post_type(),
                'posts_per_page' => -1,
                'post_status'    => 'publish'
            ]
        );

        $data = [];
        foreach ($forums as $forum) {
            $data[] = [
                'label' => $forum->post_title,
                'value' => $forum->ID
            ];
        }

        return Response::success($data);
    }

    /**
     * Get extended profile fields.
     *
     * @return Response
     */
    public static function getExtendedProfileFields()
    {
        if (!self::isPluginInstalled()) {
            return Response::error(__('BuddyBoss plugin is not active.', 'bit-pi'));
        }

        if (!\function_exists('bp_xprofile_get_groups')) {
            return Response::error(__('BuddyBoss Extended Profile functions not found.', 'bit-pi'));
        }

        $groups = bp_xprofile_get_groups(['fetch_fields' => true]);
        $data = [];

        foreach ($groups as $group) {
            if (!empty($group->fields)) {
                foreach ($group->fields as $field) {
                    $data[] = [
                        'value' => $field->id,
                        'label' => $field->name,
                    ];
                }
            }
        }

        return Response::success($data);
    }
}
