<?php

namespace CleverReach\WooCommerce\Components\Services\BusinessLogic\Usersnap;

use CleverReach\WooCommerce\Components\Services\BusinessLogic\Configuration\Config_Service;
use CleverReach\WooCommerce\Components\Util\Shop_Helper;
use CleverReach\WooCommerce\IntegrationCore\BusinessLogic\Authorization\Http\UserProxy;
use CleverReach\WooCommerce\IntegrationCore\Infrastructure\ServiceRegister;
use WC;

class Usersnap_Service {

	const USERSNAP_KEY = 'cc97c604-23e9-41e9-bd84-218745909e03';

	/**
	 * Returns Usersnap load key.
	 *
	 * @return string|null
	 */
	public function get_load_key() {
		/** @var Config_Service $config */
		$config = ServiceRegister::getService(Config_Service::CLASS_NAME);

		return $config->get_usersnap_loadkey();
	}

	/**
	 * Returns Usersnap context metadata.
	 *
	 * @return array
	 */
	public function get_context() {
		$meta = array(
			'tenantId'           => get_site_url(),
			'pageContextUrl'     => get_site_url(),
			'pluginVersion'      => Shop_Helper::get_plugin_version(),
			'wordpressVersion'   => get_bloginfo('version'),
			'woocommerceVersion' => defined('WC_VERSION') ? WC_VERSION : null,
			'phpVersion'         => PHP_VERSION,
		);

		try {
			$user_info = $this->get_user_proxy()->getUserInfo();
			if ($user_info) {
				$meta['client_id'] = $user_info->getId();
				$meta['email']     = $user_info->getEmail();
			}
		} catch (\Throwable $e) {
		}

		return $meta;
	}

	/**
	 * Returns load key.
	 *
	 * @return string
	 */
	public function get_key()
	{
		return self::USERSNAP_KEY;
	}

	/**
	 * Returns current admin email if available.
	 *
	 * @return string|null
	 */
	private function get_user_email() {
		$user_info = $this->get_user_proxy()->getUserInfo();

		return $user_info->getEmail();
	}

	/**
	 * Returns client id.
	 *
	 * @return string|null
	 */
	private function get_client_id() {
		$user_info = $this->get_user_proxy()->getUserInfo();

		return $user_info->getId();
	}

	/**
	 * Retrieves UserProxy service.
	 *
	 * @return UserProxy
	 */
	protected function get_user_proxy() {
		/**
		 * User proxy.
		 *
		 * @var UserProxy $proxy
		 */
		$proxy = ServiceRegister::getService( UserProxy::CLASS_NAME );

		return $proxy;
	}
}
