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

class Users extends Admin_Controller {
	
	function __construct() {
            
		parent::__construct(TRUE);
		$this->load->model('users_model','',TRUE);
		$this->load->model('form_model','',TRUE);
		$this->load->model('home/home_model','',TRUE);
		$this->load->helper('uri');
	}
	
	function index()
	{
            
		$this->load->view( 'users' );
	}
        
	function loadData($cmd='false'){
		$data = $this->users_model->getAllData($cmd); 
		$responce = new stdClass();
		$responce->page = $data['page'];
		$responce->total = $data['total_pages'];
		$responce->records = $data['count'];
		$i=0;
		foreach($data['result'] as $row) {
			
			$responce->rows[$i] = $row;
			$i++;
		}
		//echo json_encode($responce);
		$this->output->set_output(json_encode($responce));
	}
	function deleteData(){		
		//echo $this->users_model->delete_users(); 
		$this->output->set_output($this->users_model->delete_users());
	}
	
	function index1()
	{
		
		$this->load->helper('flexigrid');
		/*
		 * 0 - display name
		 * 1 - width
		 * 2 - sortable
		 * 3 - align
		 * 4 - searchable (2 -> yes and default, 1 -> yes, 0 -> no.)
		 */
		$colModel['user_id'] = array('ID',40,TRUE,'center',2);
		$colModel['first_name'] = array('First Name',100,TRUE,'center',1);
		$colModel['last_name'] = array('Last Name',100,TRUE,'center',1);
		$colModel['username'] = array('Username',100,TRUE,'center',1);
		$colModel['birth_date'] = array('Birth date',100,TRUE,'center',1);
		$colModel['address'] = array('Address',100,TRUE,'center',1);
		$colModel['city'] = array('City',100,TRUE,'center',1);
		$colModel['state'] = array('State',100,TRUE,'center',1);
		$colModel['country'] = array('Country',100,TRUE,'center',1);
		$colModel['zip'] = array('Zip',100,TRUE,'center',1);
		$colModel['phone_number'] = array('Phone',100,TRUE,'center',1);
		$colModel['fax_number'] = array('Fax',100,TRUE,'center',1);
		$colModel['mobile_number'] = array('Mobile',100,TRUE,'center',1);
		$colModel['email_address'] = array('Email',100,TRUE,'center',1);
		$colModel['web_address'] = array('Website',100,TRUE,'center',1);
		$colModel['company_name'] = array('Company',100,TRUE,'center',1);
		$colModel['from_date'] = array('Valid From',100,TRUE,'center',1);
		$colModel['to_date'] = array('Valid To',100,TRUE,'center',1);
		/*
		 * Aditional Parameters
		 */
		$gridParams = array(
		'width' => 'auto',
		'height' => 'auto',
		'rows' => 10,
		'rpOptions' => '[10,15,20,25,40]',
		'pagestat' => 'Displaying: {from} to {to} of {total} items.',
		'blockOpacity' => 0.5,
		'title' => 'User List',
		'showTableToggleBtn' => false
		);
		
		$buttons[] = array('Add','add','actionUsers');
		$buttons[] = array('Edit','edit','actionUsers');
		$buttons[] = array('Delete','delete','actionUsers');
		$buttons[] = array('separator');
		$buttons[] = array('Select All','add','actionUsers');
		$buttons[] = array('DeSelect All','delete','actionUsers');
		$buttons[] = array('separator');
		
		$grid_js = build_grid_js('users_list',site_url("/users/ajax/allusers"),$colModel,'user_id','asc',$gridParams,$buttons);
		
		$data['headerjs'] = '';
		$data['js_grid'] = $grid_js;
//		print_r($data);
		$this->load->view('users',$data);
	}

	function AddCopyUsers() {
		$data = $this->users_model->AddCopyUsers();
	}
	
	function form() { 
             if (!$this->form_model->validate()) {
			$this->load->helper('form');

			if (!$_POST AND uri_assoc('id')) {
				$this->form_model->prep_validation(uri_assoc('id'));
			}
						
			$cntry=$this->users_model->getCurrent(uri_assoc('id'));
			if (!$_POST AND uri_assoc('id')){ 
				$cid=$cntry[0]['country'];
			}else{
				$cid=$this->session->userdata('country');
				$rows=$this->users_model->getState($cid);
				foreach ($rows as $row) {
					$stopt .= '<option value="'.$row['id'].'"';
					$stopt .= '>'.$row['name'].'</option>';
				}
			}
			
			$rows=$this->users_model->getCountries();
			$opt="";
			foreach ($rows as $row) {
				$opt .= '<option value="'.$row['id'].'"';
				if($row['id']==$cid)
					$opt .= ' selected="selected"';
				$opt .= '>'.$row['name'].'</option>';
			}
			if($this->form_model->user_logo=="" || !isset($this->form_model->user_logo)){	
				$this->form_model->user_logo=$this->session->userdata('user_logo');
			}
			if(is_array($this->form_model->display_day)){
			$this->form_model->display_day=implode(",",$this->form_model->display_day);
			}
			$data=array();
			$data['weekdays']=explode(",",$this->form_model->display_day);
			$this->form_model->cntry = $opt;
			$this->form_model->stt = $stopt;
			$this->load->view('form',$data);
			
		}
		else {
			$user_id=$this->session->userdata('user_id');
			$formdata = $this->form_model->db_array();
			$username=$formdata['username'];
			//$formdata['address']=addslashes($formdata['address']);
			
			$formdata['email_alert'] = isset($formdata['email_alert'])?$formdata['email_alert']:0;
			$formdata['sms_alert'] = isset($formdata['sms_alert'])?$formdata['sms_alert']:0;
			$formdata['change_password'] = isset($formdata['change_password'])?$formdata['change_password']:0;
			$formdata['history'] = isset($formdata['history'])?$formdata['history']:0;
			$formdata['allow_user_profile'] = isset($formdata['allow_user_profile'])?$formdata['allow_user_profile']:0;
			$formdata['report_view'] = isset($formdata['report_view'])?$formdata['report_view']:0;
			$formdata['menu_view'] = isset($formdata['menu_view'])?$formdata['menu_view']:0;
			$formdata['sms_enable'] = isset($formdata['sms_enable'])?$formdata['sms_enable']:0;
                        $formdata['reset_count'] = isset($formdata['reset_count'])?1:0;
			$formdata['expiry_service_sms'] = isset($formdata['expiry_service_sms'])?$formdata['expiry_service_sms']:0;
			$formdata['expiry_service_email'] = isset($formdata['expiry_service_email'])?$formdata['expiry_service_email']:0;
			$formdata['show_owners'] = isset($formdata['show_owners'])?$formdata['show_owners']:0;
			$formdata['show_divisions'] = isset($formdata['show_divisions'])?$formdata['show_divisions']:0;
			$formdata['auto_refresh_setting'] = isset($formdata['auto_refresh_setting'])?$formdata['auto_refresh_setting']:0;
			$formdata['device_id_not_editable'] = isset($formdata['device_id_not_editable'])?$formdata['device_id_not_editable']:0;
			$formdata['birth_date'] = isset($formdata['birth_date'])?$formdata['birth_date']:0;
			$formdata['admin_id'] = $this->session->userdata('user_id');
			$formdata['timezone'] = $this->session->userdata('timezone');
			$formdata['language'] = $this->session->userdata('language');
			
			$formdata['add_date'] = gmdate('Y-m-d H:i:s');
			if($formdata['user_logo'] =="")
			{
				$formdata['user_logo']="nKonnect";
			}
			if(isset($formdata['display_day'])){
				$arr=implode(",",$formdata['display_day']);
				unset($formdata['display_day']);
				$formdata['display_day']=$arr;
			}else{
				$formdata['display_day']='none';
			}
			$formdata['from_date'] = date('Y-m-d', strtotime($formdata['from_date']));
			$formdata['to_date'] = date('Y-m-d', strtotime($formdata['to_date']));
			$formdata['status'] = isset($formdata['status'])?$formdata['status']:0;
			if(uri_assoc('id')){
				if(!empty($formdata['password'])){
				   unset($formdata['confirm_password']);
				   $formdata['password'] = md5($formdata['password']);
				}else{
				    unset($formdata['confirm_password']);
                                    
					unset($formdata['password']);
					 
				}
                                $this->users_model->updateCount($formdata['reset_count'], uri_assoc('id'));
				unset($formdata['reset_count']);
                                unset($formdata['add_date']);
				$this->form_model->save($formdata, uri_assoc('id'));
			}else{
				$formdata['timezone'] = $this->session->userdata('timezone');
				$formdata['network_timeout'] = $this->session->userdata('network_timeout');
				$formdata['def_dash_view'] = $this->session->userdata('def_dash_view');
				$row = $this->home_model->getAutoRefreshSettings();
				$formdata['auto_refresh_setting'] = $row->auto_refresh_setting;
				$show_zone_name = $this->home_model->getZoneNameSetting();
				$formdata['show_zone_name'] = $show_zone_name;
				$formdata['password'] = md5($formdata['password']);
				$this->users_model->save($formdata, uri_assoc('id'));
			}
		}
	}
	function export(){
		
		$this->load->plugin('to_excel'); 
		$this->form_model->export();
	}	
	function state_data(){
		$this->load->model('users_model','',TRUE);
		//echo $query=$this->users_model->state();
		$this->output->set_output($query=$this->users_model->state());
	}
	function city_data(){
		$this->load->model('users_model','',TRUE);
		//echo $query=$this->users_model->city();
		$this->output->set_output($query=$this->users_model->city());
	}
	function get_json_data()
	{
		$this->load->model('users_model','',TRUE);
		$rs=$this->users_model->get_json();
		//echo json_encode($rs);
		$this->output->set_output(json_encode($rs));
	}
	function check_duplicates()
	{
		$username=uri_assoc("name");
		$id=uri_assoc("id");
		if(!$this->users_model->checkUserDuplicate($username,$id))
		{
			//echo "This Username Already Taken, Please Choose Unique Username.";
			$this->output->set_output("This Username Already Taken, Please Choose Unique Username.");
		}
	}
	function getDashCombo()
	{
		$this->load->model('home/home_model','',TRUE);
		$combo_s="";
		$combo_s.="<option value=''>".$this->lang->line('all_assets')."</option>";
		$combo_s.="<option value='running'>".$this->lang->line('running')."</option>";
		$combo_s.="<option value='parked'>".$this->lang->line('parked')."</option>";
		$combo_s.="<option value='out_of_network'>".$this->lang->line('out_of_network')."</option>";
//		$combo_s.="<option value='device_fault'>".$this->lang->line('device_fault')."</option>";
		$rows = $this->home_model->get_group($this->session->userdata('user_id'));
			if(count($rows)) {
				foreach ($rows as $row) {
					$combo_s .= "<option value='g-".$row->id."'>".$row->group_name."</option>";
				}
			}
		
		$rows = $this->home_model->get_subuser($this->session->userdata('user_id'));
		if(count($rows)) {
			foreach ($rows as $row) {
				$combo_s .= "<option value='u-".$row->user_id."'>".$row->username." (".$row->first_name." ".$row->last_name.")</option>";
			}
		}
		//echo $combo_s;
		$this->output->set_output($combo_s);
	}
	
	function copyUsers()
	{
		$this->load->model('home/home_model','',TRUE);
		$rows = $this->home_model->get_subuser($this->session->userdata('user_id'));
		if(count($rows)) {
			foreach ($rows as $row) {
				$combo_s .= "<option value='".$row->user_id."'>".$row->username." (".$row->first_name." ".$row->last_name.")</option>";
			}
		}
		
		$data['users'] = $combo_s;
		$this->load->view( 'copy_users', $data );
	}
	
	function usersExceptMe()
	{
		$ex_user = uri_assoc('id');
		
		$this->load->model('home/home_model','',TRUE);
		$rows = $this->home_model->get_subuser($this->session->userdata('user_id'), $ex_user);
		if(count($rows)) {
			foreach ($rows as $row) {
				$combo_s .= "<option value='".$row->user_id."'>".$row->username." (".$row->first_name." ".$row->last_name.")</option>";
			}
		}
		
		$this->output->set_output($combo_s);
	}
}
?>