<?php

namespace App\Controllers;

/**
 * This class controls login access for the system.
 *
 * @author Al Zziwa <azziwa@gmail.com>
 * @version 1.1.0
 * @copyright TMIS
 * @created 01/08/2015
 */
use App\Models\_validator;
use App\Models\_permission;

class Account extends BaseController
{
    #Constructor to set some default values at class load
    public function __construct()
    {
        // parent::__construct();
        $this->validator = new _validator();
        $this->permission = new _permission();
    }
    
    
    #The login page
    public function login()
    {
        $data = filter_forwarded_data($this);
        
        if (!empty($_POST)) {
            #Is form verified?
            if ($this->request->getPost('verified')) {
                #Is user verified?
                $results = $this->validator->is_valid_account(array('login_name'=>trim($this->request->getPost('loginusername')), 'login_password'=>trim($this->request->getPost('loginpassword')) ));
                if ($results['boolean']) {
                    #If so, assign permissions and redirect to their respective dashboard
                    $this->session->set('__permissions', $this->permission->get_user_permission_list($results['user_id']));
                    #Log sign-in event
                    $this->logger->add_event(array('log_code'=>'user_login', 'result'=>'success', 'details'=>"userid=".$results['user_id']."|username=".trim($this->request->getPost('loginusername')) ));
                    
                    # Go to the user dashboard
                    #redirect(base_url().get_user_dashboard($this, $results['user_id']));
                    // redirect(base_url().'profile/user_data');
                    return redirect()->to('profile/user_data'); 
                }
                # Invalid credentials
                else {
                    $this->logger->add_event(array('log_code'=>'user_login', 'result'=>'fail', 'details'=>"username=".trim($this->request->getPost('loginusername')) ));
                    $data['msg'] = "WARNING: Invalid login details.";
                }
            } else {
                $data['msg'] = "ERROR: Your submission could not be verified.";
            }
        }
        # If already logged in, log out of current session
        elseif ($this->session->get('__user_id')) {
            $this->logout($this->session->get('__user_id'));
            $data['msg'] = "You have been logged out.";
        }
        
        echo view('account/login', $data);
    }
        
        
    
    # Log out a user
    public function logout()
    {
        #Log sign-out event
        $userId = $this->session->get('__user_id')? $this->session->get('__user_id'): "";
        $email = $this->session->get('__email_address')? $this->session->get('__email_address'): "";
        $this->logger->add_event(array('log_code'=>'user_logout', 'result'=>'success', 'details'=>"userid=".$userId."|email=".$email ));
        
        # Set appropriate message - reason for log out.
        $data['msg'] = $this->session->get('msg')? get_session_msg($this): "You have been logged out.";
                    
        #Remove any set session variables
        $this->session->destroy();
        echo view('account/login', $data);
    }
    
    
    
    
    # Apply for an account
    #	function apply()
    #	{
    #		$data = filter_forwarded_data($this);
    #
    #		if(!empty($_POST))
    #		{
    #			$this->load->model('_person');
    #Pass these details to the person object to handle with XSS filter turned on
    #			$data['result'] = $this->person->add_profile($this->request->getPost(NULL, TRUE));
    #			$data['msg'] = $data['result']['boolean'] && empty($data['result']['msg'])? "Your account has been created but will need approval for you to login.": $data['result']['msg'];
    #			if($data['result']['boolean'])
    #			{
    #				$this->session->delete_all(array('person_id'=>'', 'firstname'=>'', 'lastname'=>'', 'role__roles'=>'', 'emailaddress'=>'', 'telephone'=>''));
    #				$this->session->set('msg', $data['msg']);
    #				redirect(base_url().'account/login');
    #			}
    #		}
    #
    #		echo view('application/new_application', $data);
    #	}
    
    
    
    
    # Forgot the password
    public function forgot()
    {
        $data = filter_forwarded_data($this);
        
        if (!empty($_POST)) {
            $result = $this->user->recover_password($this->request->getPost());
            $data['msg'] = $result['boolean']? 'A temporary password has been generated and <br>sent to your registered email and phone. <br><br>Use it to login and change it immediately on your <br>profile page for your security.': $result['msg'];
            
            $data['area'] = 'basic_msg';
            echo view('addons/basic_addons', $data);
        } else {
            echo view('account/recover_password', $data);
        }
    }
}

/* End of controller file */
