<?php

namespace BitApps\PiPro\src\Integrations\WishlistMember;

use BitApps\Pi\Helpers\Utility;
use BitApps\Pi\Deps\BitApps\WPValidator\Validator;

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


final class WishlistMemberHelper
{
    /**
     * Check if WishlistMember is installed.
     *
     * @return bool
     */
    public static function isPluginInstalled()
    {
        return class_exists('WLMAPI') || class_exists('WishListMember');
    }

    /**
     * Prepare membership data.
     *
     * @param int $userId
     * @param array|int $levelId
     *
     * @return null|array
     */
    public static function prepareMembershipData($userId, $levelId)
    {
        $userId = !empty($userId) ? $userId : get_current_user_id();
        $levelId = \is_array($levelId) ? reset($levelId) : $levelId;

        if (empty($userId) || empty($levelId)) {
            return;
        }

        $data = [
            'user' => Utility::getUserInfo($userId),
        ];

        if (\function_exists('wlmapi_get_level')) {
            $data['membership_level'] = wlmapi_get_level($levelId);
        }

        if (\function_exists('wlmapi_get_member')) {
            $data['member'] = wlmapi_get_member($userId);
        }

        if (isset($data['member']['Levels'][$levelId])) {
            $data['user_registered_date_in_level'] = $data['member']['Levels'][$levelId]->Timestamp ?? '';
        }

        return $data;
    }

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

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

    /**
     * Validate API functions.
     *
     * @param array|string $apiFunctions
     * @param null|array $payload
     *
     * @return null|array
     */
    public static function validateApiFunctions($apiFunctions, $payload = [])
    {
        if (\is_string($apiFunctions)) {
            $apiFunctions = [$apiFunctions];
        }

        foreach ($apiFunctions as $function) {
            if (!\function_exists($function)) {
                return [
                    // translators: %s: Function name
                    'response'    => \sprintf(__('WishlistMember API function %s is not available.', 'bit-pi'), $function),
                    'payload'     => $payload,
                    'status_code' => 400
                ];
            }
        }
    }
}
