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

/**
* MODEL FOR Users
* @author : Zul Zolkaffly
* @last-update : Zul Zolkaffly (15/08/2016)
*/
class Usersmain extends CI_Model {
	
	public function listAllUsers($type = NULL) {
		$sql = "SELECT fldid ID, userid, username, IFNULL(role,'USER') role
						FROM tbl_usermaster
						WHERE (is_delete IS NULL OR is_delete = 0)
						".(($type) ? " AND role = '".(strtoupper($type))."' " : NULL)."
						AND ROUND ( (LENGTH(userid) - LENGTH( REPLACE ( userid, '@', '') )) / LENGTH('@')) > 0
						ORDER BY position ASC, userid ASC";
		$q = $this->db->query($sql);
		
		return ($q && ($r = $q->result())) ? $this->ObjToArray($r) : NULL;
	}
	
	public function getUser($id) {
		$sql = "SELECT fldid ID, userid email, username, IFNULL(role,'USER') role, imageFile
						FROM tbl_usermaster
						WHERE (is_delete IS NULL OR is_delete = 0)
						AND ROUND ( (LENGTH(userid) - LENGTH( REPLACE ( userid, '@', '') )) / LENGTH('@')) > 0
						AND fldid = ".$id;
		$q = $this->db->query($sql);
		
		return ($q && ($r = $q->result()) && $r[0]) ? $this->ObjToArray($r[0]) : NULL;
	}
	
	public function repairAllUsers() {
		$sql = "UPDATE tbl_usermaster
						SET is_delete = 1
						WHERE ROUND ( (LENGTH(userid) - LENGTH( REPLACE ( userid, '@', '') )) / LENGTH('@')) = 0";
		$this->db->query($sql);
		$sql = "UPDATE tbl_usermaster
						SET role = 'USER'
						WHERE role IS NULL";
		$this->db->query($sql);
		$sql = "UPDATE tbl_usermaster
						SET language = 'en'
						WHERE (language IS NULL OR language NOT IN ('en','ms'))";
		$this->db->query($sql);
	}
	
	public function inactivateUser($id) {
		$sql = "UPDATE tbl_usermaster SET is_delete = 1 WHERE fldid = ".$id;
		$this->db->query($sql);
	}
	
	/**
	* @title : OBJTOARRAY
	* @description : CONVERT FROM STDCLASS OBJECT TO ARRAY
	* @author : ZUL ZOLKAFFLY
	*	@create : 15/08/2016 (ZUL ZOLKAFFLY)
	*/
	private function ObjToArray($obj,$single=false) {
		return (!empty($obj)) ? json_decode(json_encode(($single)?$obj[0]:$obj),true) : NULL;
	}

}
