<?php

namespace KupShop\UserBundle\Util;

use KupShop\IncomakerBundle\Util\IncomakerUtil;
use KupShop\KupShopBundle\Email\NewsletterSubscribeEmail;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use KupShop\MailerLiteBundle\MailerLite;
use KupShop\UserBundle\Event\UserNewsletterEvent;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Contracts\Service\Attribute\Required;

class UserConsent
{
    protected $mailerlite;
    protected $incomaker;

    #[Required]
    public EventDispatcherInterface $eventDispatcher;

    /** @var SessionInterface */
    private $session;

    /**
     * @required
     */
    public function setSession(SessionInterface $session): void
    {
        $this->session = $session;
    }

    /**
     * @required
     */
    public function setMailerlite(?MailerLite $mailerlite)
    {
        $this->mailerlite = $mailerlite;
    }

    /**
     * @required
     */
    public function setIncomaker(?IncomakerUtil $incomakerUtil)
    {
        $this->incomaker = $incomakerUtil;
    }

    public function updateNewsletter($userId, $newsletter = 'N', $new_user = true, $confirmed = false)
    {
        $user = \User::createFromId($userId);

        if ($new_user && $this->incomaker) {
            $this->incomaker->addUser($user, $newsletter);
        }

        if (($newsletter == 'Y') && ($user->get_news == 'N') && !$confirmed) {
            if (is_null($user->date_subscribe)) {
                return $this->sendConfirmationEmail($user->email);
            }
        }

        $get_news = $user->get_news;
        if ($new_user || ($get_news != $newsletter)) {
            $qb = sqlQueryBuilder()->update('users')
                ->set('get_news', ':news')->setParameter('news', $newsletter)
                ->set('date_updated', 'NOW()')
                ->where('id = :id')->setParameter('id', $userId);
            if ($newsletter == 'Y') {
                $qb->set('date_subscribe', 'NOW()');
            }
            if ($newsletter == 'N') {
                $qb->set('date_unsubscribe', 'NOW()');
            }

            $this->eventDispatcher->dispatch(
                new UserNewsletterEvent($user->email),
                $newsletter == 'Y' ? UserNewsletterEvent::SUBSCRIBED : UserNewsletterEvent::UNSUBSCRIBED
            );
            $qb->execute();
        }

        $result = true;

        if ($newsletter == 'N') {
            if ($new_user || ($get_news == $newsletter)) {
                return $result;
            }
        }

        if (findModule(\Modules::MAILERLITE)) {
            if ($this->mailerlite->error) {
                $result = false;
            } else {
                $mailerlite_update = $this->mailerlite->updateUser($user, $newsletter);
                $result = $mailerlite_update;
            }
        }

        if (findModule(\Modules::INCOMAKER)) {
            if ($new_user || ($get_news != $newsletter)) {
                $incomaker_update = $this->incomaker->updateUser($user, $newsletter);
                $result &= $incomaker_update;
            }
        }

        return $result;
    }

    public function sendConfirmationEmail($email)
    {
        $today = new \DateTime();
        $today = $today->format('d.m.Y');
        $code = md5($email.'-'.$today);

        $emailService = ServiceContainer::getService(NewsletterSubscribeEmail::class);
        $message = $emailService->getEmail([
            'OVEROVACI_ADRESA' => path('kupshop_content_newsletter_subscribe', ['code' => $code, 'email' => $email], 0),
            'EMAIL_UZIVATELE' => $email,
        ]);
        $message['to'] = $email;
        $emailService->sendEmail($message);

        if (!isAdministration()) {
            addUserMessage(translate('emailSuccessSent', 'newsletter'), 'success');
        }

        return true;
    }
}
