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

class Users extends CI_Controller {
	public function __construct() {
		parent::__construct();
		
		$php = phpversion();
		$version = explode(".",$php);
		if ($version[0] >= 5 && $version[1] >= 5 && $version[2] >= 0) {
			if (session_status() == PHP_SESSION_NONE) session_start();
		} else {
			if(session_id() == '') session_start();
		}
		unset($php, $version);
		
		$this->load->library('layouts');
    $this->load->model('general_model');
	}
	
	public function index() {
		$this->lang->load('general', $this->session->userdata('language'));
		$this->lang->load('company', $this->session->userdata('language'));
		
    $this->load->model('users/usersmain');
	
		$this->usersmain->repairAllUsers();
		
		$data['admin'] = (element('role',$this->session->userdata('logged_in')) == "ADMIN") ? TRUE : FALSE;
		$data['users'] = $this->usersmain->listAllUsers();
		
		$this->layouts->view('users/index',array(),$data);
		
	}
	
	public function profile() {
		$id = ($this->session->userdata('logged_in')) ? element('userid',$this->session->userdata('logged_in')) : 0;
		if(!$id) redirect(base_url());
		
		$this->lang->load('general', $this->session->userdata('language'));
		$this->lang->load('company', $this->session->userdata('language'));
		
    $this->load->model('users/usersmain');
		
		$data['user'] = $this->usersmain->getUser($id);
		$data['admin'] = (element('role',$this->session->userdata('logged_in')) == "ADMIN") ? TRUE : FALSE;
	
		$data['flashdata'] = (isset($_SESSION['FLASHDATA']) && $_SESSION['FLASHDATA']) ? $_SESSION['FLASHDATA'] : NULL;
		unset($_SESSION['FLASHDATA']);
		
		$this->layouts->view('users/profile',array(),$data);
		
	}
	
	public function saveuser() {		
		$data = (!empty($_POST)) ? $_POST : NULL;
		$file = (!empty($_FILES)) ? $_FILES : NULL;
	
		$admin = ($this->session->userdata('logged_in') && element('role',$this->session->userdata('logged_in')) == "ADMIN") ? TRUE : FALSE;
		$from = ($admin) ? 'users' : NULL;
		if($data) {			
			$id = ($data['ID']) ? $data['ID'] : NULL;
			$from = (isset($data['from']) && $data['from']) ? strtolower($data['from']) : (($admin) ? 'users' : NULL);
			
			if($id) {
				unset($data['ID'], $data['from']);
				
				$upd['username'] = $data['username'];
				$upd['email'] = $data['email'];
				$upd['userid'] = $data['email'];
				$upd['language'] = "en";
				if(isset($data['role'])) $upd['role'] = (($data['role']) ? strtoupper($data['role']) : "USER");
				if($data['password']) $upd['password'] = md5($data['password']);
				
				$result = ($this->general_model->update('tbl_usermaster',$upd,array('fldid'=>$id))) ? $id : 0;				
			} else {
				unset($data['ID'], $data['from']);
				
				$ins['username'] = $data['username'];
				$ins['email'] = $data['email'];
				$ins['userid'] = $data['email'];
				$ins['language'] = "en";
				if(isset($data['role'])) $ins['role'] = (($data['role']) ? strtoupper($data['role']) : "USER");
				if($data['password']) $ins['password'] = md5($data['password']);
				
				$result = ($r = $this->general_model->insert('tbl_usermaster',$ins)) ? $r : 0;
			}
	
			if($result) {
				if(!empty($file)) {
					$img = NULL;
					$rs = $this->general_model->get_byFilter('tbl_usermaster',array('imageFile'),array('fldid'=>$result),null);
					if(isset($data['imageFileDelete']) && $data['imageFileDelete'] == 'YES') {
						$img['imageFile'] = NULL;
						if($rs && $rs[0]->imageFile) {
							$path = STR_REPLACE("\\","/",FCPATH).'dist/img/profile/'.$rs[0]->imageFile;
							unlink($path);
						}
					} else {
						if(isset($file['imageFile']['name']) && $file['imageFile']['name']) {
							if($rs && $rs[0]->imageFile) {
								$path = STR_REPLACE("\\","/",FCPATH).'dist/img/profile/'.$rs[0]->imageFile;
								unlink($path);
							}
							
							$blob = $this->uploadimg($result, 'imageFile', TRUE, FALSE);
							$img['imageFile'] = ($blob) ? $blob : (($rs) ? $rs[0]->imageFile : NULL);
						} else {
							$img['imageFile'] = (($rs) ? $rs[0]->imageFile : NULL);
						}
					}
					unset($data['imageFileDelete']);
					
					$sess = $this->session->userdata('logged_in');
					if($sess) {
						$sess['userProfilePic'] = $img['imageFile'];
						$this->session->set_userdata('logged_in', $sess);
					}
					
					$this->general_model->update('tbl_usermaster',$img,array('fldid'=>$result));
				}		
				$_SESSION['FLASHDATA'][0] = "Berjaya menyimpan butiran profil.";			
			}	else {
				$_SESSION['FLASHDATA'][0] = "Gagal menyimpan butiran profil.";
			}
		}
		
		redirect(base_url().$from);
	}

	/**
	* @title : PRINTLIST
	* @description : PRINT LIST OF USERS
	* @author : ZUL ZOLKAFFLY
	*	@create : 05/09/2016 (ZUL ZOLKAFFLY)
	*/
	public function printlist($type = ''){
    $this->load->model('users/usersmain');
		
		switch(strtoupper($type)) {
			case 'PENGGUNA' : $type = "USER"; break;
			case 'ADMIN' : $type = "ADMIN"; break;
			default : $type = NULL; break;
		}
		$data['users'] = $this->usersmain->listAllUsers($type);
		
		$this->load->view('template/reports/header.php', NULL);
		$this->load->view('users/reports/printlist.php', $data);
		$this->load->view('template/reports/footer.php');
	}
	
	public function delete($id = NULL) {
		$this->load->model('users/usersmain');
		$this->usersmain->inactivateUser($id);

		redirect(base_url().'users','refresh');
	}
	
	public function getuserajax() {
		$this->load->model('users/usersmain');
		
		$user = ($_POST['id']) ? $this->usersmain->getUser($_POST['id']) : NULL;
		
		echo json_encode($user);
	}
	

	/**
	* @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;
	}
	
	/**
	* @title : GETUPLOADBLOB
	* @description : CONVERT IMAGE TO BASE64
	* @author : ZUL ZOLKAFFLY
	*	@create : 03/08/2016 (ZUL ZOLKAFFLY)
	*	@update : 04/08/2016 (ZUL ZOLKAFFLY)
	*/
	private	function uploadimg($ID, $key = "imageFile", $resize = FALSE, $getblob = FALSE){
		$config = array(
			'allowed_types' => 'jpg|jpeg|bmp|png|gif',
			'upload_path' => FCPATH.'dist/img/profile/',
			'file_name' => $ID .'-'.time().'-'.(substr($_FILES[$key]['name'],-20)),
			'max_size' => '6048',
			'overwrite' => TRUE
		);
		
		$blob = NULL;
		if (is_uploaded_file($_FILES[$key]['tmp_name'])) {
			$this->load->library('upload', $config);
			
			if ($this->upload->do_upload($key)) {
				$image_data = $this->upload->data();
				
				// GET WIDTH & HEIGHT TO RESIZE & CROP
				$oriWidth = $image_data['image_width'];		// ORIGINAL WIDTH
				$oriHeight = $image_data['image_height'];	// ORIGINAL HEIGHT				
				$resWidth = floor(($oriWidth > 500) ? 500 : $oriWidth); // WIDTH TO RESIZE
				$resHeight = floor(($resWidth/$oriWidth)*$oriHeight); // HEIGHT TO RESIZE
					if ($resHeight > 500) {
						$resWidth = floor((500/$resHeight)*$resWidth);
						$resHeight = 500;
					}
				$cropWidth = $resWidth; // WIDTH TO CROP
				$cropHeight = ($resHeight>360) ? floor((360/500)*$resHeight) : $resHeight; // HEIGHT TO CROP
				$cropX = 0; // X AXIS START POINT FOR CROP
				$cropY = ($cropHeight>360) ? floor((360-$cropHeight)/2) : 0; // Y AXIS START POINT FOR CROP
				
				if($resize) {
					// MANIPULATION CONFIGURATION FOR RESIZING
					$manipulate['image_library'] = 'gd2';
					$manipulate['source_image'] = $image_data['full_path'];
					$manipulate['maintain_ratio'] = TRUE;
					$manipulate['width']     = $resWidth;
					$manipulate['height']   = $resHeight;
					
					$this->load->library('image_lib', $manipulate); 	
					if(!$this->image_lib->resize()) $this->session->set_flashdata('upload_message', $this->image_lib->display_errors());		
				}					
				
				if($getblob) {
					// CONVERT TO BLOB AND GET BASE64 DATA
					$blob = base64_encode(file_get_contents($image_data['full_path']));
					unlink($image_data['full_path']);	
				} else {
					$blob = $image_data['file_name'];
				}					
			} else {
				echo $this->upload->display_errors();
				$blob = NULL;
			}
		}
		return $blob;
	}
}
?>
