<?php
namespace App\Controllers\Backend;

use App\Controllers\BackendController;

class AuthenticationsController extends BackendController {

    public function actionSignIn() {
        
        if( true == isValArr( $this->g_arrmixBackendSessionDetails ) ) {
            return redirect()->route( 'dashboard' );
        } 

        $arrmixData = [];
        $arrmixData['strTitle'] = 'SignIn';
        $arrmixData['boolIsHideFooter'] = true;
        $arrmixData['boolIsHeaderFooter'] = true;
        $arrmixData['boolIsLogin'] = true;
        $arrmixData['view'] = 'authentications/sign-in';
        
        if( true == isValArr( $this->request->getPost() ) ) {
            
            $arrmixRequestData = $this->request->getPost();

            if( false == $this->validation->run( $arrmixRequestData , 'validateSignIn' ) ) { 
                
                $this->session->setFlashdata( 'error', 'Validation Errors.' );
                self::setFormValidationErrors( $this->validation->getErrors() );

                return $this->render( $arrmixData );
            }
            
            $arrmixUserDetails = \App\Models\UsersModel::createService()->findUserByUsername(  $arrmixRequestData['username'] );
            
            if( false == isValArr( $arrmixUserDetails ) ) {
                
                $this->session->setFlashdata( 'error', 'Invalid Username.' );
                return $this->render( $arrmixData );
            }  
            
            if( $arrmixRequestData['password'] != $this->decryptPassword( $arrmixUserDetails['password'] ) ) {
                
                $this->session->setFlashdata( 'error', 'Invalid Password' );
                return $this->render( $arrmixData );
            }

            $this->session->setFlashdata( 'success', 'Successfully Login' );
                
            $this->session->set( 'backend_session', $arrmixUserDetails );    
            
            return redirect()->route( 'dashboard' );
            
        }
        
        return $this->render( $arrmixData );
    }
    
    public function actionSignOut() {
        $this->session->destroy();
        
        return redirect( 'authentication/sign-in', 'refresh' ); 
    }

   
}
