<?php

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

use ElementorPro\Core\Utils;
use Itgalaxy\PluginCommon\ActionSchedulerHelper;
use Itgalaxy\PluginCommon\AnalyticsHelper;

class Helper
{
    /**
     * @param string $message
     * @param mixed  $data
     * @param string $type
     *
     * @return void
     */
    public static function log($message, $data = [], $type = 'info')
    {
        $settings = \get_option(Bootstrap::OPTIONS_KEY, []);
        $enableLogging = isset($settings['enabled_logging']) && (int) $settings['enabled_logging'] === 1;

        if (!$enableLogging) {
            return;
        }

        try {
            Bootstrap::$common->logger->log('infusion', $message, (array) $data, $type);
        } catch (\Exception $exception) {
            // Nothing
        }
    }

    /**
     * @psalm-suppress UndefinedDocblockClass
     *
     * @param array                                           $fields
     * @param \ElementorPro\Modules\Forms\Classes\Form_Record $record
     * @param string                                          $additionalKey
     *
     * @return array
     */
    public static function resolveFieldValues($fields, $record, $additionalKey = '')
    {
        $recordSettings = $record->get('form_settings');
        $sendFields = [];

        foreach ($fields as $key => $field) {
            $value = isset($recordSettings['el_pro_infusionsoft_' . $additionalKey . $key])
                ? $recordSettings['el_pro_infusionsoft_' . $additionalKey . $key]
                : '';

            $value = $record->replace_setting_shortcodes(trim($value));
            $value = self::replaceAdditionalTags($value, $recordSettings);

            if ($value === '') {
                continue;
            }

            if (empty($field['group'])) {
                $sendFields[$key] = $value;
            } else {
                if (!isset($sendFields[$field['group']])) {
                    $sendFields[$field['group']] = [];
                }

                switch ($field['group']) {
                    case 'email_addresses':
                        $sendFields[$field['group']][] = [
                            'email' => $value,
                            'field' => $key,
                        ];
                        break;
                    case 'phone_numbers':
                    case 'fax_numbers':
                        $sendFields[$field['group']][] = [
                            'number' => $value,
                            'field' => $key,
                        ];
                        break;
                    case 'social_accounts':
                        $sendFields[$field['group']][] = [
                            'name' => $value,
                            'type' => $key,
                        ];
                        break;
                    case 'addresses':
                        /** @psalm-suppress InvalidArrayOffset */
                        $sendFields[$field['group']][0]['field'] = 'BILLING';

                        /** @psalm-suppress InvalidArrayOffset */
                        $sendFields[$field['group']][0][$key] = $value;
                        break;
                    default:
                        // Nothing
                        break;
                }
            }
        }

        // custom fields
        $fields = \get_option(Bootstrap::CONTACT_CUSTOM_FIELDS_KEY, []);

        foreach ($fields as $field) {
            if (!is_array($field)) {
                continue;
            }

            $value = isset($recordSettings['el_pro_infusionsoft_' . $additionalKey . 'custom_fields_' . $field['id']])
                ? $recordSettings['el_pro_infusionsoft_' . $additionalKey . 'custom_fields_' . $field['id']]
                : '';

            $value = $record->replace_setting_shortcodes(trim($value));
            $value = self::allFieldsShortcode($value, $record);
            $value = self::replaceAdditionalTags($value, $recordSettings);

            if ($value === '') {
                continue;
            }

            switch ($field['field_type']) {
                case 'Date':
                    $value = date_i18n('m/d/Y', strtotime($value));
                    break;
                case 'Radio':
                case 'MultiSelect':
                    $explodedField = explode(', ', $value);
                    $resolveValues = [];

                    $ids = \array_column($field['options'], 'id');
                    $labels = \array_column($field['options'], 'label');

                    foreach ($explodedField as $explodeValue) {
                        if (array_search($explodeValue, $ids) !== false) {
                            $resolveValues[] = $explodeValue;
                        } elseif (array_search($explodeValue, $labels) !== false) {
                            $resolveValues[] = $ids[array_search($explodeValue, $labels)];
                        }
                    }

                    if ($resolveValues) {
                        $value =
                            $field['field_type'] === 'Dropdown'
                                ? $resolveValues[0]
                                : $resolveValues;
                    } else {
                        $value =
                            $field['field_type'] === 'Dropdown'
                                ? ''
                                : [];
                    }

                    break;
            }

            if ($value) {
                $sendFields['custom_fields'][] = [
                    'content' => $value,
                    'id' => (int) $field['id'],
                ];
            }
        }

        return $sendFields;
    }

    /**
     * @return bool
     */
    public static function isVerify()
    {
        $value = \get_site_option(Bootstrap::PURCHASE_CODE_OPTIONS_KEY);

        if (!empty($value)) {
            return true;
        }

        return false;
    }

    /**
     * @return string
     */
    public static function nonVerifyText()
    {
        return esc_html__(
            'Please verify the purchase code on the plugin integration settings page - ',
            'el-pro-form-infusionsoft-integration'
        )
            . admin_url()
            . 'admin.php?page=' . Bootstrap::OPTIONS_KEY . '#itglx-license-verify';
    }

    /**
     * @param string $value
     * @param array  $recordSettings
     *
     * @return string
     */
    public static function replaceAdditionalTags($value, $recordSettings)
    {
        $replaceArray = [
            '[utm_source]' => '',
            '[utm_medium]' => '',
            '[utm_campaign]' => '',
            '[utm_term]' => '',
            '[utm_content]' => '',
            '[roistat_visit]' => AnalyticsHelper::getCookieRoistatVisit(),
            '[yandexClientID]' => AnalyticsHelper::getCookieYandexClientId(),
            '[_fbp]' => isset($_COOKIE['_fbp']) ? \wp_unslash($_COOKIE['_fbp']) : '',
            '[_fbc]' => isset($_COOKIE['_fbc']) ? \wp_unslash($_COOKIE['_fbc']) : '',
            '[gaClientID]' => AnalyticsHelper::getGetGaClientIdFromCookie(),
            '[form_name]' => isset($recordSettings['form_name']) ? $recordSettings['form_name'] : '',
            '[meta_page_url]' => isset($_POST['referrer']) ? $_POST['referrer'] : '',
            '[meta_user_agent]' => $_SERVER['HTTP_USER_AGENT'],
        ];

        if (class_exists('\\ElementorPro\\Core\\Utils')) {
            /** @psalm-suppress UndefinedClass */
            $replaceArray['[meta_remote_ip]'] = Utils::get_client_ip();
        }

        if (!empty($_COOKIE[Bootstrap::UTM_COOKIES])) {
            $utmParams = json_decode(wp_unslash($_COOKIE[Bootstrap::UTM_COOKIES]), true);

            foreach ($utmParams as $key => $valueUtm) {
                $replaceArray['[' . $key . ']'] = rawurldecode(wp_unslash($valueUtm));
            }
        }

        /** @psalm-suppress InvalidArgument */
        return str_replace(array_keys($replaceArray), array_values($replaceArray), $value);
    }

    /**
     * @psalm-suppress UndefinedDocblockClass
     *
     * @param string                                          $value
     * @param \ElementorPro\Modules\Forms\Classes\Form_Record $record
     *
     * @return string
     */
    public static function allFieldsShortcode($value, $record)
    {
        if (strpos($value, '[all-fields]') === false) {
            return $value;
        }

        $text = [];

        foreach ($record->get('fields') as $field) {
            $formatted = self::fieldFormatted($field);

            if ($formatted) {
                $text[] = $formatted;
            }
        }

        return str_replace('[all-fields]', implode("\n", $text), $value);
    }

    /**
     * @psalm-suppress UndefinedDocblockClass
     *
     * @param \ElementorPro\Modules\Forms\Classes\Form_Record $record
     *
     * @return array
     */
    public static function resolveFilesList($record)
    {
        $files = [];

        foreach ($record->get('files') as $file) {
            if (empty($file['path'])) {
                continue;
            }

            foreach ($file['path'] as $path) {
                $files[] = $path;
            }
        }

        return $files;
    }

    /**
     * @return bool
     */
    public static function isActive()
    {
        $settings = \get_option(Bootstrap::OPTIONS_KEY, []);
        $refreshToken = \get_option(Bootstrap::REFRESH_TOKEN_KEY, '');

        return !empty($settings['api-key'])
            && !empty($settings['api-secret'])
            && !empty($refreshToken);
    }

    /**
     * @param array  $fields
     * @param array  $formSettings
     * @param string $type
     * @param int    $formID
     *
     * @return array
     */
    public static function sendProcess($fields, $formSettings, $type, $formID)
    {
        $settings = \get_option(Bootstrap::OPTIONS_KEY, []);

        if (!empty($settings['send_type']) && $settings['send_type'] === 'wp_cron') {
            Helper::log('register send form event - ' . $formID . ' - ' . $type, $fields);

            // register one time task
            ActionSchedulerHelper::registerSendFormAction(
                '_itglx_elpro_infusion_send_',
                Bootstrap::SEND_CRON_TASK,
                [
                    'fields' => $fields,
                    'settings' => $fields,
                    'type' => $type,
                ]
            );

            return [];
        }

        return Crm::send($fields, $formSettings, $type);
    }

    /**
     * @param array $field
     *
     * @return string
     */
    private static function fieldFormatted($field)
    {
        if (empty($field['value'])) {
            return '';
        }

        $formatted = '';

        if (!empty($field['title'])) {
            $formatted = sprintf('%s: %s', $field['title'], $field['value']);
        } elseif (!empty($field['value'])) {
            $formatted = sprintf('%s', $field['value']);
        }

        return $formatted;
    }
}
