<?php
/**
 * Created by PhpStorm.
 * User: danielknudsen
 * Date: 05.04.18
 * Time: 13:09
 */
namespace App\Controller;

use App\Entity\Catalogue;
use App\Entity\User;
use App\Entity\UserType;
use App\Entity\UserWorksheet;
use App\Repository\UserRepository;
use App\Repository\UserTypeRepository;
use App\Utils\Utils;
use Psr\Log\LoggerInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Routing\Annotation\Route;
use Twig\Environment;

/**
 * @Security("is_granted('ROLE_ADMIN')")
 * @Route("/admin")
 */
class AdminController extends AbstractController
{
    /**
     * @Route("/dashboard", name="admin_start")
     */
    public function showAdminStartAction()
    {
        $users = $this->getDoctrine()->getRepository(User::class)->
                    findBy(['userType' => UserTypeRepository::getUserType($this->getDoctrine()->getManager(), UserTypeRepository::USER_TYPE_USER)]);
        $users = array_reverse($users);

        return $this->render('pages-admin/admin_start.html.twig',
            [
                'users' => $users
            ]
        );
    }

    /**
     * @Route("/add-user", name="admin_add_user")
     */
    public function addUser(Request $request)
    {
        $dateInThreeYears = new \DateTime('now', new \DateTimeZone('Europe/Berlin'));
        $dateInThreeYears->modify('+3 year');
        return $this->render('pages-admin/admin_create_user.html.twig', [
            'dateInThreeYears' => $dateInThreeYears
        ]);
    }

    /**
     * @Route("/user", name="admin_create_user", methods={"POST"})
     *
     * @param Request $request
     * @param MailerInterface $mailer
     * @return \Symfony\Component\HttpFoundation\JsonResponse
     * @throws \Symfony\Component\Mailer\Exception\TransportExceptionInterface
     */
    public function createUser(Request $request, MailerInterface $mailer, LoggerInterface $logger)
    {
        $content = (object) $request->request->all();
        $em = $this->getDoctrine()->getManager();
        /** @var User $currentUser */
        $currentUser = $this->getUser();
        try {
            /** @var UserType $userType */
            $userType = UserTypeRepository::getUserType($em, UserTypeRepository::USER_TYPE_USER);
            $password = Utils::generateStrongPassword();
            $newUser = new User($em, $userType, $content->email, $content->firstname, $content->lastname, $password, $currentUser);
            $newUser = UserRepository::setClientData($newUser, $content);
            $em->persist($newUser);

            $email = (new TemplatedEmail())
                ->from("MPPTool by RealFM <".$_ENV['SYS_EMAIL'].">")
                ->to($_ENV['APP_ENV'] === 'prod' ? $content->email : $_ENV['DEV_EMAIL'])
                ->cc($_ENV['SYS_EMAIL'])
                ->subject('Ihre Registrierung bei MPPTool')
                ->htmlTemplate('email/new_user_email.html.twig')
                ->context(
                    [
                        'user' => $newUser,
                        'password' => $password,
                        'adminEmail' => $_ENV['ADMIN_EMAIL'],
                        'url' => $_SERVER['HTTP_ORIGIN']
                    ]
                );
//            $email->SMTPOptions = array(
//                'ssl' => array(
//                    'verify_peer' => false,
//                    'verify_peer_name' => false,
//                    'allow_self_signed' => true
//                )
//            );
            try {
                $mailer->send($email);
            } catch (TransportExceptionInterface $e) {
                $logger->error($e->getDebug());
            }

            $em->flush();

        } catch (\Exception $e) {
            //return $this->json($e->getMessage(), 409);
            return $this->json('Email-Adresse entweder nicht valide oder bereits in Benutzung', 409);
        }
        return $this->json(true);
    }

    /**
     * @Route("/user", name="admin_edit_user", methods={"PATCH"})
     *
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\JsonResponse
     */
    public function editUser(Request $request)
    {
        $content = (object) $request->request->all();
        $em = $this->getDoctrine()->getManager();

        /** @var User $user */
        $user = $this->getDoctrine()->getRepository(User::class)->find($content->id);
        if ($user === null) {
            return $this->json('Benutzer nicht gefunden', 409);
        }

        try {
            $user->setEmail($em, $content->email);
        } catch (\Exception $e) {
            return $this->json('Email-Adresse entweder nicht valide oder bereits in Benutzung', 409);
        }

        $user = UserRepository::setClientData($user, $content);
        $em->flush();
        return $this->json(true);
    }

    /**
     * @Route("/new-password", name="admin_new_password", methods={"POST"})
     *
     * @param Request $request
     * @param MailerInterface $mailer
     * @return \Symfony\Component\HttpFoundation\JsonResponse
     * @throws \Symfony\Component\Mailer\Exception\TransportExceptionInterface
     */
    public function newPassword(Request $request, MailerInterface $mailer, \Swift_Mailer $swiftMailer)
    {
        $content = (object) $request->request->all();
        $em = $this->getDoctrine()->getManager();

        /** @var User $user */
        $user = $this->getDoctrine()->getRepository(User::class)->find($content->id);
        if ($user === null) {
            return $this->json('Benutzer nicht gefunden', 409);
        }

        try {
            $password = Utils::generateStrongPassword();
            $user->setPassword($password);

            $email = (new TemplatedEmail())
                ->from($_ENV['SYS_EMAIL'])
                ->to($_ENV['APP_ENV'] === 'prod' ? $user->getEmail() : $_ENV['DEV_EMAIL'])
                //->cc($_ENV['ADMIN_EMAIL'])
                ->subject('Ihr Zugang bei MPPTool')
                ->htmlTemplate('email/new_password_email.html.twig')
                ->context(
                    [
                        'user' => $user,
                        'password' => $password,
                        'adminEmail' => $_ENV['ADMIN_EMAIL'],
                        'url' => $_SERVER['HTTP_ORIGIN']
                    ]
                );
            $email->SMTPOptions = array(
                'ssl' => array(
                    'verify_peer' => false,
                    'verify_peer_name' => false,
                    'allow_self_signed' => true
                )
            );

            $mailer->send($email);

//            $message = (new \Swift_Message('Ihr Zugang bei My MPP'))
//                ->setFrom($_ENV['SYS_EMAIL'])
//                ->setTo($_ENV['APP_ENV'] === 'prod' ? $user->getEmail() : $_ENV['DEV_EMAIL'])
//                ->setBody(
//                    $this->renderView(
//                    // templates/emails/registration.html.twig
//                        'email/new_password_email.html.twig',
//                        [
//                            'user' => $user,
//                            'password' => $password,
//                            'adminEmail' => $_ENV['ADMIN_EMAIL']
//                        ]
//                    ),
//                    'text/html'
//                );
//
//            $swiftMailer->send($message);



            $em->flush();
        } catch (\Exception $e) {
            return $this->json($e->getMessage(), 409);
            //return $this->json('Emailadresse entweder nicht valide oder bereits in Benutzung', 409);
        }

        return $this->json(true);
    }

    /**
     * @Route("/get-user-catalogue/{userWorksheetId}", name="admin_user_worksheet", methods={"GET"})
     */
    public function getUserCatalogue(Environment $twig, $userWorksheetId)
    {
        /** @var UserWorksheet $worksheet */
        $worksheet = $this->getDoctrine()->getRepository(UserWorksheet::class)->find($userWorksheetId);
        if ($worksheet === null) {
            return $this->json('Katalog exitiert nicht', 409);
        }
        $dompdf = UserRepository::renderWorksheetPDF($twig, $worksheet);
        // Output the generated PDF to Browser (force download)
        $fileName = "Arbeitsblatt_".$worksheet->getUser()->getId()."_".$worksheet->getCreationDate()->format('Y-m-d_H-i');
        $dompdf->stream($fileName, [
            "Attachment" => true
        ]);
        // NOTE: This is required, since method need a result!
        exit(0);
    }
}