<?php

namespace App\Service;

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

class NewsletterManager
{
	/**
	 * Constants.
	 */
	const ROOT_FOLDER_ID = 6;

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

	/**
	 * @var Translator
	 */
	protected $translator;

	/**
	 * @var MailManager
	 */
	protected $mailManager;

	/**
	 * @var ApplicationLogger
	 */
	protected $applicationLogger;

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

	/**
	 * @param array $data
	 *
	 * @return bool
	 */
	public function subscribe($data)
	{
		try {
			$newsletter = NewsletterForm::getByEmail($data['email'], 1);
			if ($newsletter && $newsletter->getNewsletterConfirmed()) {
				return true;
			} else {
				$data = array_merge($data, [
					'subscribeCode' => uniqid(),
					'unsubscribeCode' => uniqid(),
				]);
				if(!$newsletter) {
					$newsletter = NewsletterForm::create($data);
					$newsletter->setCreationDate(time());
					$newsletter->setKey(File::getValidFilename($data['email']));
					$newsletter->setParentId(self::ROOT_FOLDER_ID);
					$newsletter->setPublished(true);
					$newsletter->setFirstname('');
					$newsletter->setLastname('');
					$newsletter->setGender('');
					$newsletter->setNewsletterConfirmed(false);
					$newsletter->setNewsletterActive(false);
					$newsletter->save();
				}
			}
			$confirmationUrl = $this->request->getSchemeAndHttpHost() . Utils::url('newsletter-confirm', [
				'code' => $newsletter->getSubscribeCode(),
			]);
			$this->mailManager->sendMail('/notifikace/newsletter/prihlaseni', $newsletter->getLang(), $newsletter->getEmail(), null, [
				'confirmationUrl' => $confirmationUrl,
			]);
		} catch (Throwable $t) {
			$this->applicationLogger->error($t->getMessage() . PHP_EOL . $t->getTraceAsString(), [
				'component' => 'Newsletter',
			]);
			return false;
		}
		return true;
	}

	/**
	 * @param string $code
	 *
	 * @return bool
	 */
	public function confirm($code)
	{
		if (!$newsletter = NewsletterForm::getBySubscribeCode($code, 1)) {
			return false;
		}
		try {
			$newsletter->setNewsletterConfirmed(true);
			$newsletter->setNewsletterActive(true);
			$newsletter->save();
			$unsubscribeUrl = $this->request->getSchemeAndHttpHost() . Utils::url('newsletter-unsubscribe', [
				'code' => $newsletter->getUnsubscribeCode(),
			]);
			$this->mailManager->sendMail('/notifikace/newsletter/potvrzeni-odberu', $newsletter->getLang(), $newsletter->getEmail(), null, [
				'unsubscribeUrl' => $unsubscribeUrl,
			]);
		} catch (Throwable $t) {
			$this->applicationLogger->error($t->getMessage() . PHP_EOL . $t->getTraceAsString(), [
				'component' => 'Newsletter',
			]);
			return false;
		}
		return true;
	}

	/**
	 * @param string $code
	 *
	 * @return bool
	 */
	public function unsubscribe($code)
	{
		if (!$newsletter = NewsletterForm::getByUnsubscribeCode($code, 1)) {
			return false;
		}
		try {
			$email = $newsletter->getEmail();
			$newsletter->delete();
			return $email;
		} catch (Throwable $t) {
			$this->applicationLogger->error($t->getMessage() . PHP_EOL . $t->getTraceAsString(), [
				'component' => 'Newsletter',
			]);
			return false;
		}
	}
}
