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

class Permissions_model extends CI_Model {

	function __construct()
    {
     parent::__construct();		
	
    }
	
	//this function gets available(which can be granted) modules/menu in db
	//function was originally designed for menu_control but modified to cater for default_permissions
	//other functions for menu_control have been modified too to cater for default_permissions
	function get_all_available_modules($id,$type)
	{
		$corp_id = $this->login_model->corp_id();
		
		if($type == 'corporation')
		{
			//$query = "SELECT * FROM menu WHERE id NOT IN("SELECT id FROM corporation_id=$corporation_id")"
			$array = $this->get_granted_modules_id($id);
			$this->db->select('*');
			$this->db->from('menu');
			$this->db->where_not_in('id',$array);
			
			$query = $this->db->get();
		}
		else if($type == 'user')
		{
			/*$query = "SELECT * FROM corporation_modules WHERE corporation_id = $corp_id 
						AND menu NOT IN("SELECT menu FROM menu_control WHERE user_id=$user_id")"*/
			$array = $this->get_granted_modules_id_forUser($id);
			$this->db->select('*');
			$this->db->from('corporation_modules');
			$this->db->where('corporation_id',$corp_id);
			$this->db->where_not_in('menu',$array);
			
			$query = $this->db->get();
		}
		else if($type == 'corporations_default')
		{
			$sqlQuery = "SELECT * FROM menu WHERE id NOT IN (SELECT menu FROM corporations_default_permissions)";
			$query = $this->db->query($sqlQuery);
		}
		else if($type == 'corporation_staff')
		{
			$sqlQuery = "SELECT * FROM corporation_modules WHERE corporation_id = $corp_id 
						AND menu NOT IN
						(SELECT menu FROM default_permissions WHERE corporation_id = $corp_id AND user_type = 3)";
						//return $sqlQuery;
			$query = $this->db->query($sqlQuery);
			
		}		
		else if($type == 'corporation_member')
		{
			$sqlQuery = "SELECT * FROM corporation_modules WHERE corporation_id = $corp_id 
						AND menu NOT IN
						(SELECT menu FROM default_permissions WHERE corporation_id = $corp_id AND user_type = 4)";
						//return $sqlQuery;
			$query = $this->db->query($sqlQuery);
		}	
		//echo $this->db->last_query()."<br>";//for debugging
		if($query->num_rows()>0)
		{
			$modules = $query->result_array();
			$count = count($modules);
			$menu = '';
			for($i=0;$i<$count;$i++)
			{
				//$menu .= $modules[$i]['menu_name']."<br>";
				$menu .= "
						  <div class=\"col-md-4\">
								<div class=\"box box-primary\">
									<div class=\"box-header with-border\">";
									if($type == 'corporation')
									$menu .="<h3 class=\"box-title\">".$modules[$i]['menu_name']."</h3>
									</div><!-- /.box-header -->									
									<div class=\"box-body\">
									   <a href=\"#\" onclick=\"grantModuleAlert(".$modules[$i]['id'].","."'".$type."'".")\"><span class=\"blue\">Click to grant permission</span></a>
									</div>
								</div>
							</div>";
									else if($type == 'user')
									$menu .="<h3 class=\"box-title\">".$this->get_menu_name($modules[$i]['menu'])." - ".$modules[$i]['id']."</h3> 
									</div><!-- /.box-header -->									
									<div class=\"box-body\">
									   <a href=\"#\" onclick=\"grantModuleAlert(".$modules[$i]['menu'].","."'".$type."'".")\"><span class=\"blue\">Click to grant permission</span></a>
									</div>
								</div>
							</div>";
									else if($type == 'corporations_default')
									$menu .="<h3 class=\"box-title\">".$modules[$i]['menu_name']." - ".$modules[$i]['id']."</h3> 
									</div><!-- /.box-header -->									
									<div class=\"box-body\">
									   <a href=\"#\" onclick=\"grantModuleAlertDP(".$modules[$i]['id'].","."'".$type."'".")\"><span class=\"blue\">Click to grant permission</span></a>
									</div>
								</div>
							</div>";
									else 
									$menu .="<h3 class=\"box-title\">".$this->get_menu_name($modules[$i]['menu'])." - ".$modules[$i]['id']."</h3> 
									</div><!-- /.box-header -->									
									<div class=\"box-body\">
									   <a href=\"#\" onclick=\"grantModuleAlertDP(".$modules[$i]['menu'].","."'".$type."'".")\"><span class=\"blue\">Click to grant permission</span></a>
									</div>
								</div>
							</div>";					
				}
			return $menu;

		}
		else 
			 $return = "<p>There are no nodules to display</p>";
			 return $return;		
		
	}
	
	//this function gets all modules granted to a corporation/or user
	function get_permissions_granted_per_corporation_or_user($id,$type)
	{
		$corp_id = $this->login_model->corp_id();
		
		if($type == 'corporation')
		{
			$this->db->select('*');
			$this->db->from('corporation_modules');
			$this->db->where('corporation_id',$id);
			$query = $this->db->get();
		}
		else if($type == 'user')
		{
			$this->db->select('*');
			$this->db->from('menu_control');
			$this->db->where('user_id',$id);
			$query = $this->db->get();
		}
		else if($type == 'corporations_default')
		{
			$sqlQuery = "SELECT * FROM corporations_default_permissions";
			$query = $this->db->query($sqlQuery);
		}
		else if($type == 'corporation_staff')
		{
			$sqlQuery = "SELECT * FROM default_permissions WHERE corporation_id = $corp_id AND user_type = 3";
			$query = $this->db->query($sqlQuery);
		}
		else if($type == 'corporation_member')
		{
			$sqlQuery = "SELECT * FROM default_permissions WHERE corporation_id = $corp_id AND user_type = 4";
			$query = $this->db->query($sqlQuery);
		}
				
		if($query->num_rows()>0)
		{
			$modules = $query->result_array();
			$count = count($modules);
			$menu = '';
			for($i=0;$i<$count;$i++)
			{				
				$menu .= "
						  <div class=\"col-md-4 menu-wrapper\">
								<div class=\"box box-primary\">
									<div class=\"box-header with-border\">
										<h3 class=\"box-title\">".$this->get_module_name($modules[$i]['menu'])."</h3>
											<span id=\"select-all-span\">Select All</span>
											<a href=\"#\" id=\"check-all".$modules[$i]['id']."\" class=\"select-all\" onclick=\"selectAll(".$modules[$i]['id'].",".$modules[$i]['menu'].","."'".$type."'".") \"></a>
											<a href=\"#\" id=\"delete\" onclick = \"removeModuleAlert(".$modules[$i]['id'].","."'".$type."'".")\"></a>
									</div><!-- /.box-header -->
									<div class=\"box-body\" id=\"checkbox".$modules[$i]['menu']."\">";
									   
					$menu .= $this->return_marked_sub_menu($id,$modules[$i]['menu'],$type);
                                  
									
					$menu .= "	</div>
								</div>
							</div>";				
				}
			return $menu;

		}
		else
			 $return = "<p>There are no nodules to display</p>";
			 return $return;	
		
	}
	
	private function get_module_name($module_id)
	{
		$this->db->select('menu_name');
		$this->db->from('menu');
		$this->db->where('id',$module_id);
		
		$query = $this->db->get();
		if ($query->num_rows() == 1)
		{
			$row = $query->row_array(); 
			return $row['menu_name'];  
		}
		else return NULL;
		
	}
	
	//this function returns an array of id(s) for the modules/menu granted to a corporation
	private function get_granted_modules_id($corporation_id)
	{
		$this->db->select('menu');
		$this->db->from('corporation_modules');
		$this->db->where('corporation_id',$corporation_id);
		$query = $this->db->get();
		
		if($query->num_rows()>0)
		{
			$modules = $query->result_array();
			$count = count($modules);
			$menu = array();
			for($i=0;$i<$count;$i++)
			{
				array_push($menu,$modules[$i]['menu']);
								
			}			
			return $menu;

		}
		else return NULL;	
	}
	
	//this function returns an array of id(s) for the modules/menu granted to a USER
	private function get_granted_modules_id_forUser($user_id)
	{
		//SELECT menu FROM menu_control WHERE user_id=$user_id
		$this->db->select('menu');
		$this->db->from('menu_control');
		$this->db->where('user_id',$user_id);
		$query = $this->db->get();
		
		if($query->num_rows()>0)
		{
			$modules = $query->result_array();
			$count = count($modules);
			$menu = array();
			for($i=0;$i<$count;$i++)
			{
				array_push($menu,$modules[$i]['menu']);
								
			}			
			return $menu;

		}
		else return NULL;	
	}
	
	//gets all sub_menu for a give module/menu
	function get_sub_menu($menu_id)
	{
		//$query = "SELECT id FROM sub_menu WHERE parent_id=$menu_id"
		$this->db->select('id');
		$this->db->from('sub_menu');
		$this->db->where('parent_id',$menu_id);
		$query = $this->db->get();
						
		if($query->num_rows()>0)
		{
			$total_sub_menu = $query->result_array();
			$count = count($total_sub_menu);
			$sub_menu = array();
			for($i=0;$i<$count;$i++)
			{
				array_push($sub_menu,$total_sub_menu[$i]['id']);
								
			}			
			return $sub_menu;

		}
		else 
			return NULL;
	
	}
	
	//gets all sub_menu for a give module/menu for a corporation
	function get_sub_menu_forCorporation($menu_id)
	{
		$corp_id = $this->login_model->corp_id();
		//$query = "SELECT sub_menu FROM corporation_modules WHERE corporation_id=$corp_id AND menu=$menu_id"
		$this->db->select('sub_menu');
		$this->db->from('corporation_modules');
		$this->db->where('corporation_id',$corp_id);
		$this->db->where('menu',$menu_id);
		
		$query = $this->db->get();						
			
		if ($query->num_rows() == 1)
		{
			$row = $query->row_array(); 
			$sub_menu = $row['sub_menu'];
			$sub_menu = explode(",", $sub_menu);
			return   $sub_menu;
		}
		else 
			return NULL;
	
	}
	
	//returns the menu name to be used in div header
	private function get_menu_name($menu_id)
	{
		$this->db->select('menu_name');
		$this->db->from('menu');
		$this->db->where('id',$menu_id);
		
		$query = $this->db->get();
		if ($query->num_rows() == 1)
		{
			$row = $query->row_array(); 
			return $row['menu_name'];  
		}
		else return NULL;
		
	}
	
	
	//returns the submenu name to be used in check boxes
	private function get_sub_menu_name($sub_menu_id)
	{
		$this->db->select('submenu_name');
		$this->db->from('sub_menu');
		$this->db->where('id',$sub_menu_id);
		
		$query = $this->db->get();
		if ($query->num_rows() == 1)
		{
			$row = $query->row_array(); 
			return $row['submenu_name'];  
		}
		else return NULL;
		
	}
	
	//this function gets the granted submenu per corporation or per user per module
	private function get_granted_submenu_perCorporation_orPerUser_perModule($id,$module_id,$type)
	{
		$corp_id = $this->login_model->corp_id();
		
		if($type == 'corporation')
		{
			//$query = "SELECT sub_menu FROM corporation_modules WHERE corporation_id=$id AND $menu=$module_id"
			$this->db->select('sub_menu');
			$this->db->from('corporation_modules');
			$this->db->where('corporation_id',$id);
			$this->db->where('menu',$module_id);
		}
		else if($type == 'user')
		{
			//$query = "SELECT sub_menu FROM menu_control WHERE user_id=$id AND $menu=$module_id"
			$this->db->select('sub_menu');
			$this->db->from('menu_control');
			$this->db->where('user_id',$id);
			$this->db->where('menu',$module_id);
			
		}
		else if($type == 'corporations_default')
		{
			//$query = "SELECT sub_menu FROM corporations_default_permissions WHERE module_id = $module_id";
			$this->db->select('sub_menu');
			$this->db->from('corporations_default_permissions');
			//$this->db->where('user_id',$id);
			$this->db->where('menu',$module_id);
		}
		else if($type == 'corporation_staff')
		{
			//$query = "SELECT sub_menu FROM default_permissions WHERE corporation_id = $corp_id AND user_type = 3 AND module_id = $module_id";
			$this->db->select('sub_menu');
			$this->db->from('default_permissions');
			$this->db->where('corporation_id',$corp_id);
			$this->db->where('user_type',3);
			$this->db->where('menu',$module_id);
		}
		else if($type == 'corporation_member')
		{
			//$query = "SELECT sub_menu FROM corporations_default_permissions WHERE corporation_id = $corp_id AND user_type = 4 AND module_id = $module_id";
			$this->db->select('sub_menu');
			$this->db->from('default_permissions');
			$this->db->where('corporation_id',$corp_id);
			$this->db->where('user_type',4);
			$this->db->where('menu',$module_id);
		}
		
		$query = $this->db->get();
		if ($query->num_rows() == 1)
		{
			$row = $query->row_array(); 
			$granted_sub_menu = $row['sub_menu'];
			$granted_sub_menu = explode(",", $granted_sub_menu);
			return   $granted_sub_menu;
		}
		else return NULL;
		
	}
	
	//this function returns submenu under granted permissions with checked values where applicable
	private function return_marked_sub_menu($id,$module_id,$type)
	{
		if($type == 'corporation' || $type == 'corporations_default')
		{
			$all_sub_menu = $this->get_sub_menu($module_id);
		}
		else if($type == 'user' || $type == 'corporation_staff' || $type == 'corporation_member')
		{
			$all_sub_menu = $this->get_sub_menu_forCorporation($module_id);
		}
		
		$granted_sub_menu = $this->get_granted_submenu_perCorporation_orPerUser_perModule($id,$module_id,$type);
			
			$htmldata = "";
			foreach($all_sub_menu as $key=>$val)
			{
				if(in_array($val,$granted_sub_menu))
				{
					$htmldata .= "
									<div class=\"form-group check_box\">
									  <label>
										<input type=\"checkbox\" value=".$val." onchange=\"submitCheckedSubMenu(".$module_id.","."'".$type."'".")\" class=\"minimal\" id=\"chkbox".$val."\" checked=\"checked\" />".
										$this->get_sub_menu_name($val)
									  ."</label>
									  </div>";	
				}
				else 
					$htmldata .= "
									<div class=\"form-group check_box\">
									  <label>
										<input type=\"checkbox\" value=".$val." onchange=\"submitCheckedSubMenu(".$module_id.","."'".$type."'".")\" class=\"minimal\" id=\"chkbox".$val."\"/>".
										$this->get_sub_menu_name($val)
									  ."</label>
									  </div>";	
				
			}
			return $htmldata;
	}
	
	//this function removes permission from granted permissions
	function remove_module_access($table,$id)
	{
		//$query = "DELETE FROM corporation_modules/or menu_control/or corporations_default_permissions WHERE id=$id"
		$this->db->delete($table, array('id' => $id));
		
	}
 
 	//this function updates menu permissions by updating granted or removed submenu
	function update_submenu_permission($id,$module_id,$submenu,$type)
	{
		
		$corp_id = $this->login_model->corp_id();
		
		/*$query = "Update corporation_modules SET submenu = $submenu 
				   WHERE corporation_id = $id AND menu = $module_id"; or user_id = $id in table menu_control for users*/
		$data = array('sub_menu' => $submenu);
		
		if($type == 'corporation')
		{
			$this->db->update('corporation_modules', $data, array('corporation_id' => $id, 'menu' => $module_id));
		}
		else if($type == 'user')
		{
			$this->db->update('menu_control', $data, array('user_id' => $id, 'menu' => $module_id));
		}
		else if($type == 'corporations_default')
		{
			$this->db->update('corporations_default_permissions', $data, array('menu' => $module_id));
		}
		else if($type == 'corporation_staff')
		{
			$this->db->update('default_permissions', $data, array('corporation_id' => $corp_id, 'user_type' => 3, 'menu' => $module_id));
		}
		else if($type == 'corporation_member')
		{
			$this->db->update('default_permissions', $data, array('corporation_id' => $corp_id, 'user_type' => 4,'menu' => $module_id));
		}
		
		if($this->db->affected_rows() == 1)
		{
			return true;
		}
		else 
		{
			return false;
		}
	}
	
	//this function deactivates user accounts
	function activate_user_account($type, $id)
	{
		if($type == 'corporation')
		{			
			//$query = "UPDATE users SET active_status = 0 WHERE corporation_id = $id";
			$data = array('active_status' => 1);
			$this->db->where('corporation_id',$id);
			$this->db->update('users',$data);			
			
		}else if($type == 'user')
		{			
			//$query = "UPDATE users SET active_status = 0 WHERE id = $id";
			$data = array('active_status' => 1);
			$this->db->where('user_id',$id);
			$this->db->update('users',$data);			
			
		}
		
		if ($this->db->affected_rows() > 0)
		{			
			return   TRUE;
		}
		else
			return FALSE;
		
	}
	
	
	//this function deactivates user accounts
	function deactivate_user_account($type, $id)
	{
		if($type == 'corporation')
		{			
			//$query = "UPDATE users SET active_status = 0 WHERE corporation_id = $id";
			$data = array('active_status' => 0);
			$this->db->where('corporation_id',$id);
			$this->db->update('users',$data);			
			
		}else if($type == 'user')
		{			
			//$query = "UPDATE users SET active_status = 0 WHERE id = $id";
			$data = array('active_status' => 0);
			$this->db->where('user_id',$id);
			$this->db->update('users',$data);			
			
		}
		
		if ($this->db->affected_rows() > 0)
		{			
			return   TRUE;
		}
		else
			return FALSE;
		
	}
	
	//for super admin to get total accounts per corporation, active accounts and inactive account
	function corporation_accounts_status()
	{
		//get all corporation
		$all_corps = "SELECT corporation_id FROM corporations";
		$result = mysql_query($all_corps);
		
		//loop all corporations to create a multidimensional array for total accounts, active and inactive accounts
		$corpAccounts = array();
		while($row = mysql_fetch_array($result))
		{	
			$corp_id = $row['corporation_id'];		
			$totalAccountsQuery = "SELECT COUNT(*) AS total_accounts FROM users WHERE corporation_id = $corp_id";
			$totalAccountsResult = mysql_query($totalAccountsQuery);
			$totalAccountsRow = mysql_fetch_array($totalAccountsResult);
			$totalAccounts = $totalAccountsRow['total_accounts'];
				
			$activeAccountsQuery = "SELECT COUNT(*) AS active_accounts FROM users WHERE corporation_id = $corp_id AND active_status = 1";
			$activeAccountsResult = mysql_query($activeAccountsQuery);
			$activeAccountsRow = mysql_fetch_array($activeAccountsResult);
			$activeAccounts = $activeAccountsRow['active_accounts'];
			
			$inactiveAccountsQuery = "SELECT COUNT(*) AS inactive_accounts FROM users WHERE corporation_id = $corp_id AND active_status = 0";
			$inactiveAccountsResult = mysql_query($inactiveAccountsQuery);
			$inactiveAccountsRow = mysql_fetch_array($inactiveAccountsResult);
			$inactiveAccounts = $inactiveAccountsRow['inactive_accounts'];
			
			$corpAccounts[$corp_id]['total_accounts'] = $totalAccounts;
			$corpAccounts[$corp_id]['active_accounts'] = $activeAccounts;
			$corpAccounts[$corp_id]['inactive_accounts'] = $inactiveAccounts;
			
		}
		return $corpAccounts;
	}
	
	
	/*Functions for Default Permission*/
	/*function to get all available permissions in the database. To be seen by super admin 
	when assigning corporations default permissions*/
	function get_all_available_modules_forCorporations()
	{
		$sqlQuery = "SELECT * FROM menu WHERE id NOT IN (SELECT menu FROM corporations_default_permissions)";
		//$query = $this->db->get('menu');
		$query = $this->db->query($sqlQuery);
		$menu = '';
		foreach($query->result_array() as $modules)
		{
			$menu .= "
					  <div class=\"col-md-4\">
							<div class=\"box box-primary\">
								<div class=\"box-header with-border\">";
								$menu .="<h3 class=\"box-title\">".$modules['menu_name']." - ".$modules['id']."</h3>
								</div><!-- /.box-header -->									
								<div class=\"box-body\">
								   <a href=\"#\" onclick=\"grantModuleAlertDP(".$modules['id'].")\"><span class=\"blue\">Click to grant permission</span></a>
								</div>
							</div>
						</div>";				
		}
			return $menu;
	}
	
	
	/*NOTE: Prefix DP added to mark the functions as meant for Deafault Permissions*/
	
	//this function gets available(which can be granted) modules/menu in db
	function get_all_available_modules_perUserLevel($id,$type)
	{
		$corp_id = $this->login_model->corp_id();
		
		if($type == 'corporation')
		{
			//$query = "SELECT * FROM menu WHERE id NOT IN("SELECT id FROM corporation_id=$corporation_id")"
			$array = $this->get_granted_modules_id($id);
			$this->db->select('*');
			$this->db->from('menu');
			$this->db->where_not_in('id',$array);
		}
		else if($type == 'user')
		{
			/*$query = "SELECT * FROM corporation_modules WHERE corporation_id = $corp_id 
						AND menu NOT IN("SELECT menu FROM menu_control WHERE user_id=$user_id")"*/
			$array = $this->get_granted_modules_id_forUser($id);
			$this->db->select('*');
			$this->db->from('corporation_modules');
			$this->db->where('corporation_id',$corp_id);
			$this->db->where_not_in('menu',$array);
		}
		
		$query = $this->db->get();
		
		//echo $this->db->last_query()."<br>";//for debugging
		if($query->num_rows()>0)
		{
			$modules = $query->result_array();
			$count = count($modules);
			$menu = '';
			for($i=0;$i<$count;$i++)
			{
				//$menu .= $modules[$i]['menu_name']."<br>";
				$menu .= "
						  <div class=\"col-md-4\">
								<div class=\"box box-primary\">
									<div class=\"box-header with-border\">";
									if($type == 'corporation')
									$menu .="<h3 class=\"box-title\">".$modules[$i]['menu_name']." - ".$modules[$i]['id']."</h3>
									</div><!-- /.box-header -->									
									<div class=\"box-body\">
									   <a href=\"#\" onclick=\"grantModuleAlert(".$modules[$i]['id'].","."'".$type."'".")\"><span class=\"blue\">Click to grant permission</span></a>
									</div>
								</div>
							</div>";
									else
									$menu .="<h3 class=\"box-title\">".$this->get_menu_name($modules[$i]['menu'])." - ".$modules[$i]['id']."</h3> 
									</div><!-- /.box-header -->									
									<div class=\"box-body\">
									   <a href=\"#\" onclick=\"grantModuleAlert(".$modules[$i]['menu'].","."'".$type."'".")\"><span class=\"blue\">Click to grant permission</span></a>
									</div>
								</div>
							</div>";				
				}
			return $menu;

		}
		else 
			 $return = "<p>There are no nodules to display</p>";
			 return $return;		
		
	}
}
?>