<?php

namespace CadeauBienvenue\EventListeners;

use CadeauBienvenue\CadeauBienvenue;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Thelia\Core\Event\Coupon\CouponCreateOrUpdateEvent;
use Thelia\Core\Event\Customer\CustomerCreateOrUpdateEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\HttpFoundation\Request;
use Thelia\Core\HttpFoundation\Response;
use Thelia\Mailer\MailerFactory;
use Thelia\Model\ConfigQuery;


class NewCustomerListener implements EventSubscriberInterface
{
    protected $request;

    /**  @var MailerFactory */
    protected $mailer;

    /** @var EventDispatcherInterface */
    protected $dispatcher;

    public function __construct(Request $request, MailerFactory $mailer, EventDispatcherInterface $dispatcher)
    {
        $this->request = $request;
        $this->mailer = $mailer;
        $this->dispatcher = $dispatcher;
    }

    public static function getSubscribedEvents()
    {
        return array(
            TheliaEvents::CUSTOMER_CREATEACCOUNT => array(
                'createAccount', 100
            ),
        );
    }

    /**
     * @param CustomerCreateOrUpdateEvent $event
     * @param $eventName
     * @param EventDispatcherInterface $dispatcher
     */
    public function createAccount(CustomerCreateOrUpdateEvent $event, $eventName, EventDispatcherInterface $dispatcher)
    {
        $customer = $event->getCustomer();

        $couponCode = substr(str_shuffle(md5(time())), 0, 14);
        $discountAmount = ConfigQuery::create()->filterByName(CadeauBienvenue::VARIABLE_MONTANT_CODE_PROMO)->findOne()->getValue();
        $couponServiceId = 'thelia.coupon.type.remove_x_amount';
        $effects = [ 'amount' =>  $discountAmount];
        $dateExpiration = (new \DateTime())->add(new \DateInterval('P1Y'));      // Expiration dans 1 an

        $couponEvent = new CouponCreateOrUpdateEvent(
            $couponCode, // Code
            $couponServiceId, // $serviceId
            'Offre de bienvenue', // $title
            $effects, // $effects
            'Code promotion pour un nouveau client', // $shortDescription
            sprintf('Code promo de bienvenue pour le client : %s %s (%d)',$customer->getFirstname(), $customer->getLastname(), $customer->getId()), // $description
            true, // $isEnabled
            $dateExpiration, // $expirationDate
            false, // $isAvailableOnSpecialOffers
            false, // $isCumulative
            false, // $isRemovingPostage,
            1, // $maxUsage,
            $customer->getLocale(), // $locale,
            [], // $freeShippingForCountries,
            [], // $freeShippingForMethods,
            1 // $perCustomerUsageCount,
        );
        $this->dispatcher->dispatch(TheliaEvents::COUPON_CREATE, $couponEvent);

        // Envoyer le mail au client
        $this->mailer->sendEmailToCustomer(
            CadeauBienvenue::MESSAGE_MAIL_CLIENT,
            $customer,
            [
                'customer_id' => $customer->getId(),
                'montant' => $discountAmount,
                'date_validite' => $dateExpiration,
                'code_promo' => $couponCode
            ]
        );
    }
}
