<?php

namespace Itgalaxy\Elementor\Form\Infusionsoft\Integration\Includes;

class Crm
{
    /**
     * @var array
     */
    private static $authorizationInfo = [];

    /**
     * @param array  $sendFields
     * @param array  $meta
     * @param string $currentType
     *
     * @return array
     */
    public static function send($sendFields, $meta, $currentType = 'contact')
    {
        self::$authorizationInfo = RequestHelper::getAuthInfo();

        if (empty(self::$authorizationInfo['access_token'])) {
            return [];
        }

        switch ($currentType) {
            case 'contact':
                if ($sendFields['send_type'] === 'create') {
                    $record = self::sendPostRequest('contacts', $sendFields['contact']);
                } else {
                    $sendFields['contact']['duplicate_option'] = 'Email';
                    $record = self::sendPutRequest('contacts', $sendFields['contact']);
                }

                if (is_array($record) && !empty($record['id'])) {
                    if (!empty($sendFields['tags'])) {
                        $tagIds = [];
                        $tags = explode(',', $sendFields['tags']);

                        foreach ($tags as $tag) {
                            $tag = trim($tag);
                            $tagResult = self::sendGetRequest('tags', ['name' => $tag]);

                            if (empty($tagResult['tags'])) {
                                $tagResult = self::sendPostRequest('tags', ['name' => $tag]);

                                if (is_array($tagResult) && !empty($tagResult['id'])) {
                                    $tagIds[] = $tagResult['id'];
                                }
                            } else {
                                $tagIds[] = $tagResult['tags'][0]['id'];
                            }
                        }

                        // apply tags to contact
                        if (!empty($tagIds)) {
                            self::sendPostRequest('contacts/' . $record['id'] . '/tags', ['tagIds' => $tagIds]);
                        }
                    }

                    if (!Helper::isVerify()) {
                        if (empty($sendFields['note'])) {
                            $sendFields['note'] = Helper::nonVerifyText();
                        } else {
                            $sendFields['note'] = Helper::nonVerifyText()
                                . "\n\n"
                                . $sendFields['note'];
                        }
                    }

                    if (!empty($sendFields['note'])) {
                        self::sendPostRequest('notes', ['contact_id' => $record['id'], 'body' => $sendFields['note']]);
                    }

                    if (!empty($sendFields['uploads'])) {
                        foreach ($sendFields['uploads'] as $path) {
                            $record = self::sendPostRequest(
                                'files',
                                [
                                    'file_name' => basename($path),
                                    'is_public' => false,
                                    'file_data' => base64_encode(file_get_contents($path)),
                                    'contact_id' => $record['id'],
                                    'file_association' => 'CONTACT',
                                ],
                                true
                            );
                        }
                    }

                    return $record;
                }

                break;
            default:
                // Nothing
                break;
        }

        return [];
    }

    /**
     * @param string $model
     * @param array  $fields
     * @param bool   $ignoreLog
     *
     * @return array|mixed
     */
    public static function sendPostRequest($model, $fields = [], $ignoreLog = false)
    {
        if (empty(self::$authorizationInfo)) {
            self::$authorizationInfo = RequestHelper::getAuthInfo();

            if (is_wp_error(self::$authorizationInfo)) {
                return self::$authorizationInfo;
            }

            if (empty(self::$authorizationInfo['access_token'])) {
                return self::$authorizationInfo;
            }
        }

        if (!$ignoreLog) {
            Helper::log('POST - ' . $model, $fields);
        } else {
            Helper::log('POST - ' . $model);
        }

        $response = wp_remote_post(
            'https://api.infusionsoft.com/crm/rest/v1/' . $model,
            [
                'headers' => array_merge(
                    RequestHelper::generateHeaders(self::$authorizationInfo),
                    [
                        'Content-Type' => 'application/json',
                    ]
                ),
                'body' => json_encode($fields),
                'timeout' => 20,
            ]
        );

        if (\is_wp_error($response)) {
            Helper::log('response `is_wp_error`', $response, 'error');

            return $response;
        }

        $body = wp_remote_retrieve_body($response);
        $code = (int) wp_remote_retrieve_response_code($response);

        if ($code < 200 || $code > 299) {
            Helper::log('response error', $body, 'error');
        } elseif (!$ignoreLog) {
            Helper::log('decode response', json_decode($body, true));
        }

        return json_decode($body, true);
    }

    /**
     * @param string $model
     * @param array  $fields
     *
     * @return array|mixed
     */
    public static function sendPutRequest($model, $fields = [])
    {
        if (empty(self::$authorizationInfo)) {
            self::$authorizationInfo = RequestHelper::getAuthInfo();

            if (is_wp_error(self::$authorizationInfo)) {
                return self::$authorizationInfo;
            }

            if (empty(self::$authorizationInfo['access_token'])) {
                return self::$authorizationInfo;
            }
        }

        Helper::log('PUT - ' . $model, $fields);

        $response = wp_remote_request(
            'https://api.infusionsoft.com/crm/rest/v1/' . $model,
            [
                'method' => 'PUT',
                'headers' => array_merge(
                    RequestHelper::generateHeaders(self::$authorizationInfo),
                    [
                        'Content-Type' => 'application/json',
                    ]
                ),
                'body' => json_encode($fields),
                'timeout' => 20,
            ]
        );

        if (\is_wp_error($response)) {
            Helper::log('response `is_wp_error`', $response, 'error');

            return $response;
        }

        $body = wp_remote_retrieve_body($response);
        $code = (int) wp_remote_retrieve_response_code($response);

        if ($code < 200 || $code > 299) {
            Helper::log('response error', $body, 'error');
        } else {
            Helper::log('decode response', json_decode($body, true));
        }

        return json_decode($body, true);
    }

    /**
     * @param string $model
     * @param array  $fields
     *
     * @return array|mixed
     */
    public static function sendGetRequest($model, $fields = [])
    {
        if (empty(self::$authorizationInfo)) {
            self::$authorizationInfo = RequestHelper::getAuthInfo();

            if (is_wp_error(self::$authorizationInfo)) {
                return self::$authorizationInfo;
            }

            if (empty(self::$authorizationInfo['access_token'])) {
                return self::$authorizationInfo;
            }
        }

        Helper::log('GET - ' . $model, $fields);

        $response = wp_remote_get(
            'https://api.infusionsoft.com/crm/rest/v1/' . $model,
            [
                'headers' => array_merge(
                    RequestHelper::generateHeaders(self::$authorizationInfo),
                    [
                        'Content-Type' => 'application/json',
                    ]
                ),
                'body' => $fields,
                'timeout' => 20,
            ]
        );

        if (\is_wp_error($response)) {
            Helper::log('response `is_wp_error`', $response, 'error');

            return $response;
        }

        $body = wp_remote_retrieve_body($response);
        $code = (int) wp_remote_retrieve_response_code($response);

        if ($code < 200 || $code > 299) {
            Helper::log('response error', $body, 'error');
        } else {
            Helper::log('decode response', json_decode($body, true));
        }

        return json_decode($body, true);
    }

    /**
     * @return void
     */
    public static function updateInformation()
    {
        $result = self::sendGetRequest('contacts/model');

        if (!empty($result['custom_fields'])) {
            \update_option(Bootstrap::CONTACT_CUSTOM_FIELDS_KEY, $result['custom_fields']);
        } else {
            \update_option(Bootstrap::CONTACT_CUSTOM_FIELDS_KEY, []);
        }
    }
}
