<?php



namespace Template\Controller;



use CoffeeCode\Router\Router;

use League\Plates\Engine;

use Doctrine\ORM\EntityManagerInterface;
use Exception;
use Template\Entity\Brand;

use Template\Entity\Config;

use Template\Entity\User;

use Template\Helper\FlashMessageTrait;

use Template\Services\Mailer;

use Template\Security\Guard;

class Admin 

{

    use FlashMessageTrait, Guard;

    

    private $view;

    private $router;

    private $entityManager;

    private $repository;

    private $repositoryBrand;

    private $repositoryConfig;

    

    public function __construct(EntityManagerInterface $entityManager)

    {

        $this->view = new Engine(__DIR__ . '/../../views/admin/');

        $this->entityManager = $entityManager;

        $this->repository = $entityManager->getRepository(User::class);

        $this->repositoryBrand = $entityManager->getRepository(Brand::class);

        $this->repositoryConfig = $entityManager->getRepository(Config::class);

        $this->router = new Router(URL_BASE);

    }

    

    public function index()

    {

        echo $this->view->render('index', [

            'brand' => $this->repositoryBrand->findOneBy(['id' => 1]),

            'setting' => $this->repositoryConfig->findOneBy(['id' => 1])

            ]

        );

        

        if (isset($_SESSION['logado']) && $_SESSION['logado']) {

            $this->router->redirect("/dashboard");

        }

    }

    

    public function persist($data)

    {

        $user = filter_var(

            $data['user'],

            FILTER_SANITIZE_STRING

        );

        

        $password = filter_var(

            $data['password'],

            FILTER_SANITIZE_STRING

        );

        

        $password = password_hash($password, PASSWORD_DEFAULT);

        

        $admin = new User();

        $admin->setUser($user);

        $admin->setPassword($password);

        $this->entityManager->persist($admin);

        $this->entityManager->flush();

    }

    

    public function login($data)

    {

        $user = filter_var(

            $data['user'],

            FILTER_SANITIZE_STRING

        );

        

        $password = filter_var(

            $data['password'],

            FILTER_SANITIZE_STRING

        );

        

        /** @var User $user */

        $user = $this->repository->findOneBy(['user' => $user]);

        

        if (is_null($user) || !$user->verify_password($password)) {

            $this->defineMensagem('danger', 'Usuário ou senha inválidos');

            

            $this->router->redirect("/admin");

        }

        

        $_SESSION['logado'] = true;

        

        $this->defineMensagem('success', 'Bem vindo ao painel!');

        $this->router->redirect("/dashboard");

    }

    

    public function painel()

    {

        echo $this->view->render('painel', [

            'brand' => $this->repositoryBrand->findOneBy(['id' => 1]),

            'setting' => $this->repositoryConfig->findOneBy(['id' => 1])

            ]);

        }

        public function forgot() { 

            echo $this->view->render('forgot-admin', [
    
                'brand' => $this->repositoryBrand->findOneBy(['id' => 1]),
    
                'setting' => $this->repositoryConfig->findOneBy(['id' => 1])
    
            ]);
        }
    
        
        public function recovery() { 
            if(isset($_SESSION['token']) and $_SESSION['token']):
                $token = true;
            else:
                $token = false;
            endif;
    
            echo $this->view->render('forgot-admin-recovery', [
    
                'token' => $token,
    
                'brand' => $this->repositoryBrand->findOneBy(['id' => 1]),
    
                'setting' => $this->repositoryConfig->findOneBy(['id' => 1])
    
            ]);
        }
        
        public function changePassword($data) {
            $entity = $this->entityManager;
            $password = $data['senha1'];
            $password = password_hash($password, PASSWORD_DEFAULT);
    
            $user =$this->repository->findOneBy(['id' => 1]);
            try
            { 
            $user->setPassword($password);
            $entity->persist($user);
            $entity->flush();  
    
            unset($_SESSION['recovery']);
            unset($_SESSION['token']);
            echo $this->router->redirect("/admin");
            }
            catch(Exception $e)
            {
                echo "Essa conta não existe. Erro: $e";
            }
    
        }
    
        
        public function recoveryPersist($data){
            $token = $data['token'];
            $user =$this->repository->findOneBy(['id' => 1]);
    
            if($user->getPassword() == $token):
                $_SESSION['token'] = true;
                echo $this->router->redirect("/admin/recovery");
                return;
            endif;
        }
    
        public function forgotPersist($data) {
    
            $email = $data['email'];
            $query =$this->repositoryConfig->findOneBy(['email' => $email]);
            if(!is_null($query)):
                $this->defineMensagem('success', "Foi enviado o email de recuperação de conta para <strong>$email</strong>");
    
                $mailer = new Mailer;
                $user =$this->repository->findOneBy(['id' => 1]);
                $mailer->setSubject('KimPages - TOKEN DE RECUPERAÇÃO DE CONTA');
                $mailer->setMessage(
                    'SEU TOKEN DE RECUPERAÇÃO DE SENHA É:<br><hr>'.$user->getPassword().
                    '<hr><br> Use o Token no seguinte Link:'.URL_BASE.'/admin/recovery'
            );
                $mailer->send($email, '');
    
                Guard::hasRecovery();
    
                echo $this->router->redirect("/admin/recovery");
                return;
            endif;
    
            $this->defineMensagem('danger', "Não existe essa conta.");
            echo $this->router->redirect("/admin/forgot");
            return;
    
        }
    


        public function logout()

        {

            unset($_SESSION['logado']);

            $this->defineMensagem('success', 'Sessão encerrada!');

            $this->router->redirect("/admin");

        }

        

    }

    