<?php

namespace AppBundle\Controller\Admin;

use AppBundle\Form\Type\RecoveryType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

class RecoveryController extends Controller
{
    /**
     * @Template()
     *
     * @param Request $request
     * @return array()
     */
    public function indexAction(Request $request)
    {
        $form = $this->createForm(new RecoveryType());
        $form->handleRequest($request);

        if ($success = $form->isValid()) {
            $email = $form['email']->getData();
            $em = $this->getDoctrine()->getManager();
            $user = $em->getRepository('AppBundle:User')->findOneByEmail($email);

            if ($user && !$user->getIsRemoved()) {
                $user->generateActivationKey();
                $this->getMailerService()->sendRecoveryLinkEmail($user);

                $em->flush();

                $this->get('session')->getFlashBag()
                    ->add('notice', 'Email z linkiem resetującym hasło został wysłany. Będzie on aktywny 24h.');
                return $this->redirect($this->generateUrl('app_admin.security.login'));
            }
        }

        return array(
            'form' => $form->createView(),
            'error' => $success && (!isset($user) || isset($user) && $user->getIsRemoved() )
        );
    }

    /**
     * @param $userId
     * @param $activationKey
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function recoverAction($userId, $activationKey)
    {
        $em = $this->getDoctrine()->getManager();
        $user = $em->getRepository('AppBundle:User')->find($userId);
        $now = new \DateTime();

        if (!$user
            || $user->getActivationKey() != $activationKey
            || $now->diff($user->getActivationKeyCreatedAt())->h >= 24
        ) {
            $this->get('session')->getFlashBag()
                ->add('notice', 'Błędny lub nieaktywny link resetujący hasło.');
            return $this->redirect($this->generateUrl('app_admin.recovery.index'));
        }

        $password = $this->getPasswordService()->setRandomPassword($user);
        $user
            ->setActivationKey(null)
            ->setActivationKeyCreatedAt(null);
        $em->flush();

        $this->getMailerService()->sendRecoveryPasswordEmail($user, $password);

        $this->get('session')->getFlashBag()
            ->add('notice', 'Email z nowym hasłem został wysłany.');
        return $this->redirect($this->generateUrl('app_admin.security.login'));
    }

    /**
     * @return \AppBundle\Service\PasswordService
     */
    private function getPasswordService()
    {
        return $this->get('app.service.password');
    }

    /**
     * @return \AppBundle\Service\MailerService
     */
    private function getMailerService()
    {
        return $this->get('app.service.mailer');
    }
}