<repo_name>rullymartanto/Angularjs-Codeigniter-GenesisUI<file_sep>/application/models/Access_item_model.php
<?php
/**
 * User: gamalan
 * Date: 3/17/2015
 * Time: 10:06 AM
 */

class access_item_model extends AR_Model {

    public function __construct(){
        parent::__construct();
        $this->allow_insert = "user_access_id,access_item_id,access_item_type,access_custom";
        $this->allow_update = "access_item_id,access_item_type,access_custom";
        $this->tblName = "t_access_item";
        $this->tblId = "id";
    }

}<file_sep>/application/controllers/AuthController.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class AuthController extends AR_Controller {

	public function __construct(){

		parent::__construct();
		$this->load->model("user_model");

	}

	public function index(){

	}

	public function login()
	{
		$result = $this->result;
		$post_data = $this->input_data;

		$username = $post_data['username'];
		$userData = $this->App_model->find('user', $username,"username");
		$password = md5(strtolower($username).$post_data['password']);

		if(isset($userData['password']) && $userData['password'] == $password){

			$result['data'] = $userData;
			$result['error'] = 0;
			$result['msg'] = '';

		}	

		echo json_encode($result);
	}
	
	public function logout(){
	
		$this->session->unset_userdata('adminData');
		session_destroy();
	
	}

}

<file_sep>/application/helpers/ar_helper.php
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
//helper
//created by : <NAME>


    function generateSearchString($search,$sort_by = "",$order = "",$page = 1,$limit = ""){
        $str = "";
        $page--;
        $start = $page * $limit;
        $str .= " AND ( ";
        
        foreach($search as $key=>$val){

            if($key != 0){
                $str .= " OR ";
            }
            
            $str .= " ".$val[1]." ".$val[2]." '".$val[0]."'";
            
        }
        $str .= " ) ";
        if($sort_by != ""){
            $str .= " ORDER BY $sort_by $order";
        }
        if($limit != ""){
            $str .= " limit $start,$limit";
        }
    
        return $str;
    }
    function search_access_array($id, $array) {
        if(count($array)>0){
            foreach ($array as $key => $val) {
                if ($val['id'] === $id) {
                   return $val;
                }
            }
        }
       return null;
    }
    function generateBootstrapPagination($base_url,$total,$limit){
        //BEGIN PAGINATION
            $ci =& get_instance(); 
            $ci->load->library("pagination");
            $config['base_url'] = $base_url;
            $config['total_rows'] = $total;
            $config['per_page'] = $limit;
            $config['query_string_segment'] = "page";
            $config['use_page_numbers'] = TRUE;
            $config['page_query_string'] = TRUE;
            $config['full_tag_open'] = "<ul class='pagination'>";
            $config['full_tag_close'] ="</ul>";
            $config['num_tag_open'] = '<li>';
            $config['num_tag_close'] = '</li>';
            $config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
            $config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
            $config['next_tag_open'] = "<li>";
            $config['next_tagl_close'] = "</li>";
            $config['prev_tag_open'] = "<li>";
            $config['prev_tagl_close'] = "</li>";
            $config['first_tag_open'] = "<li>";
            $config['first_tagl_close'] = "</li>";
            $config['last_tag_open'] = "<li>";
            $config['last_tagl_close'] = "</li>";
            $ci->pagination->initialize($config);
            return $ci->pagination->create_links();
        //END PAGINATION
    }
    function ismobile()
        {
            $mobile_browser = '0';

            if (preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|android)/i', strtolower($_SERVER['HTTP_USER_AGENT']))) {
                    $mobile_browser++;
            }

            if ((strpos(strtolower($_SERVER['HTTP_ACCEPT']),'application/vnd.wap.xhtml+xml') > 0) or ((isset($_SERVER['HTTP_X_WAP_PROFILE']) or isset($_SERVER['HTTP_PROFILE'])))) {
                    $mobile_browser++;
            }

            $mobile_ua = strtolower(substr($_SERVER['HTTP_USER_AGENT'], 0, 4));
            $mobile_agents = array(
                            'w3c ','acs-','alav','alca','amoi','audi','avan','benq','bird','blac',
                            'blaz','brew','cell','cldc','cmd-','dang','doco','eric','hipt','inno',
                            'ipaq','java','jigs','kddi','keji','leno','lg-c','lg-d','lg-g','lge-',
                            'maui','maxo','midp','mits','mmef','mobi','mot-','moto','mwbp','nec-',
                            'newt','noki','oper','palm','pana','pant','phil','play','port','prox',
                            'qwap','sage','sams','sany','sch-','sec-','send','seri','sgh-','shar',
                            'sie-','siem','smal','smar','sony','sph-','symb','t-mo','teli','tim-',
                            'tosh','tsm-','upg1','upsi','vk-v','voda','wap-','wapa','wapi','wapp',
                            'wapr','webc','winw','winw','xda ','xda-');

            if (in_array($mobile_ua,$mobile_agents)) {
                    $mobile_browser++;
            }

            if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']),'windows') > 0) {
                    $mobile_browser = 0;
            }

            if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']),'mac') > 0) {
                    $mobile_browser = 0;
            }

            if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']),'ios') > 0) {
                    $mobile_browser = 1;
            }
            if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']),'android') > 0) {
                    $mobile_browser = 1;
            }
            if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']),'windows phone') > 0) {
                    $mobile_browser = 1;
            }	
            if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']),'iphone os') > 0) {
                    $mobile_browser = 1;
            }
            return $mobile_browser;
    }
	function getPrefixNo($id)
	{
		
        $ci =& get_instance(); 
        $ci->load->model("prefix_model");
		$ci->load->database();
		$structure = $ci->db->query("SELECT * FROM prefix WHERE id = '$id' ORDER BY running_number DESC LIMIT 1")->row_array();
		
		$intial = $structure['prefix'];
		$length = $structure['length'];

		if ($structure['running_number'] >= 1)
		{
			$number = intval($structure['running_number']);
		}else{
			$number = 0;
		}
		$number++;
		$tmp= "";
		for ($i=0; $i < ($length-strlen($number)) ; $i++)
		{
			$tmp = $tmp."0";
		}
		$ci->prefix_model->update($id,array('running_number'=>$number));
		//return generate ID
		return strval($intial.$tmp.$number);
	}

    function getPrefixmmyy($id)
    {
        
        $ci =& get_instance(); 
        $ci->load->model("prefix_model");
        $ci->load->database();
        $structure = $ci->db->query("SELECT * FROM prefix WHERE id = '$id' ORDER BY running_number DESC LIMIT 1")->row_array();

        $intial = date("my");
        $length = $structure['length'];

        if ($structure['running_number'] >= 1)
        {
            $number = intval($structure['running_number']);
        }else{
            $number = 0;
        }
        $number++;
        $tmp= "";
        for ($i=0; $i < ($length-strlen($number)) ; $i++)
        {
            $tmp = $tmp."0";
        }
        $ci->prefix_model->update($id,array('running_number'=>$number));
        //return generate ID
        return strval($intial.$tmp.$number);
    }
	
    function upload_handler($file_name,$new_name,$new_path, $required = true,$old_file_path = ""){
        $ci =& get_instance();
        $returnData = array();
        $config['upload_path'] = $new_path;
        $config['allowed_types'] = 'jpg|png|jpeg';
        $config['max_size'] = '1024';
        $config['max_width']  = '1024';
        $config['max_height']  = '1024';
        $config['overwrite'] = TRUE;
        $config['file_name'] = $new_name;
        $ci->load->library('upload', $config);
        if(isset($_FILES[$file_name]))
        {
            if (!$ci->upload->do_upload($file_name))
            {
                
                $returnData['error'] =  $ci->upload->display_errors();
                $returnData['status'] = 0;
            }
            else
            {
             
                $upload_data = $ci->upload->data();
                $returnData['file_path'] = $new_path.$upload_data['raw_name'].$upload_data['file_ext'];
           
                $parts = explode(".",$upload_data['full_path']);
                $ci->load->library('image_lib');
                    /* read the source image */
                    if($upload_data['file_type'] == "image/jpeg" || $upload_data['file_type'] == "image/jpg"){
                         $source_image = imagecreatefromjpeg($upload_data['full_path']);
                    }
                    else if($upload_data['file_type'] == "image/png"){
                        $source_image = imagecreatefrompng($upload_data['full_path']);
                    }
                    else if($upload_data['file_type'] == "image/gif"){
                        $source_image = imagecreatefromgif($upload_data['full_path']);
                    }

                    $width = imagesx($source_image);
                    $height = imagesy($source_image);
                    /* create a new, "virtual" image */
                  
                    
                    // first resize the image 
                    $thumbnail_size = 200;
                    if ($width < $height){
                        $desired_width = $thumbnail_size;
                        $desired_height = floor($height * ($desired_width / $width));
                        $w_start = 0;
                        $h_start = $desired_height / 2 - ($thumbnail_size/2);
                    }else{
                         $desired_height = $thumbnail_size;
                        $desired_width = floor($width * ($desired_height / $height));
                        $w_start = $desired_width / 2 - ($thumbnail_size/2);
                        $h_start = 0;
                    }

                    /* copy source image at a resized size based on the shortest length */
                    $virtual_image = imagecreatetruecolor(200, 200);
                    imagecopyresampled($virtual_image, $source_image, -$w_start, -$h_start, 0, 0, $desired_width, $desired_height, $width, $height);
                
                    /* create the physical thumbnail image to its destination */
                    $thumbnail_path = $upload_data['file_path']."/".$upload_data['raw_name']."_thumb".$upload_data['file_ext'];
                    $returnData['thumbnail_path'] = $new_path."/".$upload_data['raw_name']."_thumb".$upload_data['file_ext'];
                    if($upload_data['file_type'] == "image/jpeg" || $upload_data['file_type'] == "image/jpg"){
                         imagejpeg($virtual_image, $thumbnail_path);
                    }
                    else if($upload_data['file_type'] == "image/png"){
                         imagepng($virtual_image, $thumbnail_path);
                    }
                    else if($upload_data['file_type'] == "image/gif"){
                         imagegif($virtual_image, $thumbnail_path);
                    }
                  $returnData['status'] = 1;
                //END CREATING THUMBNAILS
                //BEGIN DELETE OLD FILE
                    if($old_file_path != ""){
                        if(file_exists($old_file_path)){
                            unlink($old_file_path);
                        }
                        $parts = explode(".",$old_file_path);
                        $old_thumb_path = $parts[0]."_thumb.".$parts[1];
                        if(file_exists($old_thumb_path)){
                            unlink($old_thumb_path);
                        }
                    }
                //END DELETE OLD FILE
            }
        }
        else{
            if($required){
                $returnData['status'] = 1;
            }
            else{
                $returnData['status'] = 0;
            }
        }
   
        return $returnData;
    }
	function labelStatus($status){
		$label 	= '';
		if($status == "PENDING"){
			$label .= '<span class="label label-info">';
		}else if($status == "PROCESSED"){
			$label .= '<span class="label label-primary">';
		}else if($status == "OPEN"){
			$label .= '<span class="label label-success">';
		}else if($status == "PAID"){
			$label .= '<span class="label label-success">';
		}else if($status == "CLOSE"){
			$label .= '<span class="label label-default">';
		}else if($status == "CLOSED"){
			$label .= '<span class="label label-default">';
		}else if($status == "UNPAID"){
			$label .= '<span class="label label-warning">';
		}else if($status == "FINISHING"){
			$label .= '<span class="label label-info">';
			$class = 'Info';
		}else if($status == "FINISHED"){
			$label .= '<span class="label label-default">';
		}else if($status == "PARTITIAL PAID"){
            $label .= '<span class="label label-warning">';
        }
		$label .= $status."</span>";
		return $label;
	}

    function generate_table_header(){

    }
	
	/* created by samuel */
	function time_ago( $date )
	{
		if( empty( $date ) )
		{
			return "No date provided";
		}

		$periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");

		$lengths = array("60","60","24","7","4.35","12","10");

		$now = time();

		$unix_date = strtotime( $date );

		// check validity of date

		if( empty( $unix_date ) )
		{
			return "Bad date";
		}

		// is it future date or past date

		if( $now > $unix_date )
		{
			$difference = $now - $unix_date;
			$tense = "ago";
		}
		else
		{
			$difference = $unix_date - $now;
			$tense = "from now";
		}

		for( $j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++ )
		{
			$difference /= $lengths[$j];
		}

		$difference = round( $difference );

		if( $difference != 1 )
		{
			$periods[$j].= "s";
		}

		return "$difference $periods[$j] {$tense}";

	}
	
	
	function generateBarcode($code){
		$ci =& get_instance();
		$path = "./public/barcode/";
		$ci->load->library('Zend');
        //load in folder Zend
        $ci->zend->load('Zend/Barcode');
        //generate barcode
        $file = Zend_Barcode::draw('code128', 'image', array('text'=>$code), array());
		$code = time().$code;
		$store_image = imagepng($file,$path."{$code}.png");
		return $path."{$code}.png";
	}
    
     function add_comission($id=null)
	{
		
        $ci =& get_instance(); 
        $ci->load->model("prefix_model");
		$ci->load->database();
        
		$inv = $ci->db->query("SELECT * FROM sales_invoice WHERE id = '$id'")->row_array();
		$sales_id = $inv['sales_id'];
           
		$sales =  $ci->db->query("SELECT * FROM sales WHERE id = '$sales_id'")->row_array();
        $cust_id=$sales['customer_id'];
        
        $cust =  $ci->db->query("SELECT * FROM customer WHERE id = '$cust_id'")->row_array();
        $salesman_id=$cust['salesman_id'];
        $join_date=$cust['join_date'];
        
          
        $user_com =  $ci->db->query("SELECT * FROM user_comission WHERE user_id = '$salesman_id' and sales_id='$sales_id'");
        
        $count_ucom=$user_com->num_rows();
        if($count_ucom==0){
            $now=gmdate("Y-m-d"); 
    		$date1 = new DateTime($join_date);
    		$now1 = new DateTime($now);
            
            $join_month=$now1->diff($date1)->format("%m");
            $comission_value=0;
            
    		$u_com_setting =  $ci->db->query("SELECT * FROM user_comission_setting WHERE user_id = '$salesman_id' and is_general=0 and deleted_by is null")->row_array();
    
            $com_set_id=$u_com_setting['comission_setting_id'];
            $u_com_setting =  $ci->db->query("SELECT * FROM comission_setting_detail WHERE comission_setting_id = '$com_set_id'")->result_array();
                $i=0;
                foreach($u_com_setting as $row){
        	       if($join_month>=$row['from_month'] && $join_month<=$row['to_month']){
        	           $comission_value=($row['percentage']/100)*$sales['grand_total'];
                       $data_comission=array(
                        "sales_id"=>$sales_id,
                        "user_id"=>$salesman_id,
                        "calculation"=>$row['percentage']."%",
                        "comission"=>$comission_value,
                        "month"=>$join_month
                       );
                       $ci->db->insert("user_comission",$data_comission);
                       $i++;
                      
        	       }
        	    }
                if($i==0){
                    return "Error";
                }else{
                    return "Success add comission";
                }
        }else{
            return "Not add comission";
        }
    }
    
    function product_log($status=null,$remarks=null,$id=null)
	{
		
        $ci =& get_instance(); 
		$ci->load->database();
        $result="";
		$detail = $ci->db->query("SELECT * FROM delivery_order_detail WHERE delivery_order_id = '$id'")->result_array();
    		foreach($detail as $d){
    		  $stock = $ci->db->query("SELECT * FROM product_stock WHERE product_id = '$d[product_id]'")->row_array();
              if($status=="in"){
                    $update_stock=$stock['qty']+$d['qty'];
      		        $data_log=array(
                            "product_id"=>$d['product_id'],
                            "start_qty"=>$stock['qty'],
                            "in"=>$d['qty'],
                            "remarks"=>$remarks,
                            "end_qty"=>$update_stock
                           );
                    $ci->db->insert("product_stock_log",$data_log);
                    $data_stock=array(
                        "qty"=>$update_stock
                       );
                    $ci->db->where('id', $stock['id']);
                    $ci->db->update("product_stock",$data_stock);
                    
                    $sd=$ci->db->query("SELECT * FROM sales_detail WHERE id = '$d[sales_detail_id]'")->row_array();                    
                    $balance_stock=$sd['balance']+$d['qty'];                    
                    $data_balance=array(
                        "balance"=>$balance_stock
                       );
                    $ci->db->where('id',$d['sales_detail_id']);
                    $ci->db->update("sales_detail",$data_balance);                    
                    $result.="Plus In Success ".$d['product_id'];
              }else if($status=="out"){
                    $update_stock=$stock['qty']-$d['qty'];
      		        $data_log=array(
                            "product_id"=>$d['product_id'],
                            "start_qty"=>$stock['qty'],
                            "out"=>$d['qty'],
                            "remarks"=>$remarks,
                            "end_qty"=>$update_stock
                           );
                    $ci->db->insert("product_stock_log",$data_log);
                    $data_stock=array(
                        "qty"=>$update_stock
                       );
                    $ci->db->where('id', $stock['id']);
                    $ci->db->update("product_stock",$data_stock);
                    $result.="Plus Out Success ".$d['product_id'];
		      }else{
		          $result.="No Action";
		      }
              
    		}
        return $result;
		
	}

     function preprocess_date($date_data){
        if($date_data == "" || $date_data == "0000-00-00"){
            $ret_data = NULL;
        }else{
            $ret_data = date("Y-m-d",strtotime($date_data));
        }
        return $ret_data;
    }

    function view_date($date_data){
   
        if($date_data == "" || $date_data == "0000-00-00"){
            $date_data = "";
        }else{
            $date_data = date("d-m-Y",strtotime($date_data));
        }
        return $date_data;
    }
    function view_date_1($date_data){
   
        if($date_data == "" || $date_data == "0000-00-00"){
            $date_data = "";
        }else{
            $date_data = date("d/m/Y",strtotime($date_data));
        }
        return $date_data;
    }
    
    
    function get_timeago( $ptime )
    {
        $estimate_time = time() - $ptime;

        if( $estimate_time < 1 )
        {
            return 'less than 1 second ago';
        }

        $condition = array(
                    12 * 30 * 24 * 60 * 60  =>  'year',
                    30 * 24 * 60 * 60       =>  'month',
                    24 * 60 * 60            =>  'day',
                    60 * 60                 =>  'hour',
                    60                      =>  'minute',
                    1                       =>  'second'
        );

        foreach( $condition as $secs => $str )
        {
            $d = $estimate_time / $secs;

            if( $d >= 1 )
            {
                $r = round( $d );
                return 'about ' . $r . ' ' . $str . ( $r > 1 ? 's' : '' ) . ' ago';
            }
        }
    }

    function send_mail($to="",$subject="",$message=""){ 
        $ci =& get_instance();
        
        $ci->load->library('email');
        $ci->load->model('company_model');

        $ci->email->set_newline("\r\n");
        
        $ci->email->from("<EMAIL>");
        $to = "<EMAIL>";
        
        $ci->email->to($to);
        $ci->email->subject($subject);
        $ci->email->message($message);
        
        try {
            $ci->email->send();
            $email_debug = $ci->email->print_debugger();  
            return 0; 
        } catch (Exception $e) {
            return 1;;
        }
        
    }


    function product_addition_qty($post_data){

        $ci =& get_instance();
        $ci->load->model('product_stock_model');
        $ci->load->model('product_log_model');

        $error =0;
        $check_product_stok  = $ci->product_stock_model->find($post_data["product_id"],"product_id"," AND company_branch_id =  ".$post_data["company_branch_id"]);

        $credit = NULL;
        $debit = $post_data["addition"];
        if($check_product_stok){
            $starting_balance   = $check_product_stok["qty"];
            $ending_balance     =  $check_product_stok["qty"]+$post_data["addition"];

            $new_qty = $check_product_stok["qty"]+$post_data["addition"];
            $update_data = array();
            $update_data["qty"] = $new_qty;

            $ci->product_stock_model->update($check_product_stok["id"],$update_data);
            $id = $check_product_stok["id"];

        }else{
            $starting_balance = $post_data["addition"];
            $ending_balance = $post_data["addition"];

            $post_data["qty"] = $post_data["addition"];
            $id = $ci->product_stock_model->add($post_data);
        }

        if(isset($id)){
            $error = 0;

            //product log
            $product_log_data = array();
            $product_log_data["product_id"] = $post_data["product_id"];
            $product_log_data["company_branch_id"] = $post_data["company_branch_id"];
            $product_log_data["starting_balance"] = $starting_balance;
            $product_log_data["debit"] = $debit;
            $product_log_data["credit"] = $credit;
            $product_log_data["ending_balance"] = $ending_balance;
            $product_log_data["remarks"] = $post_data["remarks"];

            $ci->product_log_model->add($product_log_data);
        }else{
            $error = 1;
        }
        return $error;
    }
    function product_dedcution_qty($post_data){

        $ci =& get_instance();
        $ci->load->model('product_stock_model');
        $ci->load->model('product_log_model');

        $error =0;
        $check_product_stok  = $ci->product_stock_model->find($post_data["product_id"],"product_id"," AND company_branch_id =  ".$post_data["company_branch_id"]);
        
        if($check_product_stok["qty"] >= $post_data["deduction"] ){
            $credit = $post_data["deduction"];
            $debit = NULL;
            $starting_balance = $check_product_stok["qty"];
            $ending_balance = $check_product_stok["qty"]-$post_data["deduction"];

            $new_qty = $check_product_stok["qty"]-$post_data["deduction"];
            $update_data = array();
            $update_data["qty"] = $new_qty;

            $ci->product_stock_model->update($check_product_stok["id"],$update_data);
            $id = $check_product_stok["id"];

        }
        if(isset($id)){
            //product log
            $product_log_data = array();
            $product_log_data["product_id"] = $post_data["product_id"];
            $product_log_data["company_branch_id"] = $post_data["company_branch_id"];
            $product_log_data["starting_balance"] = $starting_balance;
            $product_log_data["debit"] = $debit;
            $product_log_data["credit"] = $credit;
            $product_log_data["ending_balance"] = $ending_balance;
            $product_log_data["remarks"] = $post_data["remarks"];

            $ci->product_log_model->add($product_log_data);
            $error = 0;
        }else{
            $error = 1;
        }
        return $error;
    }
	
	function product_log_purchase($status=null,$remarks=null,$id=null,$qty=null)
	{
		
        $ci =& get_instance(); 
		$ci->load->database();
        
		$d = $ci->db->query("SELECT * FROM purchase_order_detail WHERE id = '$id'")->row_array();
    		  $stock = $ci->db->query("SELECT * FROM product WHERE id = '$d[product_id]'")->row_array();
              if($status=="in"){
                    $update_stock=$stock['qty']+$qty;
      		        $data_log=array(
                            "product_id"=>$d['product_id'],
                            "start_qty"=>$stock['qty'],
                            "in"=>$qty,
                            "remarks"=>$remarks,
                            "end_qty"=>$update_stock
                           );
                    $ci->db->insert("product_stock_log",$data_log);
                    $data_stock=array(
                        "qty"=>$update_stock
                       );
                    $ci->db->where('id', $stock['id']);
                    $ci->db->update("product",$data_stock);
                    return "Plus In Success";
              }else if($status=="out"){
                    $update_stock=$stock['qty']-$qty;
      		        $data_log=array(
                            "product_id"=>$d['product_id'],
                            "start_qty"=>$stock['qty'],
                            "out"=>$qty,
                            "remarks"=>$remarks,
                            "end_qty"=>$update_stock
                           );
                    $ci->db->insert("product_stock_log",$data_log);
                    $data_stock=array(
                        "qty"=>$update_stock
                       );
                    $ci->db->where('id', $stock['id']);
                    $ci->db->update("product",$data_stock);
                    return "Plus Out Success";
		      }else{
		          return "No Action";
		      }
		
	}



<file_sep>/application/models/Access_item_category_model.php
<?php

/**

 * User: mike

 * Date: 3/28/2015

 * Time: 12:01 AM

 */



class Access_Item_Category_Model extends AR_Model {



    public function __construct(){

        parent::__construct();

        $this->allow_insert = "user_access_id,access_item_id,access_item_type,access_custom";

        $this->allow_update = "access_item_id,access_item_type,access_custom";

        $this->tblName = "t_access_category";

        $this->tblId = "id";



    }



    public function get_sidemenu_categories($user_access_ids){

    	$query = "SELECT DISTINCT access_category_id FROM t_access_item WHERE";

        $query .= " route IS NOT NULL AND ( ";

    	foreach($user_access_ids as $key=>$id){

    		if($key!=0){

    			$query .= " OR";

    		}

    		$query .= " id = '$id'";

    	}

        $query .=" ) ";

        $query .=" Order by display_order asc";

    	$datas = $this->query($query);

    	$query2 = "SELECT * FROM t_access_category WHERE";

    	foreach($datas->result_array() as $key=>$row){

    		if($key != 0){

    			$query2 .= " OR";

    		}

    		$query2 .= " id = '".$row['access_category_id']."'";

    	}
        $query2 .=" Order by display_order asc";
    	$ret = $this->query($query2);

        foreach($ret->result_array() as $row){

            $return[] = $row;

        }

    	return $return;

    }



}<file_sep>/application/models/User_group_model.php
<?php
class User_group_model extends AR_Model    
{

    public function __construct()
    {
        parent::__construct();
        $this->tblName = "user_group";
        $this->tblId = "id";
        $this->allow_insert = "code,description";
        $this->allow_update = "code,description";
    }
    
    
}
?>
<file_sep>/application/views/admin_template.php

<!DOCTYPE html>
<html lang="en" ng-app="app">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <meta name="description" content="Admin Panel Bootstrap 4.0.0 &amp; AngularJS 1.5.0">
        <!-- <link rel="shortcut icon" href="assets/ico/favicon.png"> -->
        <title>ROOT Admin - UI Admin Kit</title>
        <link href="<?php echo base_url("angularjs/assets/css/style.css")?>" rel="stylesheet">
        <script>
        var base_url = "<?php echo base_url();?>";
            </script>
    </head>
    <body class="navbar-fixed sidebar-nav fixed-nav">
        <base href="<?php echo base_url();?>angularjs/" />
        <!-- User Interface -->
        <ui-view></ui-view>

        <script src="<?php echo base_url("angularjs/assets/libs/jquery.min.js")?>"></script>
        <script src="<?php echo base_url("angularjs/assets/libs/tether.min.js")?>"></script>
        <script src="<?php echo base_url("angularjs/assets/libs/bootstrap.min.js")?>"></script>

        <script src="<?php echo base_url("angularjs/assets/libs/angular.min.js")?>"></script>

        <script src="<?php echo base_url("angularjs/assets/libs/angular-animate.min.js")?>"></script>
        <script src="<?php echo base_url("angularjs/assets/libs/angular-sanitize.min.js")?>"></script>
        <script src="<?php echo base_url("angularjs/assets/libs/angular-ui-router.min.js")?>"></script>
        <script src="<?php echo base_url("angularjs/assets/libs/ocLazyLoad.min.js")?>"></script>
        <script src="<?php echo base_url("angularjs/assets/libs/angular-translate.min.js")?>"></script>
        <script src="<?php echo base_url("angularjs/assets/libs/angular-breadcrumb.min.js")?>"></script>
        <script src="<?php echo base_url("angularjs/assets/libs/loading-bar.min.js")?>"></script>

        <script src="<?php echo base_url("angularjs/assets/libs/ngstorage/ngStorage.js")?>"></script>

        <script src="<?php echo base_url("angularjs/scripts/app.js")?>"></script>
        <script src="<?php echo base_url("angularjs/scripts/config.js")?>"></script>
        <script src="<?php echo base_url("angularjs/scripts/config.lazyload.js")?>"></script>
        <script src="<?php echo base_url("angularjs/scripts/config.routes.js")?>"></script>
        <script src="<?php echo base_url("angularjs/scripts/services.api.js")?>"></script>
        <script src="<?php echo base_url("angularjs/controllers/SidebarCtrl.js")?>"></script>
        
        <script src="<?php echo base_url("angularjs/directives/directives.js")?>"></script>
        <script src="<?php echo base_url("angularjs/directives/lazyload.js")?>"></script>

        <!-- <script>

              function open_modal(data,$modal){

                 var modalInstance = $modal.open({
                        animation: true,
                        templateUrl: 'views/modal/'+data.template,
                        controller: data.ctrl,
                        size: data.size,
                        resolve: {
                            param: function () {
                                return data.param;
                            }
                        }
                    });
              }

              function open_full_modal(data,$modal){

                 var modalInstance = $modal.open({
                        animation: true,
                        templateUrl: 'views/modal/'+data.template,
                        controller: data.ctrl,
                        size: data.size,
                  windowClass: 'app-modal-window',
                        resolve: {
                            param: function () {
                                return data.param;
                            }
                        }
                    });
              }

              function show_alert(type,msg,ngNotify){

                ngNotify.set(msg, {
                  position: 'top',
                  theme: 'pure',
                  type: type
               });

              }

        </script> -->
    </body>
</html><file_sep>/angularjs/scripts/config.routes.js
'use strict';
angular
    .module('app')

    .run(

    ['$rootScope', '$state', '$stateParams', 'AUTH_EVENTS', 'AuthService',
        function ( $rootScope,   $state,   $stateParams ,AUTH_EVENTS, AuthService) {
            $rootScope.$state = $state;
            $rootScope.$stateParams = $stateParams;

                $rootScope.$on('$stateChangeStart', function (event,next, nextParams, fromState) {
                    if ('data' in next && 'authorizedRoles' in next.data) {
                        var authorizedRoles = next.data.authorizedRoles;
                        if (!AuthService.isAuthorized(authorizedRoles)) {
                            $rootScope.$broadcast(AUTH_EVENTS.notAuthorized);
                        }
                    }

                    if (!AuthService.isAuthenticated()) {
                        if (next.name !== 'appSimple.login') {
                            event.preventDefault();
                            $state.go('appSimple.login');
                        }
                    }
                });
            }
        ]
    )

   .config(['$stateProvider', '$urlRouterProvider', '$breadcrumbProvider','MODULE_CONFIG','USER_ROLES', function($stateProvider, $urlRouterProvider, $breadcrumbProvider,MODULE_CONFIG, USER_ROLES) {

        //$urlRouterProvider.otherwise('/dashboard');

        $urlRouterProvider.otherwise(function ($injector, $location) {
            var $state = $injector.get("$state");
            $state.go("app.main");
        });

        $breadcrumbProvider.setOptions({
            prefixStateName: 'app.main',
            includeAbstract: true,
            template: '<li ng-repeat="step in steps" ng-class="{active: $last}" ng-switch="$last || !!step.abstract"><a ng-switch-when="false" href="{{step.ncyBreadcrumbLink}}">{{step.ncyBreadcrumbLabel}}</a><span ng-switch-when="true">{{step.ncyBreadcrumbLabel}}</span></li>'
        });

        $stateProvider
            .state('app', {
                abstract: true,
                templateUrl: 'views/common/layouts/full.html',
                //page title goes here
                ncyBreadcrumb: {
                    label: 'Root',
                    skip: true
                },
                resolve: load([
                    'chart',
                    'controllers/shared.js'
                ])
            })
            .state('app.main', {
                url: '/dashboard',
                templateUrl: 'views/main.html',
                //page title goes here
                ncyBreadcrumb: {
                    label: '{{ "HOME" | translate }}',
                },
                //page subtitle goes here
                params: { subtitle: 'Welcome to ROOT powerfull Bootstrap & AngularJS UI Kit' },
                resolve: load([
                    'controllers/main.js',
                    'assets/libs/moment.min.js',
                    'assets/libs/daterangepicker.min.js', 
                    'assets/libs/angular-daterangepicker.min.js',
                    'assets/libs/gauge.min.js',
                    'assets/libs/angular-toastr.tpls.min.js'
                ])
            })
            .state('app.product_list', {
                url: '/tables',
                templateUrl: 'views/components/tables.html',
                ncyBreadcrumb: {
                    label: '{{ "TABLES" | translate }}'
                },
                controller : "MainCtrl",
                resolve: load([
                    'controllers/Main.js'
                ])
            })
            .state('appSimple', {
                abstract: true,
                templateUrl: 'views/common/layouts/simple.html'
            })
            .state('appSimple.login', {
                url: '/login',
                templateUrl: 'views/pages/login.html',
                controller : "LoginCtrl",
                resolve: load([
                    'controllers/LoginCtrl.js',
                    'assets/libs/angular-toastr.tpls.min.js'
                ])
            })
            

            function load(srcs, callback) {
                return {
                    deps: ['$ocLazyLoad', '$q',
                        function( $ocLazyLoad, $q ){
                            var deferred = $q.defer();
                            var promise  = false;
                            srcs = angular.isArray(srcs) ? srcs : srcs.split(/\s+/);
                            if(!promise){
                                promise = deferred.promise;
                            }
                            angular.forEach(srcs, function(src) {
                                promise = promise.then( function(){
                                    angular.forEach(MODULE_CONFIG, function(module) {
                                        if( module.name == src){
                                            if(!module.module){
                                                name = module.files;
                                            }else{
                                                name = module.name;
                                            }
                                        }else{
                                            name = src;
                                        }
                                    });
                                    return $ocLazyLoad.load(name);
                                });
                            });
                            deferred.resolve();
                            return callback ? promise.then(function(){ return callback(); }) : promise;
                        }
                    ]
                }
            }

    }]);
<file_sep>/application/controllers/ApiController.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class ApiController extends AR_Controller {

	public function __construct(){

		parent::__construct();
		
		$this->load->model("Prefix_model");
		$this->load->model("master_setting_model");
		$this->set_session();

	}

	public function index(){

		$result = $this->result;
		echo json_encode($this->result);

	}
	
	public function get_company($id = 1)
	{
		$result = $this->result;
		$post_data = $this->input_data;
		$result['data'] = $this->App_model->find('company',$id);
		$result['error'] = 0;
		echo json_encode($result);
	}

	public function getsidebar($id){	

		$result = $this->result;
		$page = array();
		$user = $this->App_model->find('user',$id);
		if(isset($user['user_access_id']))
		{
			$page =  $this->access_management->generate_admin_sidemenu_angular($id);
		}

		$result['data'] = $page;
		echo json_encode($result);

	}

	public function getPrefix($id){
	
		$data = getPrefixNo($id);
		
		echo json_encode(array("number"=>$data));
		
	}
	
	public function getUserOnline($user_id){
	
		$data = $this->User_model->all(' AND id != "'.$user_id.'"');
		
		$result = array();
		
		if(count($data) > 0){
		
			foreach($data as $value){
			
				$this->load->model("User_chat_model");
				
				if($value['id'] < $user_id){
		
					$channel = md5($value['id'].$user_id);
				
				}else{
				
					$channel = md5($user_id.$value['id']);
				
				}
				
				$chat = $this->User_chat_model->all(' AND channel = "'.$channel.'" ORDER BY datetime DESC LIMIT 1');
				
				$msg = '';
				
				if(count($chat) > 0){
				
					$msg = $chat[0]['message'];
				}
			
				$result[] = array(
				
					"id" => $value['id'],
					
					"full_name" => $value['full_name'],
					
					"last_chat" => $msg
				
				);
			
			}
		
		}
		
		echo json_encode(array("data"=>$result));
	
	}
	
	public function getUserChat($user_target_id){
		
		$this->load->model("User_chat_model");
		
		$post_data = $this->input_data;
		
		$result = array();
		
		if($user_target_id < $post_data['user_id']){
		
			$channel = md5($user_target_id.$post_data['user_id']);
		
		}else{
		
			$channel = md5($post_data['user_id'].$user_target_id);
		
		}
		
		$data = $this->User_chat_model->all(' AND channel = "'.$channel.'" ');
		
		if(count($data) > 0 && isset($data)){
		
			foreach($data as $value){
				
				$user = $this->User_model->find($value['user_id']);
				
				if($value['user_id'] == $post_data['user_id']){
				
					$position = "right";
				
				}else{
				
					$position = "left";
				}
				
				$result[] = array(
				
					"id"		=> $value['id'],
					
					"message" => $value['message'],
					
					"username" => $user['full_name'],
					
					"position"	=> $position,
					
					"datetime" => get_timeago(strtotime($value['datetime']))
					
				);
			
			}
		
		}
		
		echo json_encode(array("data"=>$result));
	
	}
	
	public function send_message(){
		
		$this->load->model("User_chat_model");
		
		$post_data = $this->input_data;
		
		if($post_data['user_to'] < $post_data['user_id']){
		
			$channel = md5($post_data['user_to'].$post_data['user_id']);
		
		}else{
		
			$channel = md5($post_data['user_id'].$post_data['user_to']);
		
		}
		
		$param = array(
			"message"=>$post_data['message'],
			"user_id"=>$post_data['user_id'],
			"channel"=>$channel,
			"datetime"=>date("Y-m-d H:i:s"),
			"status"=>"unread"
		);
		
		$id = $this->User_chat_model->add($param);
		
		$this->load->library("pusher");
		
		/* Push notification */
		$this->pusher->trigger('chat_channel', 'chat_event', array('message' => 'new message','user_id' => $post_data['user_to'],'user_from'=> $post_data['user_id']));
		
		echo json_encode(array("id"=>$id));
	
	}
	
	public function getUser($id){
	
		$data = $this->User_model->find($id);
		
		echo json_encode(array("data"=>$data));
	
	}
	
	public function language(){
	
		$lang = isset($_GET['lang']) ? $_GET['lang'] : "en_US" ;
		
		switch($lang){
		
			case "en_US":
				$field = "en";
			break;
			case "zh_CN";
				$field = "zh";
			break;
			default : $field = "en";
		
		}
		
		$this->load->model("language_presentation_model");
		
		$data = $this->language_presentation_model->all();
	
		foreach($data as $value){
		
			$res[$value['template']] = $value[$field];
		
		}
		
		echo json_encode(array("load"=>array("page"=>$res)));
	}

	public function master_setting(){
		$data = $this->master_setting_model->find(1);
		echo json_encode(array("data"=>$data));
	}
	public function store_master_setting(){
		$post_data = $this->input_data;
		$result = $this->master_setting_model->update(1,$post_data);
		echo json_encode(array("data"=>$result));
	}
}

<file_sep>/angularjs/scripts/services.api.js
angular.module('app.services', [])

/* Post Data to API */
.factory('API',function($http,$q){
	return{
		get: function(api_url) {
			var returnData = $q.defer();
			$http({
				url: api_url,
				method: 'GET'
			}).success(function(data) {
				returnData.resolve(data);
			}).error(function(error) {
				console.log(error);
				returnData.reject();
			});
			// returns the promise of the API call - whether successful or not
			return returnData.promise;
		},

		post: function(api_url,obj) {
		// tell Angular to wait for iiiiiiiiiiiit....
			var returnData = $q.defer();
			$http({
				url: api_url,
				method: "POST",
				data: obj
			}).success(function(data) {
				returnData.resolve(data);
			}).error(function(error) {
				console.log(error);
				returnData.reject();
			});
			// returns the promise of the API call - whether successful or not
			return returnData.promise;
		}
	}
})

/* Url Config */

.service('PathApiService',function(){

	var report 			= base_url+'index.php/Report';

	var login 			= base_url+'index.php/AuthController';

	var api	 			= base_url+'index.php/ApiController';

	var company 		= base_url+'index.php/company';

	var department 		= base_url+'index.php/department';

	var pos_api	 		= base_url+'index.php/Api';
	var pos_api_2	 		= base_url+'index.php/PosApi';

	

	var customer_group 	= base_url+'index.php/CustomerGroup';

	var customer_list 	= base_url+'index.php/CustomerList';

    var customer_detail 	= base_url+'index.php/CustomerDetails';

	var customer_outlet = base_url+'index.php/CustomerOutlet';

	

	var project_group 	= base_url+'index.php/ProjectGroup';

	var job_sheet 	= base_url+'index.php/JobsheetList';

	var project_meeting = base_url+'index.php/ProjectMeeting';

	var project_quotation = base_url+'index.php/ProjectQuotation';

	var project_invoice = base_url+'index.php/ProjectInvoice';

    var project_list = base_url+'index.php/ProjectList';

	var project_invoice_payment = base_url+'index.php/ProjectInvoicePayment';

	var project_task	= base_url+'index.php/ProjectTask';

	var project_sow		= base_url+'index.php/ProjectSow';

	var job				= base_url+'index.php/Job';

	var project_detail 	= base_url+'index.php/ProjectDetail';

	

	var user          	= base_url+'index.php/User';

	var user_group		= base_url+'index.php/UserGroup';

	var user_scheme 	= base_url+'index.php/UserScheme';

	

	

	var product_group 	= base_url+'index.php/ProductGroup';

	var product_list	= base_url+'index.php/ProductList';

	var product_detail 	= base_url+'index.php/ProductDetail';

	

	

	var payment_terms	= base_url+'index.php/PaymentTerms';

	var language		= base_url+'index.php/Language';

	var payment_method	= base_url+'index.php/PaymentMethod';

    var statement_account 		= base_url+'index.php/StatementAccount';

	

	var vendor_group	= base_url+'index.php/VendorGroup';

	var vendor			= base_url+'index.php/Vendor';

	

	var send_email		= base_url+'index.php/SendEmail';

	

	var purchase_order	= base_url+'index.php/PurchaseOrder';

	var purchase_payment 		= base_url+'index.php/PurchasePayment';

	var Purchase_Multiple_Payment = base_url+'index.php/PurchaseMultiplePayment';

	var purchase_arrival 		= base_url+'index.php/PurchaseArrival';



	var sales_list 			= base_url+'index.php/SalesList';

	var sales_payment 		= base_url+'index.php/SalesPayment';

	var sales_delivery 		= base_url+'index.php/SalesDelivery';

    var delivery_order 		= base_url+'index.php/DeliveryOrder';

    var sales_invoice 		= base_url+'index.php/SalesInvoice';

	

	var expenses_list 	= base_url+'index.php/Expenses';

	var expenses_category 	= base_url+'index.php/ExpensesCategory';

    var expenses_subcategory = base_url+'index.php/ExpensesSubcategory';

	

	var employee 		= base_url+'index.php/employee';

	var prefix	 		= base_url+'index.php/Prefix';

	var system_settings	= base_url+'index.php/systemSettings';

	var transaction_tax	= base_url+'index.php/TransactionTax';

	

	var pos_temp 		= base_url+'index.php/PosTemp';

	var product_favorite = base_url+'index.php/ProductFavorite';
	var report_product_stock = base_url+'index.php/ReportProductStock';
	var report_commission = base_url+'index.php/ReportCommission';

	return {

		report_commission		: function()	{return report_commission;},
		report_product_stock		: function()	{return report_product_stock;},
		report		: function()	{return report;},

		prefix			: function()	{return prefix;},

		login			: function() 	{return login;},

		company			: function() 	{return company;},

		department 		: function() 	{return department;},

		api				: function()	{return api;},

		customer_group 	: function()	{return customer_group;},

		customer_list 	: function()	{return customer_list;},

        customer_detail 	: function()	{return customer_detail;},

		project_group 	: function()	{return project_group;},

		job_sheet 	: function()	{return job_sheet;},

        project_list 	: function()	{return project_list;},

		project_meeting : function()	{return project_meeting;},

		user  			: function()	{return user;},

		user_group  	: function()	{return user_group;},

		user_scheme 	: function()	{return user_scheme;},

		project_quotation : function() 	{return project_quotation;},

		product_group 	: function()	{return product_group;},

		product_list	: function()	{return product_list;},

		project_invoice : function()	{return project_invoice;},

		project_invoice_payment : function() 	{return project_invoice_payment;},

		payment_terms	: function()	{return payment_terms;},

		product_detail	: function()	{return product_detail;},

		project_task	: function()	{return project_task;},

		customer_outlet : function()	{return customer_outlet;},

		language		: function()	{return language;},

		project_sow		: function()	{return project_sow;},

		customer_detail : function()	{return customer_detail;},

        statement_account : function(){return statement_account;},

		payment_method	: function()	{return payment_method;},

		job 			: function()	{return job;},

		vendor			: function()	{return vendor;},

		vendor_group	: function()	{return vendor_group;},

		send_email		: function()	{return send_email;},

		purchase_order	: function()	{return purchase_order;},

		purchase_payment 		: function()	{return purchase_payment;},

		purchase_arrival 		: function()	{return purchase_arrival;},

		project_detail	: function()	{return project_detail;},

		expenses_list	: function()	{return expenses_list;},

		expenses_category: function()	{return expenses_category;},

		expenses_subcategory : function()	{return expenses_subcategory;},

		employee		: function()	{return employee;},

		prefix			: function()	{return prefix;},

		system_settings : function()	{return system_settings;},

		transaction_tax	: function()	{return transaction_tax;},

		sales_list 			: function()	{return sales_list;},

		sales_payment 		: function()	{return sales_payment;},

		sales_delivery 		: function()	{return sales_delivery;},

        delivery_order 		: function()	{return delivery_order;},

        sales_invoice 		: function()	{return sales_invoice;},

		pos_temp		: function()	{return pos_temp;},

		product_fav		: function()	{return product_favorite;},

		pos_api			: function()	{return pos_api;},
		pos_api_2			: function()	{return pos_api_2;}

	};

	

})



/* Auth Config */

.service('AuthService', function($q, $http, USER_ROLES) {
	var LOCAL_TOKEN_KEY = 'JumpHigh1234567890!@#$%^&&*)_';
	var username = '';
	var user_id = '';
	var isAuthenticated = false;
	var role = '';
	var authToken;

	function loadUserCredentials() {

		var token = window.localStorage.getItem(LOCAL_TOKEN_KEY);

		if (token) {

			useCredentials(token);

		}

	}



	function storeUserCredentials(token) {

		window.localStorage.setItem(LOCAL_TOKEN_KEY, token);

		useCredentials(token);

	}



	function useCredentials(token) {

		username = token.split('.')[0];

		isAuthenticated = true;

		authToken = token;

		user_id = token.split('.')[1];



		switch(token.split('.')[2]){

		

			case "1":

				role = USER_ROLES.admin;

			break;

			default : role = "user";

		}

		//role = USER_ROLES.admin



		// Set the token as header for your requests!

		$http.defaults.headers.common['X-Auth-Token'] = token;

	}



	function destroyUserCredentials() {

		authToken = undefined;

		username = '';

		role = '';

		isAuthenticated = false;

		user_id = '';

		$http.defaults.headers.common['X-Auth-Token'] = undefined;

		window.localStorage.removeItem(LOCAL_TOKEN_KEY);

	}



	var login = function(data) {

		return $q(function(resolve, reject) {

			if(data.error == 0){

				// Make a request and receive your auth token from your server

				storeUserCredentials(data.data.full_name+'.'+data.data.id+'.'+data.data.user_access_id);

				resolve('Login success.');

			} else {

				reject('Login Failed.');

			}

		});

	};



	var logout = function() {

		destroyUserCredentials();

	};



	var isAuthorized = function(authorizedRoles) {

		if (!angular.isArray(authorizedRoles)) {

			authorizedRoles = [authorizedRoles];

		}

		return (isAuthenticated && authorizedRoles.indexOf(role) !== -1);

	};



	loadUserCredentials();



	return {

		login			: login,

		logout			: logout,

		isAuthorized	: isAuthorized,

		isAuthenticated	: function() {return isAuthenticated;},

		username		: function() {return username;},

		user_id			: function() {return user_id;},

		role			: function() {return role;}

	};

})



.factory('AuthInterceptor', function ($rootScope, $q, AUTH_EVENTS) {

	return {

		responseError: function (response) {

			$rootScope.$broadcast({

				401: AUTH_EVENTS.notAuthenticated,

				403: AUTH_EVENTS.notAuthorized

			}[response.status], response);

			return $q.reject(response);

		}

	};

})

.config(function ($httpProvider) {

	$httpProvider.interceptors.push('AuthInterceptor');

})

.factory('Func', function() {
    return {
		isUndefined : function(val){
			//return angular.isUndefined(val) || val === null ;
			return !angular.isDefined(val) || val===null;
		},
		isNumber : function(n){
			return !isNaN(parseFloat(n)) && isFinite(n);
		}
	}
});<file_sep>/application/libraries/Access_management.php
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Access_management
{
	private $function_name = '';

	public function generate_admin_sidemenu_angular(){

		$ci =& get_instance(); 
		$user_data = $ci->session->userdata('adminData');
		$result = array();
		$sidemenu = "";
	
		if($user_data['username'] != ''){
			//if($user_data['username'] == 'root'){
			/* root access only */
			$categories = "SELECT a.* FROM t_access_category a LEFT JOIN t_access_item b ON a.id = b.access_category_id WHERE b.route IS NOT NULL GROUP BY a.id ORDER BY a.display_order ASC ";
			$categories = $ci->db->query($categories)->result_array();
			foreach($categories as $category){
				$menus = $ci->App_model->all("t_access_item"," AND access_category_id = ".$category['id']." AND route IS NOT NULL AND display = 1 ORDER BY display_order ASC");	
				$child = array();
				if(count($menus) != 0){
					foreach($menus as $menu){
						$child[] = array(
							"label" => strtoupper($menu['code']),					
							"routes" => $menu['route']
						);
					}
				}
				$result[] = array(            
					"label" => strtoupper($category['code']),
					"routes" => $category['route'],
					"icon"  => $category['icon'],
					"menu_active" => $category['menu_active'],
					"child" => $child			  
				);
			}
		}
		
		return $result;
	}
	/* */
}<file_sep>/angularjs/controllers/main.js
'use strict';

angular.module('app')  
  .controller('MainCtrl', ['$scope', '$translate', '$localStorage', '$location', '$rootScope','USER_ROLES','AuthService','$state','API','PathApiService','AuthService',
    function ( $scope,   $translate,   $localStorage,   $location,   $rootScope , USER_ROLES, AuthService,$state,API,PathApiService ) {
 
       $scope.logout = function() {
		  API.post(PathApiService.login()+'/logout/',{user_id:AuthService.user_id()}).then(function(result){});
        AuthService.logout();
        $state.go('appSimple.login');
      };
      
    
	
  }]);
    <file_sep>/application/models/App_model.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class App_model extends CI_Model {
	protected $input_data;
	protected $temporary_data;
	protected $data;
	protected $controller_name;
	protected $module_name;
	protected $function_name;
	protected $result;
    protected $table;
    protected $_user_id;
    protected $_username;


    public function __construct(){
        parent::__construct();
//        $this->load->database();
		
		 $this->_user_id = $this->session->userdata("user_id");
 
        $userData = $this->session->userdata("adminData");
        if(isset($userData['id'])){
            $this->_user_id = $userData['id'];
            $this->_username = $userData['username'];
        }else{
            $this->_user_id = 0;
            $this->_username = 'Guest';
        }
       
    }
	
	function count_filtered($table,$column,$order)
	{
		$this->_get_datatables_query($table,$column,$order);
		$this->db->where("deleted_at IS NULL");

		$query = $this->db->get();
		return $query->num_rows();
	}

	public function count_all($table)
	{
		$this->db->where("deleted_at IS NULL");

		$this->db->from($table);
		return $this->db->count_all_results();
	}

	public function get_by_id($table,$id)
	{
		$this->db->from($table);
		$this->db->where('id',$id);
		$query = $this->db->get();

		return $query->row();
	}

	private function getInsertId(){
            return $this->db->insert_id();
    }
	private function insert($table,$data,$log = 1){    
        foreach($data as $key=>$val){
            if ($this->db->field_exists($key, $table)){
                $insert[$key] = $val;
            }   
        }
        $insert["created_at"] = date("Y-m-d H:i:s");
		$insert['created_by'] = $this->_user_id;
        $this->db->insert($table, $insert); 
        $insert_id = $this->db->insert_id();
        $query = $this->db->last_query();
        return $insert_id;
    }

	private function query($query){
        return $this->db->query($query);
    }
    private function executeQuery($query){
        $res =  $this->db->query($query);
        return $res;
    }
   	

   	private function readAllRows($table, $additional_criteria = "",$data_status = ""){
        $data = array();

        if($data_status == "")
        {   
            $where = " WHERE deleted_at IS NULL";
        }
        else if($data_status == "only_trash"){
            $where = " WHERE deleted_at IS NOT NULL";
        }
        else if($data_status == "with_trash"){
            $where = " WHERE 1";
        }
        
        $where .= $additional_criteria != "" ? $additional_criteria : "";
        $query = "SELECT * FROM " . $table . $where;
        
        $rows = $this->executeQuery($query);
        
        foreach ($rows->result_array() as $row) {
            foreach($row as $key=>$val){
                    $row[$key] = $val;
            }
            $data[] = $row;
        }
        
        return $data;
    }
    private function readRowInfo($table, $id, $by = "", $additional_criteria = ""){
        $data = array();
        if ($by == "") $by = "id";
        $where = ($id != "") ? " WHERE $by = '$id'" : "";
        $where .= $additional_criteria != "" ? $additional_criteria : "";
        $query = "SELECT * FROM " . $table . $where;
                $rows = $this->executeQuery($query);
                foreach ($rows->result_array() as $row) {
                        $data = $row;
                }
                return $data;
    }
    private function updateRow($data,$table,$id,$by,$log = 1){
        foreach($data as $key=>$val){
            if ($this->db->field_exists($key, $table)){
                $update[$key] = $val;
            }
        }
        $update["updated_at"] = date("Y-m-d H:i:s");
		$update['updated_by'] = $this->_user_id;
        $this->db->where($by,$id);
        $this->db->update($table, $update); 
        $query = $this->db->last_query();
        if($log == 1){
            $this->log($table,$data,$id,"update",$query);
        }

    }

    private function countRows($table, $additional_criteria = "",$data_status = ""){
        if($data_status == "")
        {   
            $where = " WHERE deleted_at IS NULL";
        }
        else if($data_status == "only_trash"){
            $where = " WHERE deleted_at IS NOT NULL";
        }
        else if($data_status == "with_trash"){
            $where = " WHERE 1";
        }
        $where .= $additional_criteria != "" ? $additional_criteria : "";
        $query = "SELECT COUNT(*) as cnt FROM " . $table . $where;
        $rows = $this->executeQuery($query);
   
        foreach ($rows->result_array() as $row)
        {
            $count = isset($row['cnt']) ? $row['cnt'] : "";
        }
    
        return $count;
    }
    private function DeleteRow($table,$id,$by,$log = 1){

        $data["deleted_at"] = date("Y-m-d H:i:s");
        $data['deleted_by'] = $this->_user_id;
        $this->db->where($by,$id);
        $this->db->update($table, $data);

        $query = $this->db->last_query();
        $data = $this->readRowInfo($table,$id);
        if($log == 1){
            $this->log($table,$data,$id,"deactive",$query);
        }
    }
    private function restoreRow($table,$id,$by,$log = 1){
        $data["deleted_at"] = NULL;
        $data['deleted_by'] = $this->_user_id;
        $this->db->where($by,$id);
        $this->db->update($table, $data);
        $query = $this->db->last_query();
        $data = $this->readRowInfo($table,$id);
        if($log == 1){
            $this->log($table,$data,$id,"restore",$query);
        }
    }
    private function realDeleteRow($table,$id,$data = NULL,$log = 1){
        $this->db->where('id', $id);
        $data = $this->readRowInfo($table,$id);
        $this->db->delete($table);
        $query = $this->db->last_query();
        
        if($log == 1){
            $this->log($table,$data,$id,"restore",$query);
        }

    }
    private function log($table,$data,$id,$action,$query){
        $month = date("m-Y");
        $ip = $this->input->ip_address();
        
        $userData = $this->session->userdata("adminData");
        if(isset($userData['id'])){
            $user_id = $userData['id'];
            $user_name = $userData['username'];
        }else{
            $user_id = 0;
            $user_name = "guest";
        }

        $insert['ip'] = $ip;
        $insert['user_id'] = $userData['id'];
        $insert['user_name'] = $user_name;
        $insert['affected_table'] = $table;
        $insert['affected_id'] = $id;
        $insert['query'] = $query;
        $insert['action'] = $action;
        $insert['data'] = json_encode($data);
        $insert['wording_log'] = $user_name." ".$action." ".$table;
        $insert["created_at"] = date("Y-m-d H:i:s");
        //$this->db->insert("log", $insert); 
        $txt = implode(" ",$insert);
        $myfile = file_put_contents('logs/'.$month.'.txt', $txt.PHP_EOL , FILE_APPEND);
    }
    
    public function add($table,$data)
    {
        return $this->insert($table,$data);
    }

	public function all($table,$custom_where="",$data_status=""){
        $rows = $this->readAllRows($table,$custom_where,$data_status);
        return $rows;
    }

    public function find($table,$id,$by='id',$custom_where="") 
    {
        $rows = $this->readRowInfo($table, $id,$by,$custom_where);
        return $rows;
    }
	
    public function count($table,$custom_where="")
    {
        $num = $this->countRows($table, $custom_where);
        return $num;
    }
    public function update($table,$table_id,$id,$data,$by = null)
    {
        if($by == null){
            $by = $table_id;
        }
        $this->updateRow($data, $table,$id,$by);
    }
    public function delete($table,$table_id,$id,$by = null){
        if($by==null)
        {
            $by = $this->table_id;
        }
        $this->deleteRow($table,$id,$by);
    }
    public function realDelete($table,$table_id,$id){
        $this->realDeleteRow($table,$id,$table_id);
    }
    public function soft_delete($table,$table_id,$id){
        $this->deleteRow($table,$id,$table_id);
    }
    public function restore($id){
        $this->restoreRow($table,$id,$this->table_id);
    }

	public function check_Mypassword($psw)
	{
		$match = FALSE;
		$user_id = $this->session->userdata("user_id");
		$user = $this->app_model->find('user',$user_id);
		$pass =md5(strtolower($psw));
		if ($user['password'] == $pass )
		{
			$match = TRUE;
		}
		return $match;
	}
	
	public function changeMypassword($new_password,$user_id)
	{
		$this->db->query('update user set password ="'. $new_password .'" where id = '.$user_id);
	}
	//Konversi tanggal
	public function tgl_sql($date){
		$exp = explode('-',$date);
		if(count($exp) == 3) {
			$date = $exp[2].'-'.$exp[1].'-'.$exp[0];
		}
		return $date;
	}
	public function tgl_str($date){
		$exp = explode('-',$date);
		if(count($exp) == 3) {
			$date = $exp[2].'-'.$exp[1].'-'.$exp[0];
		}
		return $date;
	}
	
	public function tgl_jam_sql($date){
		$exp =explode(' ',$date);
		$tgl = $exp[0];
		$jam = $exp[1];	 
		$exp = explode('-',$tgl);
		if(count($exp) == 3) {
			$date = $exp[2].'-'.$exp[1].'-'.$exp[0];
		}
		return $date.' '.$jam;
	}
	
	public function tgl_jam_str($date){
		$exp =explode(' ',$date);
		$tgl = $exp[0];
		$jam = $exp[1];	 
		$exp = explode('-',$tgl);
		if(count($exp) == 3) {
			$date = $exp[2].'-'.$exp[1].'-'.$exp[0];
		}
		return $date.' '.$jam;
	}
	
	/* Tanggal dan Jam */
	public function Jam_Now(){
		date_default_timezone_set("Asia/Jakarta");
   		$jam = date("H:i:s"); 
   		
		return $jam;
		//echo "$jam WIB";
	}
	
	public function Hari_Bulan_Indo(){
		date_default_timezone_set('Asia/Jakarta'); // PHP 6 mengharuskan penyebutan timezone.
		$seminggu = array("Minggu","Senin","Selasa","Rabu","Kamis","Jum\'at","Sabtu");
		$hari = date("w");
		$hari_ini = $seminggu[$hari];
		
		return $hari_ini;
	}
	
	public function tgl_indo($tanggal){
			date_default_timezone_set('Asia/Jakarta'); // PHP 6 mengharuskan penyebutan timezone.
			$tgl = $tanggal; //date("Y m d");
			$tanggal = substr($tgl,8,2);
			$bulan = $this->app_model->getBulan(substr($tgl,5,2));
			$tahun = substr($tgl,0,4);
			return $tanggal.' '.$bulan.' '.$tahun;		 
	}
	
	public function tgl_now_indo(){
			date_default_timezone_set('Asia/Jakarta'); // PHP 6 mengharuskan penyebutan timezone.
			$tgl = date("Y m d");
			$tanggal = substr($tgl,8,2);
			$bulan = $this->app_model->getBulan(substr($tgl,5,2));
			$tahun = substr($tgl,0,4);
			return $tanggal.' '.$bulan.' '.$tahun;		 
	}	

	public function getBulan($bln){
		switch ($bln){
			case 1: 
				return "Januari";
				break;
			case 2:
				return "Februari";
				break;
			case 3:
				return "Maret";
				break;
			case 4:
				return "April";
				break;
			case 5:
				return "Mei";
				break;
			case 6:
				return "Juni";
				break;
			case 7:
				return "Juli";
				break;
			case 8:
				return "Agustus";
				break;
			case 9:
				return "September";
				break;
			case 10:
				return "Oktober";
				break;
			case 11:
				return "November";
				break;
			case 12:
				return "Desember";
				break;
		}
	} 
	
	/*fungsi terbilang*/
	public function bilang($x) {
		$x = abs($x);
		$angka = array("", "satu", "dua", "tiga", "empat", "lima",
		"enam", "tujuh", "delapan", "sembilan", "sepuluh", "sebelas");
		$result = "";
		if ($x <12) {
			$result = " ". $angka[$x];
		} else if ($x <20) {
			$result = $this->app_model->bilang($x - 10). " belas";
		} else if ($x <100) {
			$result = $this->app_model->bilang($x/10)." puluh". $this->app_model->bilang($x % 10);
		} else if ($x <200) {
			$result = " seratus" . $this->app_model->bilang($x - 100);
		} else if ($x <1000) {
			$result = $this->app_model->bilang($x/100) . " ratus" . $this->app_model->bilang($x % 100);
		} else if ($x <2000) {
			$result = " seribu" . $this->app_model->bilang($x - 1000);
		} else if ($x <1000000) {
			$result = $this->app_model->bilang($x/1000) . " ribu" . $this->app_model->bilang($x % 1000);
		} else if ($x <1000000000) {
			$result = $this->app_model->bilang($x/1000000) . " juta" . $this->app_model->bilang($x % 1000000);
		} else if ($x <1000000000000) {
			$result = $this->app_model->bilang($x/1000000000) . " milyar" . $this->app_model->bilang(fmod($x,1000000000));
		} else if ($x <1000000000000000) {
			$result = $this->app_model->bilang($x/1000000000000) . " trilyun" . $this->app_model->bilang(fmod($x,1000000000000));
		}      
			return $result;
	}
	public function terbilang($x, $style=4) {
		if($x<0) {
			$hasil = "minus ". trim($this->app_model->bilang($x));
		} else {
			$hasil = trim($this->app_model->bilang($x));
		}      
		switch ($style) {
			case 1:
				$hasil = strtoupper($hasil);
				break;
			case 2:
				$hasil = strtolower($hasil);
				break;
			case 3:
				$hasil = ucwords($hasil);
				break;
			default:
				$hasil = ucfirst($hasil);
				break;
		}      
		return $hasil;
	}
}
	
/* End of file app_model.php */
/* Location: ./application/models/app_model.php */<file_sep>/application/core/AR_Controller.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class AR_Controller extends CI_Controller {
	protected $input_data;
	protected $temporary_data;
	protected $data;
	protected $controller_name;
	protected $module_name;
	protected $function_name;
	protected $result;

	public function __construct(){
		
		parent::__construct();
		
		if($_POST){
		
			$this->input_data = $this->input->post();
			
		}	
		else if($_GET){
		
			$this->input_data = $this->input->get();
			
		} else {
		
			$this->load->model("user_model");
		
			$this->input_data = json_decode(file_get_contents("php://input"), true);

		}
		
		$this->result['error'] 	= 1;

		$this->result['msg']	= "Woopps...";

		$this->result['data']	= null;

		
	}
	
	public function set_session(){
		
		$post_data = $this->input_data;
		
		if(isset($post_data['user_id'])){
		
			$user_id = $post_data['user_id'];

			$userData = $this->user_model->find($user_id);

			$this->session->set_userdata("adminData",$userData);
			
		}
	
	}

	
}

/* End of file AR_Controller.php */
/* Location: ./application/core/AR_Controller.php */<file_sep>/application/models/User_access_group_model.php
<?php
class User_Access_Group_Model extends AR_Model {

    public function __construct(){
        parent::__construct();
        $this->allow_insert = "code,description";
        $this->allow_update = "code,description";
        $this->tblName = "user_group";
        $this->tblId = "id";
    }
    public function all_detail($id){
    	$group = $this->find($id);
    	$this->load->model("user_access_model");
    	$group['items'] = $this->user_access_model->all(" AND user_access_group_id = $id");
    	return $group;
    }
    public function get_allowed_access($id){
        $data = array();
        $group = $this->find($id);
        $this->load->model("user_access_model");
        $items =  $this->user_access_model->all(" AND user_access_group_id = $id AND access_type != 'none'");
        foreach($items as $item){
            $data[] = $item['access_item_id'];
        }
        return $data;
    }
}<file_sep>/application/models/Access_item_group_model.php
<?php
/**
 * User: gamalan
 * Date: 3/17/2015
 * Time: 10:06 AM
 */

class access_item_group_model extends AR_Model {

    public function __construct(){
        parent::__construct();

        $this->tblName = "t_access_category";
        $this->tblId = "id";
    }
    public function all_details(){
    	$datas = array();
    	$groups = $this->all();
    	$this->load->model("access_item_model");
    	foreach($groups as $group){
    		$items = $this->access_item_model->all(" AND access_category_id = ".$group['id'] );
    		$group['items'] = $items;
    		$datas[] = $group;
    		
    	}
    	return $datas;
    }
}