<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Forgot extends CI_Controller {
	
    function __construct(){
        parent::__construct();
        // date_default_timezone_set('Asia/Jakarta');
				$this->load->database();
				$this->load->library('authorization');
				$this->load->library('session'); 
        $this->load->model('engine/activity_log_model');
        $this->load->model('master/operator_model');
    }
	
	public function index()
	{
		$data = array(
			'content'	=>	'forgot/main'
		);
		
		$this->load->view($data['content'],$data);
    }

    function submit(){
        $result['url'] = '';
		$result['error_msg'] = '';
		$result['url'] = 'main';
		$error = '';
		$email = $this->input->post('tEmail');
        // check email
        $where = array();     
        $where['email'] = $email;    
        $opr = $this->operator_model->get($where);
        if(!$opr['idOperator']){
            $error = 'Email tidak ditemukan';
        }else{
            // check, apakah ada task Forgot Password sebelumnya, kalau ada, set ke "canceled"
            $whereActLog = array();
            $whereActLog['fidOperator'] = $opr['idOperator'];
            $whereActLog['SchemaName'] = 'public';
            $whereActLog['TableName'] = 'msOperator';
            $whereActLog['LogType'] = 'forgot_password';
            $lastLog = $this->db->select('*')
                                ->where($whereActLog)
                                ->order_by('idActivityLog','desc')
                                ->limit(1)
                                ->get('public.activityLog')
                                ->row_array();
            if (isset($lastLog['idActivityLog'])){
                // ditemukan data Forgot, maka set kecancel
                $logData = json_decode($lastLog['LogData'],true);
                $logData['Status'] = 'cancel';
                //
                $logCancel = array();
                $logCancel['idActivityLog'] = $lastLog['idActivityLog'];
                $logCancel['LogData'] = json_encode($logData);
                // $this->activity_log_model->save($logCancel);
                $this->db->query('UPDATE "public"."activityLog" SET "LogData" = \''.$logCancel['LogData'].'\' WHERE "idActivityLog" = '.$lastLog['idActivityLog']);
            }   
            // create task forgot password
            $data = $whereActLog;
            // $data['idActivityLog'] = 0;
            $token = md5(uniqid(rand(), true));
            $logData = array();
            $logData['Status'] = 'open';
            $logData['Token'] = $token;
            $data['LogData'] = json_encode($logData);
            // $this->activity_log_model->save($data);
            $this->db->insert('public.activityLog', $data);
            // send link to email
            $this->_sendEmail($opr,$token);
            //
            $result['userLogin'] = $opr['userName'];
        }
        $result['error_msg'] = $error;
		echo json_encode($result);
    }
    function info($userLogin){
        $where = array();     
        $where['userName'] = $userLogin;
        $opr = $this->operator_model->get($where);
        $data = array(
			'content'	=>	'forgot/info',
			'opr'	=>	$opr
		);
		
		$this->load->view($data['content'],$data);
    }
    function token($token){
        $error = '';
        $log = $this->activity_log_model->getByToken($token);
        if (!$log['idActivityLog']){
            $error = 'Token tidak ditemukan';
        }else{
            $logData = json_decode($log['LogData'],true);
            $sessToken = $logData['Status'];
            if ($sessToken <>'open'){
                $error = 'Session token <strong>'.$sessToken.'</strong>';
            }
        }
        $where = array();     
        $where['idOperator'] = ($log['fidOperator']?:0);
        $opr = $this->operator_model->get($where);
        $data = array(
			'content'	=>	'forgot/reset',
			'opr'	=>	$opr,
			'token'	=>	$token,
			'error'	=>	$error,
		);
		
		$this->load->view($data['content'],$data);
    }

    function reset(){
        $result['url'] = '';
		$result['error_msg'] = '';
		$result['url'] = 'main';
		$error = '';
        $token = $this->input->post('tToken');
        $password = $this->input->post('tPassword');
        $reTypePassword = $this->input->post('tReTypePassword');
        // validasi Token, apakah masih open
        $log = $this->activity_log_model->getByToken($token);
        $logData = json_decode($log['LogData'],true);
        $sessToken = $logData['Status'];
        if ($sessToken <>'open'){
            $error = 'Session token '.$sessToken;
        }
        // validasi password, apakah sesuai
        if ($password <> $reTypePassword){
            $error = 'Password tidak sesuai';
        }
        // validasi password, tidak boleh kosong
        if (!$password){
            $error = 'Password tidak boleh kosong';
        }
        
        if (!$error){
            $this->db->trans_start();
            // update new password
            $opr = array();
            $opr['idOperator'] = $log['fidOperator'];
            $opr['passWord'] = md5($password);
            $this->operator_model->save($opr);
            // update log to 
            $logData = json_decode($log['LogData'],true);
            $logData['Status'] = 'done';
            $logData['Time'] = date("Y-m-d H:i:s");
            $logDataEncode = json_encode($logData);
            $this->db->query('UPDATE "public"."activityLog" SET "LogData" = \''.$logDataEncode.'\' WHERE "idActivityLog" = '.$log['idActivityLog']);
            // done
            $this->db->trans_complete();
            if ($this->db->trans_status() === false) {
                $this->db->trans_rollback();
                $error = 'Update data gagal';
            } else {
                $this->db->trans_commit();
            }
        }
        $result['error_msg'] = $error;
		echo json_encode($result);
    }
    private function _sendEmail($opr,$token){
        $mailSubject = 'Reset Password mineSeal';
        //
        $data = array();
        $data['token'] = $token;
        $data['opr'] = $opr;
        $mailBody = $this->load->view('forgot/confirmation_email',$data,true);
        ///
		$pwd	= '2020@eco';
		$from	= 'ecos@elcorps.com';

		// baca config dari file /config/myconfig.php
		$to 	= $opr['email'];
		// config
		$config = Array(  
		'protocol' => 'smtp',  
		'smtp_host' => 'ssl://smtp.elzatta.com',  
		'smtp_port' => 465,
		'smtp_user' => $from,   
		'smtp_pass' => $pwd,   
		'mailtype' => 'html',   
		'charset' => 'iso-8859-1'  
	    );  
	    $this->email->initialize($config); 
	    $this->email->set_newline("\r\n");  
	    $this->email->from($from, 'elcorps Core System');   
	    $this->email->to($to);   
        // $this->email->cc($cc);  
		//
		$this->email->subject($mailSubject);		
        $this->email->message($mailBody);
        
		
	    if (!$this->email->send()) {  
			// $this->error('Sending failed....!') ;
            // echo $this->email->print_debugger();  
            return false;
	    }else{  
            // $this->success('Sending successfull.... have a nice day!..') ;
            // echo 'sukses';
            return true;
	    } 
    }
}