<?php

/*
 * PuzzleApp
 * Webemyos
 * Jérôme Oliva
 * GNU Licence
 */

namespace Apps\Base\Module\SingUp;

use Core\Controller\Controller;
use Core\Core\Request;
use Core\Security\Authentication;
use Core\View\ElementView;
use Core\View\View;
use Core\Control\Captcha\Captcha;
use Core\Entity\User\User;
use Core\Security\TokenManager;
use Core\Control\Link\Link;

use Apps\Base\Helper\EmailHelper;


class SingUpController extends Controller
{
    /**
   * Constructeur
   */
   function __construct($core="")
   {
       $this->Core = $core;
   }
   
   /*
    * Connection Module
    */
   function Index($error = "")
   {
        $view = new View(__DIR__."/View/index.tpl", $this->Core);
        $success = false;
        $error = "";
        
        if(Request::isPost())
        {
            if(!Captcha::IsValid())
            {
               $message = $this->Core->GetCode("Captcha.Incorrect");     
            }   
            else
            {
                $message = Authentication::CreateUser($this->Core,
                                               Request::GetPost("login"),
                                               Request::GetPost("password"), 
                                               Request::GetPost("verif") 
                                            );

                
                if( $message === true)
                {                            
                    //On connecte l'utilisateur et on le redirige dans l'espace membre                            
                    Authentication::Connect(Request::GetPost("login"), Request::GetPost("password"));

                    
                     EmailHelper::SendEmail($this->Core, 
                                    "Cms-Register", 
                                    $this->Core->User->Email->Value, 
                                    array("{{userName}}" => $this->Core->User->GetPseudo()
                                    ),
                                    $this->Core->GetCode("Base.LinkWelcomeTitle"),
                                    $this->Core->GetCode("Base.LinkWelcomeMessage"),
                                );
                    
                    $this->Core->Redirect("/Membre");
                }
            }
         if($message == "")
         {
             $success = true;
         }
         else
         {
             $error = $message;
         }
        }
        
        $Captcha = new Captcha();
       
        $view->AddElement(new ElementView("Captcha", $Captcha->Show()));
       
        $view->AddElement(new ElementView("Success", $success));
        $view->AddElement(new ElementView("error", $error));
      
        
        //Auth Plugin 
        $authPlugin = \Apps\EeApp\Helper\AppHelper::GetPluginType($this->Core, "Cms", "Auth");

        $view->AddElement(new ElementView("haveAuthPlugin",  $authPlugin ? true : false));
        $view->AddElement(new ElementView("authPluginScript",  $authPlugin ? $authPlugin->GetRegisterPlugin() : ""));
        $view->AddElement(new ElementView("authPlugin",  $authPlugin ? $authPlugin->Render($authPlugin->Parameters) : ""));
        
        
        return $view->Show();
   }

   /**
    * Forget pass
    */
   public function ForgetPassword()
   {
        $view = new View(__DIR__."/View/forgetPassword.tpl", $this->Core);
    
        if(Request::isPost())
        {
            $user = new User($this->Core);
            $user = $user->GetByEmail(Request::GetPost("email"));    

            if($user->IdEntite != "")
            {
                $token = TokenManager::Generate($this->Core, $user->IdEntite);    

                $link = new Link($this->Core->GetCode("Base.emailLink"), $this->Core->GetPath("/NewPassword/".$token));
           
                EmailHelper::SendEmail($this->Core, 
                                    "Cms-ForgetPassWord", 
                                    $user->Email->Value, 
                                    array("{{link}}"=> $link->Show(),
                                          "{{userName}}" => $user->GetPseudo()
                                    ),
                                    $this->Core->GetCode("Base.LinkResetPasswordSubject"),
                                    $this->Core->GetCode("Base.LinkResetPasswordMessage"),
                                );
 
                $view->AddElement(new ElementView("Message", $this->Core->GetCode("Base.emailForgetSended")));    
            }
            else
            {
                $view->AddElement(new ElementView("Message", $this->Core->GetCode("Base.emailForgetUNknowUser")));
            }
            
            $view->AddElement(new ElementView("Success", true));
        }
        else
        {
            $view->AddElement(new ElementView("Success", false));
        }

        return $view->Render();
   }  
   
   /**
    * Enter new Password
    */
   function NewPassword($params)
   {
       $view = new View(__DIR__."/View/newPassword.tpl", $this->Core);
       $isValid = TokenManager::IsValid($this->Core, $params);

       if($isValid)
       {
            if(Request::isPost())
            {
                   $pass = Request::GetPost("password");
                   $verify = Request::GetPost("verify");

                    if($pass != $verify)
                    {
                        $view->AddElement(new ElementView("Error", $this->Core->GetCode("Base.PassNotEqual")));    
                        $view->AddElement(new ElementView("State", "validToken"));
                    }
                    else
                    {
                        $isValid->User->Value->ChangePassword($pass);
                        
                        $view->AddElement(new ElementView("Error", "")); 
                        $view->AddElement(new ElementView("State", "updated"));   
                    }
            }
            else
            {
                $view->AddElement(new ElementView("State", "validToken"));
                $view->AddElement(new ElementView("Error", ""));    
            }
        }     
       else
       {
           $view->AddElement(new ElementView("State", "invalidToken"));
       }

       return $view->Render();
   }    
}
