<?php
namespace controllers;

use \services\authorization\SendResetLinkEmail;
use \services\authorization\ResetPassword;
    
/**
 * Password reset controller
 * @author Jérôme Brilland
 * @version 2.1
 * @copyright (c) 2019-2022, Jérôme Brilland
 * @license http://www.gnu.org/licenses/gpl.txt GNU General Public License
 */
class PasswordResetController extends \ActionController {

    public function doShowLinkRequestForm() {
        $i18n = \IoC::resolve( 'i18n' );
        $this->title = $i18n->__( 'forgot_password' );
        $this->render( 'forgotten_password.html' );
    }

    public function doSendResetLinkEmail() {
        $sendResetLinkEmail = new SendResetLinkEmail( $this->request->getParameters()->getString( 'email', null, 'email' ) );
        $sendResetLinkEmail->perform( $this );
    }

    public function sendResetLinkEmailFailed( $error ) {
        $this->flash['error'] = $error;
        $this->forward( 'controllers\\PasswordResetController', 'showLinkRequestForm' );
    }

    public function sendResetLinkEmailSucceeded() {
        \IoC::resolve( 'eventmediator' )->trigger( 'after_send_reset_link_email', [$this] );
        $i18n = \IoC::resolve( 'i18n' );
        $this->flash['notice'] = $i18n->__( 'password_reset_instructions_sent' );
        $this->redirect( BASE_URL . 'login' );
    }

    public function doShowResetForm() {
        $i18n = \IoC::resolve( 'i18n' );
        if ( empty( $this->token ) ) {
            $this->token = $this->request->getAttribute( 'token' );
        }
        $this->title = $i18n->__( 'reset_password' );
        $this->render( 'reset_password.html' );
    }

    public function doResetPassword() {
        $this->token = $this->request->getParameters()->getAlnum( 'token' );
        $resetPassword = new ResetPassword( $this->request->getParameters()->getString( 'email', null, 'email' ), $this->token, $this->request->getParameters()->getString( 'password' ), $this->request->getParameters()->getString( 'password_confirmation' ) );
        $resetPassword->perform( $this );
    }

    public function validateTokenFailed() {
        $i18n = \IoC::resolve( 'i18n' );
        $this->flash['error'] = $i18n->__( 'invalid_or_expired_token' );
        $this->redirect( BASE_URL . 'login' );
    }

    public function resetPasswordFailed( $user ) {
        $this->errors = $user->getErrors();
        $this->doShowResetForm();
    }

    public function resetPasswordSucceeded() {
        \IoC::resolve( 'eventmediator' )->trigger( 'after_reset_password', [$this] );
        $i18n = \IoC::resolve( 'i18n' );
        $this->flash['success'] = $i18n->__( 'password_has_been_reset' );
        $this->redirect( BASE_URL . 'login' );
    }
}
