<?php

namespace App\Service;

use App\Model\DataObject\User;
use App\Tool\Utils;
use Pimcore\File;
use Pimcore\Bundle\ApplicationLoggerBundle\ApplicationLogger;
use Pimcore\Logger;
use Pimcore\Translation\Translator;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;

class UserManager
{
	const ROOT_FOLDER_ID = 3;

	/**
	 * @var Request
	 */
	protected $request;

	/**
	 * @param Translator        $translator
	 * @param MailManager       $mailManager
	 * @param NewsletterManager $newsletterManager
	 * @param RequestStack      $requestStack
	 */
	public function __construct(
		protected Translator $translator,
		protected MailManager $mailManager,
		protected NewsletterManager $newsletterManager,
		protected ApplicationLogger $applicationLogger,
		protected RequestStack $requestStack
	) {
		$this->request = $requestStack->getCurrentRequest();
	}

	/**
	 * @param array $data
	 *
	 * @return bool
	 */
	public function createUser($data)
	{
		$data['activationCode'] = uniqid();
		try {
			$user = User::create($data);
			$user->setKey(File::getValidFilename($data['email']));
			$user->setParentId(self::ROOT_FOLDER_ID);
			$user->setPublished(false);
			$user->save();

			if (!empty($data['newsletter'])) {
				$this->newsletterManager->subscribe($data);
			}

			$this->mailManager->sendMail('/notifikace/registrace', $data['lang'], $data['email'], null, [
				'siteUrl' => $this->request->getSchemeAndHttpHost().Utils::docUrl('/', $data['lang']),
				'activationUrl' => $this->request->getSchemeAndHttpHost().Utils::url('activate-account', [
					'language' => $data['lang'],
					'code' => $data['activationCode'],
				]),
				'user' => $user,
			]);

			return true;
		} catch (\Exception $e) {
			$this->applicationLogger->error('USER REGISTRATION - '.$e->getMessage()."\n".$e->getTraceAsString());

			return false;
		}
	}
}
