<?php if(!defined('BASEPATH')) exit('Akses langsung tidak di perkenankan');

class Login extends CI_Controller {

    public $trans_data  = array();

    public function __construct() {
    	parent::__construct();	
        $this->load->model('m_login');
        $this->load->model('file/m_new_company');
        $this->load->model('list/m_employee');
		$this->load->helper('custom_string_helper');
	}

    function index() {
        if ($this->session->userdata("login") == TRUE) {
            redirect('', 'refresh');
        }
        else {
            $data['branch']     = $this->m_login->get_branch();
			$data['DateServer'] = date("Y-m-d");

            $this->load->view("v_header");
            $this->load->view("v_login",$data);
            $this->load->view("v_footer");
        }
    }

    function get_user_description($username,$password,$branch){

        $cek_session    = $this->m_login->check_admin($username, $password);
        $AdminAuthority = $cek_session[0]->AdminAuthority;

        // customize stored in session
        //$group_id = $this->m_login->get_group_id($username);
        //$arr_menu_id = $this->m_login->get_menu_id($group_id);
        //$arr_menu_id = array_unique($arr_menu_id);

        // get detail employee

        $detail_employee = $this->m_login->get_detail_employee($username);

        foreach($detail_employee as $row) {
            $user_id            = $row->UserID;
            $group_id           = $row->GroupID;
            $employee_code      = $row->EmployeeCode;
            $jobtitle_code      = $row->JobTitleCode;
            $jobtitle_status    = $row->JobTitleStatus;
            $department_code    = $row->DepartmentCode;

            if(($AdminAuthority == 9) && ($branch != '')){
                $cek_branch         = $this->m_login->get_branch_by($branch);

                $company_name       = $cek_branch->CompanyName;
                $company_code       = $cek_branch->CompanyCode;
                $branch_code        = $cek_branch->BranchCode;
                $branch_status      = $cek_branch->BranchStatus;
            }
            else{
                $company_code       = $row->CompanyCode;
                $company_name       = $row->CompanyName;
                $branch_code        = $row->BranchCode;
                $branch_status      = $row->BranchStatus;
            }
        }
        //$sessionKey = $this->session->userdata('keydata');
        if(count($this->session->userdata('keydata'))>0){
            $dataSesKey = $this->session->userdata('keydata');           
        }else{
            for($exm=0;$exm<=255;$exm++){
                $data_value[$exm]=false;
            }   
            $dataSesKey = json_encode($data_value);
        }
        $data = array(
            //'menu' => $arr_menu_id,
            'user_id'           => $user_id,
            'username'          => $employee_code,
            'group_menu'        => $group_id,
            'company'           => $company_code,
            'company_name'      => $company_name,
            'department'        => $department_code,
            'branch'            => $branch_code,
            'branch_status'     => $branch_status,
            'jobtitle'          => $jobtitle_code,
            'jobtitle_status'   => $jobtitle_status,
            'keydata'           => $dataSesKey,
            'login'             => TRUE
        );

        return $data;
    }

    function transfer_coa($company_code,$year_now,$year_coa){

        /*======================= AccountBSStatus 0 = profit n Loss, 1 = Balance Sheet =====================*/
        /*======================= get coa by company =======================================================*/
        $coa_data = $this->m_login->get_coa_bycompany($company_code,$year_coa);

        $this->trans_data['total_coa'] = 0;

        foreach ($coa_data as $row){

            $array_coa = array(
                'CompanyCode'       => $row->CompanyCode,
                'BranchCode'        => $row->BranchCode,
                'AccountNumber'     => $row->AccountNumber,
                'GLSaldoYears'      => $year_now, //$row->GLSaldoYears
                'GLSaldoOpening'    => $row->AccountBSStatus === 0 ? 0 : $row->GLSaldoOpening,
                'GLSaldoBSheet'     => $row->AccountBSStatus === 0 ? 0 : $row->GLSaldoBSheet,
                'GLSaldoBalance1'   => 0,
                'GLSaldoBalance2'   => 0,
                'GLSaldoBalance3'   => 0,
                'GLSaldoBalance4'   => 0,
                'GLSaldoBalance5'   => 0,
                'GLSaldoBalance6'   => 0,
                'GLSaldoBalance7'   => 0,
                'GLSaldoBalance8'   => 0,
                'GLSaldoBalance9'   => 0,
                'GLSaldoBalance10'  => 0,
                'GLSaldoBalance11'  => 0,
                'GLSaldoBalance12'  => 0,
                'PLStatus'          => $row->PLStatus,
                'TransStatus'       => $row->TransStatus,
                'LastUserOP'        => $row->LastUserOP,
                'LastUserPL'        => $row->LastUserPL);
            
            $this->trans_data['array_coa'][] = $array_coa; 
            $this->trans_data['total_coa'] += 1;
            
            //$this->m_login->transaction_transfer_coa($array_coa);
        }
    }

    function process_login() {
       $username       = $this->input->post('username');
       $password       = $this->input->post('password');
       $branch         = $this->input->post('cmb-branch');
	
       $user_checked   = $this->m_employee->check_resign_date($username);
	   $browser = get_user_browser();
	   
       if($user_checked == NULL){
			if(($browser == "chrome") || ($browser == "safari") || ($browser == "firefox")){
				if ($this->m_login->check_user($username, $password) == TRUE) {	
	
					/*===================== get usr description ====================*/
					$user_data = $this->get_user_description($username,$password,$branch);
	
					$year_now       = date('Y');
	
					/*========================= get GL Saldo Years Last =========================*/
					$check_year_coa = $this->m_login->check_year_transaction_in_coa($user_data['company']);
	
					if($year_now > $check_year_coa){
	
						/*====================== check_company lock / unlock ================================*/
						$check_company_ul = $this->m_login->check_company_lock_unlock($user_data['company']);
	
						if($check_company_ul == 0){
	
							if($username == '20000'){
	
								$this->trans_data['delete_session']['username'] = $username;
	
								$user_data['session_id'] = $this->session->userdata('session_id');
	
								/*========================= set data session to database ==================================*/
								$this->trans_data['data_session'] = $user_data;
	
								/*================= total coa 0 karena tahun sekarang = glsaldoyear =========================*/
								$this->trans_data['total_coa'] = 0;
	
								$result_return = $this->m_login->transfer_coa_transaction($this->trans_data);
	
								$this->trans_data = [];
	
								if($result_return){
	
									$this->session->set_userdata($user_data);
									redirect(' ', 'refresh');
								}else{
	
									$this->session->set_flashdata('message', 'Login Filed.');
									redirect('login', 'refresh');
								}
	
							}else{
								/*================= lock company ==========================*/
								$this->m_login->lock_unlock_company($user_data['company'],1);
	
								/*================ get and copy coa for new year by company ==========================*/
								$this->transfer_coa($user_data['company'],$year_now,$check_year_coa);
								//$this->trans_data['company'] = $user_data['company'];
	
								/*=============================== set untuk delete session id sebelumnya di db ===============================*/
								$this->trans_data['delete_session']['username'] = $username;
	
								/*=============================== get session id baru ===============================*/
								$user_data['session_id'] = $this->session->userdata('session_id');
	
								/*========================= set data session to database ==================================*/
								$this->trans_data['data_session'] = $user_data;
	
								/*=========================== insert session dan coa ke database ==========================*/
								$result_return = $this->m_login->transfer_coa_transaction($this->trans_data);
	
								$this->trans_data = [];
	
								if($result_return){
	
									/*================= unlock company ==========================*/
									$this->m_login->lock_unlock_company($user_data['company'],0);
	
									$this->session->set_userdata($user_data);
									
									redirect(' ', 'refresh');
	
								}else{
	
									/*================= unlock company ==========================*/
									$this->m_login->lock_unlock_company($user_data['company'],0);
	
									$this->session->set_flashdata('message', 'Transfer Coa failed.');
									redirect('login', 'refresh');
								}
							}
	
						}else{
	
							$this->session->set_flashdata('message', 'Company is lock. wait in minutes.');
							redirect('login', 'refresh');
	
						}
	
					}else{
	
						$this->trans_data['delete_session']['username'] = $username;
	
						$user_data['session_id'] = $this->session->userdata('session_id');
	
						/*========================= set data session to database ==================================*/
						$this->trans_data['data_session'] = $user_data;
	
						/*================= total coa 0 karena tahun sekarang = glsaldoyear =========================*/
						$this->trans_data['total_coa'] = 0;
	
						/*========================= hanya insert session ke database ============================*/
						$result_return = $this->m_login->transfer_coa_transaction($this->trans_data);
	
						$this->trans_data = [];
	
						if($result_return){
	
							$this->session->set_userdata($user_data);
							redirect(' ', 'refresh');
						}else{
	
							$this->session->set_flashdata('message', 'Login Filed.');
							redirect('login', 'refresh');
						}
	
					}
	
				}
				else {
					$this->session->set_flashdata('message', 'Username or password invalid.');
					redirect('login', 'refresh');
				}
			}
			else{
				$this->session->set_flashdata('message', 'This browser does not use Chrome, please access program with Chrome');
            	redirect('login', 'refresh');
			}
        }
        else{
            $this->session->set_flashdata('message', 'Username was already in-active as employee');
            redirect('login', 'refresh');            
        }
    }	
    
    function process_logout(){
        $username       = $this->session->userdata('username');
        $session_id     = $this->session->userdata('session_id');
        $this->m_login->delete_session($username,$session_id);
        $this->session->sess_destroy();
        redirect('login', 'refresh');
    }

    function delete_cooki(){
        if (ini_get("session.use_cookies")) {
            $params = session_get_cookie_params();
            setcookie(session_name(), '', time() - 42000,
                $params["path"], $params["domain"],
                $params["secure"], $params["httponly"]
            );
        }
    }
	
    function check_full_admin(){
        if($this->m_login->check_full_admin()){
            echo true;
        }
        else{
            echo false;
        }
    }
}