<?php

class Login_mdl extends Base_Model {

	function __construct() {

        parent::__construct();
		$this->table = 'user';
		$this->table2 = 'user_group';
		$this->table3 = 'user_hak_akses';
    }
	
	function do_login($form_data = NULL)
	{
		// A few safety checks
		// Our array has to be set

		if(!isset($form_data))
			return FALSE;
	
		//Our array has to have 2 values
		//No more, no less!
		if(count($form_data) != 2)
		return FALSE;
	
		$nama_user = $form_data['nama_user'];
		$fpass = $form_data['pass'];
		
		// $this->db->from($this->table);
		// $this->db->where('nama_user', $nama_user);
		// $query = $this->db->get();
		$q="SELECT * 
			FROM user a, user_group b, user_hak_akses c, tb_menu d
			WHERE a.grup = b.code_group_user
			AND a.grup = c.grup
			AND d.id = c.code_menu
			AND a.nama_user = '$nama_user'
			ORDER BY d.id";
		$rs=$this->db->query($q)->result();
		
		// die($this->db->last_query());
		// dd($query->result());
		$m=1;
		foreach ($rs as $row){
			$username = $row->nama_user;			
			$pass = $this->encrypt->decode($row->pass);
			$kd_cmpy = $row->kd_cmpy;
			$grup = $row->grup;
			$l = $row->lihat;
			$t = $row->tambah;
			$u = $row->ubah;
			$h = $row->hapus;
			$menu = 'menu'.$m;
			$newdata = array(
				$menu  		=> $row->code_menu,
				'l'.$m 		=> $row->lihat,
				't'.$m 		=> $row->tambah,
				'u'.$m 		=> $row->ubah,
				'h'.$m 		=> $row->hapus
			);
			$this->session->set_userdata($newdata);	 
			$m++;
		}
		// die($fpass.' = '.$pass);

		if ($fpass == $pass){
			$q="SELECT * FROM mst_perusahaan a
				WHERE KdPrshn='$kd_cmpy' LIMIT 1";
			$rs=$this->db->query($q)->result();
			
			$newdata = array(
				'nm_cmpy'  		=> "PT CORINTHIAN INDUSTRIES INDONESIA",
				'kd_cmpy'  		=> $rs[0]->KdPrshn,
				'nm_subkon'  	=> $rs[0]->NmPrshn,
				'username'  	=> $username,
				'grup'  	=> $grup,
				'logged_in' 	=> TRUE,
				'l' 	=> $l,				
				't' 	=> $t,				
				'u' 	=> $u,				
				'h' 	=> $h
				);
			// Our user exists, set session.
			$this->session->set_userdata($newdata);	 
			
			$ketlog="$username login.";
			$this->addLog('',$ketlog); 
		
			return TRUE;
		} else {
			// No existing user.
			return FALSE;
		}
	}
	
}