<?php
class CT_app_uman extends CI_Controller{
    function __construct()
    {
        parent::__construct();
		if (!$this->dx_auth->is_logged_in()) {
            redirect('');  
            die(); 
        }
        
        $uid = $this->session->userdata('DX_user_id');
        
        if(!permissionAuth(2) && $uid != RID){ 
            header('HTTP/1.1 401 Unauthorize');die('noaccess');
        } 
            
        $this->load->model("MDL_main", 'mdlMain');
        $this->load->helper('form');
        $this->load->library('form_validation');
        
        
        $uid = $this->session->userdata('DX_user_id');
        
 
         
        
    }

    function index(){
        $data = array();
        $this->load->view('settings/view_app_user_management', $data);
    }
    
    function loadUserData(){
        
        $page = isset($_POST['page'])?$_POST['page']:1; // get the requested page
        $limit = isset($_POST['rows'])?$_POST['rows']:10; // get how many rows we want to have into the grid
        $sidx = isset($_POST['sidx'])?$_POST['sidx']:'id'; // get index row - i.e. user click to sort
        $sord = isset($_POST['sord'])?$_POST['sord']:''; // get the direction
       
        $start = $limit*$page - $limit;

        if ($start<0) $start=0;
        
        
        $records = $this->mdlMain->getAllUsers($limit,$start,$sidx,$sord);
        $count = $this->mdlMain->getAllUsersCount();
        if( $count > 0 ) { $total_pages = ceil($count/$limit); } else { $total_pages = 0; } 
        if ($page > $total_pages) $page=$total_pages;
        
        $response->page = $page;
		$response->total = $total_pages;
		$response->records =  $count;
        $i=0;
        foreach($records as $r){
            $details = $this->mdlMain->getUserProfile($r->id);
            
            $response->rows[$i]['id']=$r->id; 
            $response->rows[$i]['role_id'] = $this->mdlMain->idToRoles($r->role_id); 
            $response->rows[$i]['role_code'] = $r->role_id; 
            $response->rows[$i]['uname']=$r->username; 
            $response->rows[$i]['email']=$r->email; 
            $response->rows[$i]['last_login']=$r->last_login; 
            $response->rows[$i]['name']= @$details[0]->name; 
            $response->rows[$i]['phone']= @$details[0]->phone; 
            $response->rows[$i]['branch']= @$details[0]->branchID; 
            $response->rows[$i]['division_code']= @$details[0]->divisionID; 
            $response->rows[$i]['division']= @$this->mdlMain->idToDivision($details[0]->divisionID); 
            $response->rows[$i]['blocked']=$r->banned; 
            $i++;
        }
        echo json_encode($response);
        
    }
    
    function loadUserLevelData(){
        $page = isset($_POST['page'])?$_POST['page']:1; 
        $limit = isset($_POST['rows'])?$_POST['rows']:10; 
        $sidx = isset($_POST['sidx'])?$_POST['sidx']:'id'; 
        $sord = isset($_POST['sord'])?$_POST['sord']:''; 
        $start = $limit*$page - $limit;

        if ($start<0) $start=0;
        
        
        $records = $this->mdlMain->getUsersLevel($limit,$start,$sidx,$sord);
        $count = $this->mdlMain->getUsersLevelCount();
        if( $count > 0 ) { $total_pages = ceil($count/$limit); } else { $total_pages = 0; } 
        if ($page > $total_pages) $page=$total_pages;
        
        $response->page = $page;
		$response->total = $total_pages;
		$response->records =  $count;
        $i=0;
        foreach($records as $r){
            
            $response->rows[$i]['id']=$r->id; 
            $response->rows[$i]['parent_id']=$r->parent_id; 
            $response->rows[$i]['name']=$r->name; 
 
            $i++;
        }
        echo json_encode($response);
    }
    
    function loadUserDivisionData(){
        $page = isset($_POST['page'])?$_POST['page']:1; 
        $limit = isset($_POST['rows'])?$_POST['rows']:10; 
        $sidx = isset($_POST['sidx'])?$_POST['sidx']:'id_div'; 
        $sord = isset($_POST['sord'])?$_POST['sord']:''; 
        $start = $limit*$page - $limit;

        if ($start<0) $start=0;
        
        
        $records = $this->mdlMain->getUsersDivision($limit,$start,$sidx,$sord);
        $count = $this->mdlMain->getUsersDivisionCount();
        if( $count > 0 ) { $total_pages = ceil($count/$limit); } else { $total_pages = 0; } 
        if ($page > $total_pages) $page=$total_pages;
        
        $response->page = $page;
		$response->total = $total_pages;
		$response->records =  $count;
        $i=0;
        foreach($records as $r){
            
            $response->rows[$i]['id']=$r->id_div; 
            $response->rows[$i]['desc']=$r->div_name; 
 
            $i++;
        }
        echo json_encode($response);
    }
    
    
    function generateTreeModule(){
        $level_id =  $this->input->post('level_id');
        
        echo <<<EOM
        <script type="text/javascript">

            $(document).ready(function(){
                $( "#user-menu-data-container" ).hide();
                $( "#btnappmenuusersave" ).button();       
                $( "#btnappmenuuserreset" ).button();  
                
                $("#app_manage_menu_user").dynatree({
                  debugLevel:0,  
                  checkbox: true,
                  persist: true,
                  selectMode: 2,
                  imagePath: baseUrl + 'assets/images/icons/16x16/',
                  initAjax: {        	       
            					url: baseUrl + "settings/ct_app_uman/getAllMenu"
                    	    },
                  onSelect: function(select, node) {
                    // Display list of selected nodes
                    var selNodes = node.tree.getSelectedNodes();
                    // convert to title/key array
                    var selKeys = $.map(selNodes, function(node){
                         return node.data.key;
                    });
                    $("#user-menu-data-container").text(selKeys.join(","));
                  },
                  onClick: function(node, event) {
                    // We should not toggle, if target was "checkbox", because this
                    // would result in double-toggle (i.e. no toggle)
                    if( node.getEventTargetType(event) == "title" )
                      node.toggleSelect();
                  },
                  onKeydown: function(node, event) {
                    if( event.which == 32 ) {
                      node.toggleSelect();
                      return false;
                    }
                  },
                  // The following options are only required, if we have more than one tree on one page:
                  cookieId: "userManagement-ccs-tree",
                  idPrefix: "uman-ccs-tree"
                });
            });
        </script>
        <div>
        <br />
        <p>
        <a href="#" id="btnSelectAll">Select all</a> -
        <a href="#" id="btnDeselectAll">Deselect all</a> -
        <a href="#" id="btnToggleSelect">Toggle select</a> - 
        <a href="#" id="btnExpandAll">Expand all</a> -
        <a href="#" id="btnCollapseAll">Collapse all</a> -
        <a href="#" id="btnToggleExpand">Toggle expand</a>
        </p>
        
        </div>
        <hr />
        <div id="app_manage_menu_user" style="height:325px;overflow:auto;"></div>
        <textarea id="user-menu-data-container"></textarea>
        
EOM;
    }
    
   
    function generateMenuTypeGrid(){
             $level_id =  $this->input->post('level_id');
            header('Content-Type: application/json');
			 $treeData='';
		     $typemenus = $this->mdlMain->getAllMenuType2($level_id); 
			    foreach($typemenus['data'] as $r){ 
				$treeData=$r->treedata; 
				break;
				} 
		  echo <<<EOM
        <script type="text/javascript">
	     var treeData = $treeData ; 
 $("#tree3").dynatree({
      checkbox: true,
      selectMode: 3,
      children: treeData,
	  imagePath: baseUrl+'assets/images/icons/16x16/',
      onSelect: function(select, node) {
        // Get a list of all selected nodes, and convert to a key array:
			var selKeys = $.map(node.tree.getSelectedNodes(), function(node){
          return node.data.key;
        });
        $("#echoSelection3").text(selKeys.join(", "));

        // Get a list of all selected TOP nodes
        var selRootNodes = node.tree.getSelectedNodes(true);
        // ... and convert to a key array:
        var selRootKeys = $.map(selRootNodes, function(node){
          return node.data.key;
        });
        $("#echoSelectionRootKeys3").text(selRootKeys.join(", "));
        $("#echoSelectionRoots3").text(selRootNodes.join(", "));
      },
      onDblClick: function(node, event) {
        node.toggleSelect();
      },
      onKeydown: function(node, event) {
        if( event.which == 32 ) {
          node.toggleSelect();
          return false;
        }
      },
      // The following options are only required, if we have more than one tree on one page:
//        initId: "treeData",
      cookieId: "dynatree-Cb3",
      idPrefix: "dynatree-Cb3-"
    }); 
		
        </script> 
        
     	<div id="tree3"></div>
	  <input type="hidden" id="userman_manage_menu" name="userman_manage_menu" value="$level_id"/>
EOM;
        

    }
    
    function generateMenuTypeGrid2(){
         $level_id =  $this->input->post('level_id');
         $this->load->model('dx_auth/permissions', 'permissions');
        
        $level_id =  $this->input->post('level_id');
        $selected_data = $this->permissions->get_permission($level_id)->result();
        $js_select = "";
        
        if(count($selected_data) > 0){
            $selected_arr = explode(",",$selected_data[0]->perm_menutype);
        
            foreach($selected_arr as $select){
                $js_select = $js_select . "case '".$select."':                                   jQuery('#appusermenutypegridlist').jqGrid('setSelection',rowData[i].id); break;";
            }
        }
        
        //print_r();die();
        
        
        echo <<<EOM
        <script type="text/javascript">
	
		jQuery("#appusermenutypegridlist").jqGrid({
                    url:baseUrl + 'settings/ct_app_menu_man/loadMenuTypeData',     
                    mtype : "post",
        			postData:{'q':'1'},
        			datatype: "json",
        			colNames:['ID', 'USE', 'ALIAS', 'TITLE','DESCRIPTION','PUBLISHED','FP DESC.','ORDER'],
        			colModel:[
        				{name:'id',index:'id', width:30, hidden:true},
						{name: 'active', index: 'active', width: 45, align: 'center',   formatter: function (cellvalue) {
    return "<input type='checkbox' class='itmchk' ><strong>" +
        $.jgrid.htmlEncode(cellvalue) + "</strong>";
}
},				{name:'menutype',index:'menutype', width:20},
        				{name:'menutitle',index:'menutitle', width:25},
        				{name:'menudesc',index:'menudesc', width:25,hidden:true},
        				{name:'menupublished',index:'menupublished', width:20, align:'center'},
        				{name:'menufp',index:'menufp', width:50,hidden:true},
        				{name:'menuorder',index:'menuorder', width:20, align:'center',hidden:true}
        			],
                    rowNum:20,
                    width: 600,
                    height: 200,
                    rowList:[10,20,30],
        			jsonReader: { repeatitems : false },
                    pager: '#pappusermenutypegridlist',
                    sortname: 'id',
                    viewrecords: true,
                    rownumbers: true,
                   // gridview: true,
					treeGrid: true,
					treeGridModel: "adjacency",
					multiselect: true,
                    gridComplete: function(){
        				var rowIDs = jQuery("#appusermenutypegridlist").getDataIDs(); 
        				var rowData = $("#appusermenutypegridlist").getRowData();
                        
        				for (var i = 0; i < rowData.length; i++) 
        				{
        				   var trElement = jQuery("#"+ rowIDs[i],jQuery('#appusermenutypegridlist'));
        					switch (rowData[i].id) {
        						$js_select
        					}
        				}
        
                    },
					beforeSelectRow: function (rowid, e) {
						var  isLeafName = $(this).jqGrid("getGridParam", "treeReader").leaf_field,
						localIdName = $(this).jqGrid("getGridParam", "localReader").id,
						localData,
						state,
						setChechedStateOfChildrenItems = function (children) {
							$.each(children, function () {
								$("#" + this[localIdName] + " input.itmchk").prop("checked", state);
								if (!this[isLeafName]) {
									setChechedStateOfChildrenItems($(this).jqGrid("getNodeChildren", this));
								}
							});
						};
					if (e.target.nodeName === "INPUT" && $(e.target).hasClass("itmchk")) {
						state = $(e.target).prop("checked");
						localData = $(this).jqGrid("getLocalRow", rowid);
						setChechedStateOfChildrenItems($(this).jqGrid("getNodeChildren", localData), state);
					}
}
        		}).navGrid('#paappusermenutypegridlist',{edit:false,add:false,del:false,view:true,search:false});
                //
        </script>
        
        <table id="appusermenutypegridlist"></table> <!--Grid table-->
        <div id="pappusermenutypegridlist"></div>  <!--pagination div-->
        <input type="hidden" id="userman_manage_menu" name="userman_manage_menu" value="$level_id"/>
EOM;
        

    }
    
    function generateForm(){
        
        
        if($this->input->post('view') ==  'edit'){
            $username = $this->input->post('username');
            $name= $this->input->post('name');
            $uid= $this->input->post('uid');
            $email= $this->input->post('email');
            $division_id= $this->input->post('division');
            $role_id= $this->input->post('role_id');
            $phone= $this->input->post('phone');
            $branch_id= $this->input->post('branch');
            
            $url = "updateappuser";
            $readonly = "readonly=readonly";
            $required = "false";
        } else {
            $username = "";
            $name= "";
            $uid= "";
            $email= "";
            $division_id= "";
            $role_id= "";
            $phone= "";
            $branch_id= "";
            
            $url = "saveappuser";
            $readonly = "";
            $required = "true";
        }
        
        $roles = $this->mdlMain->getRoles();
        $options_roles[ "" ] = "--";
        foreach ($roles as $row)
        {
            $options_roles[ $row->id ] = $row->name;
        }
        
        
        $js_roles = 'id="level"';
        $combo_roles = form_dropdown('level', $options_roles, $role_id,$js_roles);
        
        $division = $this->mdlMain->getDivision();
        $options_division[ "" ] = "--";
        foreach ($division as $row)
        {
            $options_division[ $row->id_div ] = $row->div_name;
        }
        
        
        $js_division = 'id="division"';
        $combo_division = form_dropdown('division', $options_division, $division_id,$js_division);
        
        $branch = $this->mdlMain->getBranch();
        $options_branch[ "" ] = "--";
        foreach ($branch as $row)
        {
            $options_branch[ $row->id_br ] = $row->br_name;
        }

        $js_branch = 'id="branch"';
        $combo_branch = form_dropdown('branch', $options_branch, $branch_id,$js_branch);
        
        

        //echo $roles_combo;
 echo <<<EOF
        <form method="post" name="frmuserman" id="frmuserman" action="">
                <input type="hidden" id="uid" name="uid" value="$uid" />
				<div class="ff"><label class="frm-lbl">Username </label><span><input type="text" id="username" name="username" style="width: 128px;" class="r-25" value="$username" $readonly /></div>
				<div class="ff"><label class="frm-lbl">Name </label><span><input type="text" id="name" name="name" style="width: 128px;" class="r-25"  value="$name"/></div>
				<div class="ff"><label class="frm-lbl">Password </label><span><input type="password" id="password" name="password" style="width: 128px;" class="r-25" /></div>
				<div class="ff"><label class="frm-lbl">Confirm Password </label><span><input type="password" id="conf_password" name="conf_password" style="width: 128px;" class="r-25" /></div>
				<div class="ff"><label class="frm-lbl">Phone </label><span><input type="text" id="phone" name="phone" style="width: 128px;" class="r-25" value="$phone" /></div>
                <div class="ff"><label class="frm-lbl">e-mail </label><span><input type="text" id="email" name="email" style="width: 128px;" class="r-25" value="$email" $readonly /></div>
                <div class="ff"><label class="frm-lbl">Level </label><span>$combo_roles</span></div>
                <div class="ff"><label class="frm-lbl">Division </label><span>$combo_division</span></div>
                <div class="ff"><label class="frm-lbl">Branch </label><span>$combo_branch</span></div>
                  <fieldset id="error-container" style="display:none;position:absolute; right:5px;top:35px;width:200px;background:#FFFF99;">
                  <legend>Warning</legend>
                    
                  </fieldset>
                
				<br/>

        </form>
        <script type="text/javascript">

            $(document).ready(function(){
                 $("#frmuserman").validate({
        
                    errorElement:"div",
        
        
                    //set the rules for the fild names
                    rules:{
        
                        username:{
                            required:true,
                            minlength:3,
                            maxlength:25
                        },
                        name:{
                            required:true,
                            minlength:3,
                            maxlength:25
                        },
                        email:{
                            required:true,
                            minlength:3,
                            maxlength:50,
                            email:true
                        },
                        phone:{
                            required:true,
                            minlength:6,
                            maxlength:25,
                            number:true
                        },
                        password:{
                            required:$required,
                            minlength:5,
                            maxlength:15
                        },
                        conf_password:{
                            required:$required,
                            minlength:5,
                            maxlength:15,
                            equalTo:"#password"
                        },
                        level:{
                            required:true
                        },
                        division:{
                            required:true
                        },
                        branch:{
                            required:true
                        }
        
        
                    },
                    //set messages to appear inline
                    messages:{
        
                        username:{
                            required:"Username is required.",
                            minlength:"Your name must be at least 5 characters long",
                            maxlength:"name can not be more than 25 characters"
                        },
                        
                        name:{
                            required:"Name is required.",
                            minlength:"Your name must be at least 5 characters long",
                            maxlength:"name can not be more than 25 characters"
                        },
        
                        password:{
                            required:"Please provide a password.",
                            minlength:"Your password must be at least 5 characters long",
                            maxlength:"Password can not be more than 15 characters"
                        },
        
                        conf_password:{
                            required:"Please provide a Confirmation Password.",
                            minlength:"Your password must be at least 5 characters long",
                            maxlength:"Password can not be more than 15 characters"
                        },
        
                        email:{
                            email:"Valid email is required.",
                            minlength:"Your email must be at least 3 characters long",
                            maxlength:"email can not be more than 50 characters"
                        },
                        phone:{
                            required:"Phone is required.",
                            minlength:"Your password must be at least 6 characters long",
                            maxlength:"Password can not be more than 15 characters",
                            number:"Only number allowed"
                        },
                        level:"Level is required",
                        division:"Division is required",
                        branch:"Branch is required"
                    },
        
                    errorPlacement:function (error, element) {                       
                        error.appendTo(element.parent());
                    },
                    //errorLabelContainer: $("#error-container"),
                    submitHandler:function () {
                        var postData = $("#frmuserman").serialize();
                        $.ajax({	
            				url : baseUrl + "settings/ct_app_uman/$url",
            				type : 'POST',
            				data : postData,
            				dataType: 'json',
            				success: function(res){
            				     if(res.error == 1){
            				        
                                    if(res.data.other){
                                        alert(res.data.other);
                                        return false;   
                                    }
                                    
                                    var msg = '';
                                    if (res.data.name) {
                                        $("#name").removeClass('valid');
                                        $("#name").addClass('error');
                                        msg += ' - ' + res.data.name + '\\n';
                                    }
                                    if(res.data.username){
                                        $("#username").removeClass('valid');
                                        $("#username").addClass('error');
                                        msg += ' - ' + res.data.username + '\\n';
                                    }
                                    if (res.data.password) {
                                        $("#password").removeClass('valid');
                                        $("#password").addClass('error');
                                        msg += ' - ' + res.data.password + '\\n';
                                    }
                                    
                                    if (res.data.conf_password) {
                                        $("#conf_password").removeClass('valid');
                                        $("#conf_password").addClass('error');
                                        msg += ' - ' + res.data.conf_password + '\\n';
                                    }
                                    if (res.data.phone) {
                                        $("#phone").removeClass('valid');
                                        $("#phone").addClass('error');
                                        msg += ' - ' + res.data.phone + '\\n';
                                    }
                                    if (res.data.email) {
                                        $("#email").removeClass('valid');
                                        $("#email").addClass('error');
                                        msg += ' - ' + res.data.email + '\\n';
                                    }
              
                                    if (res.data.level) {
                                        $("#level").removeClass('valid');
                                        $("#level").addClass('error');
                                        msg += ' - ' + res.data.level + '\\n';
                                    }
                                    
                                    if (res.data.division) {
                                        $("#division").removeClass('valid');
                                        $("#division").addClass('error');
                                        msg += ' - ' + res.data.division + '\\n';
                                    }
                                    
                                    if (res.data.branch) {
                                        $("#branch").removeClass('valid');
                                        $("#branch").addClass('error');
                                        msg += ' - ' + res.data.branch + '\\n';
                                    }
            
                                    if (res.data.email_exist) {
                                        $("#email").removeClass('valid');
                                        $("#email").addClass('error');
                                        msg += ' - ' + res.data.email_exist + '\\n';
                                    }
                                    
                                    if (res.data.uname_exist) {
                                        $("#username").removeClass('valid');
                                        $("#username").addClass('error');
                                        msg += ' - ' + res.data.uname_exist + '\\n';
                                    }
                                    
                                    alert('Please Check Again These Fields :\\n---------------------------------------------\\n' + msg);
                                } else if(res.error == 0){
                                    $(".ui-dialog-titlebar-close").trigger('click');
                                    $("#appumangridlist").trigger("reloadGrid");
                                    alert('Success!')
                                } else {
                                    alert('unknown error!');
                                    
                                }
                            }
            			});
                    }
        
                });
            });
        </script>
        
EOF;
    }
        
    function saveappuser(){
        if(!permissionAuth(3)){ 
            //die('No Permission!');
        } 
        
        if($this->mdlMain->getAllUsersCountNoRoot() >= 100){
            $error = array("error"=> 1,
                           "data" => array("other" => "Max User Reached You cannot add more user!"));
            echo json_encode($error);
            die();
        }


        $this->form_validation->set_rules('username', 'Username', 'trim|alpha_dash|required|min_length[3]|max_length[15]');
        $this->form_validation->set_rules('name', 'Name', 'trim|required|min_length[3]|max_length[25]');
        $this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[5]|max_length[15]');
        $this->form_validation->set_rules('conf_password', 'Password Confirmation', 'trim|required|min_length[5]|max_length[15]|matches[password]');     
        $this->form_validation->set_rules('phone', 'Phone', 'trim|required|numeric|min_length[6]|max_length[15]');
        $this->form_validation->set_rules('email', 'Email address', 'trim|required|valid_email|min_length[3]|max_length[50]');
        $this->form_validation->set_rules('level', 'Admin Level', 'alpha_dash|trim|required');
        $this->form_validation->set_rules('division', 'Division', 'alpha_dash|trim|required');
        $this->form_validation->set_rules('branch', 'branch', 'alpha_dash|trim|required');


        //Setting custom error messages
        $this->form_validation->set_message('min_length', 'Minimum length for %s is %s characters');
        $this->form_validation->set_message('max_length', 'Maximum length for %s is %s characters');

        if ($this->form_validation->run() === FALSE) {
            $error = array("error"=> 1,
                           "data" => form_errors_array()
            );

            echo json_encode($error);
            //echo validation_errors();
        } else {
            //Form validation is successful, clean the input and use it.

            $this->username      = $this->input->post('username');
            $this->name     = $this->input->post('name');
            $this->password = $this->input->post('password');
            $this->conf_password = $this->input->post('conf_password');
            $this->phone    = $this->input->post('phone');
            $this->email    = $this->input->post('email');
            $this->level    = $this->input->post('level');
            $this->division = $this->input->post('division');
            $this->branch = $this->input->post('branch');

             $check_username = $this->dx_auth->is_username_available($this->username);
             $check_email = $this->dx_auth->is_email_available($this->email);
             
             if ($check_username) {
                if($check_email){
                    $register = $this->dx_auth->register($this->username, $this->conf_password, $this->email,$this->level);
                    
                    
                    if(is_array($register) && $register['username'] == $this->username){
                        
                        $uid     = $this->mdlMain->usernameToID($this->username);
                        $data['name']        = $this->name;
                        $data['divisionID']  = $this->division;
                        $data['branchID']    = $this->branch;
                        $data['levelID']     = $this->level;
                        $data['phone']       = $this->phone;
                        
                        $user_profile = $this->mdlMain->registerUser($data,$uid);
                        
                        $error = array("error" => 0,
                           "data" => array("    " => 1));
                    
                    }
                    
                    
                    
                    echo json_encode($error);
                } else {
                    $error = array("error"=> 1,
                           "data" => array("email_exist" => "The email address you entered already exist!"));
                    echo json_encode($error);
                }
             } else {
                $error = array("error"=> 1,
                           "data" => array("uname_exist" => "The username you entered already exist!"));
                echo json_encode($error);
             }
            

        }
        //print_r($_POST);
        
    }
    
    function updateappuser(){
        if(!permissionAuth(3)){ 
            //die('No Permission!');
        } 
        
        


        $this->form_validation->set_rules('uid', 'UID', 'trim|numeric|required');
        $this->form_validation->set_rules('username', 'Username', 'trim|alpha_dash|required|min_length[3]|max_length[15]');
        $this->form_validation->set_rules('name', 'Name', 'trim|required|min_length[3]|max_length[25]');
        $this->form_validation->set_rules('password', 'Password', 'trim|min_length[5]|max_length[15]');
        $this->form_validation->set_rules('conf_password', 'Password Confirmation', 'trim|min_length[5]|max_length[15]|matches[password]');     
        $this->form_validation->set_rules('phone', 'Phone', 'trim|required|numeric|min_length[6]|max_length[15]');
        $this->form_validation->set_rules('email', 'Email address', 'trim|required|valid_email|min_length[3]|max_length[50]');
        $this->form_validation->set_rules('level', 'Admin Level', 'alpha_dash|trim|required');
        $this->form_validation->set_rules('division', 'Division', 'alpha_dash|trim|required');
        $this->form_validation->set_rules('branch', 'branch', 'alpha_dash|trim|required');


        //Setting custom error messages
        $this->form_validation->set_message('min_length', 'Minimum length for %s is %s characters');
        $this->form_validation->set_message('max_length', 'Maximum length for %s is %s characters');

        if ($this->form_validation->run() === FALSE) {
            $error = array("error"=> 1,
                           "data" => form_errors_array()
            );

            echo json_encode($error);
            //echo validation_errors();
        } else {
            //Form validation is successful, clean the input and use it.

            $this->uid      = $this->input->post('uid');
            $this->username      = $this->input->post('username');
            $this->name     = $this->input->post('name');
            $this->password = $this->input->post('password');
            $this->conf_password = $this->input->post('conf_password');
            $this->phone    = $this->input->post('phone');
            $this->email    = $this->input->post('email');
            $this->level    = $this->input->post('level');
            $this->division = $this->input->post('division');
            $this->branch = $this->input->post('branch');
            
            
                    
                    
            if($this->conf_password != "" && $this->password != ""){
                $this->load->model('dx_auth/users', 'users');
            
                $encode = crypt($this->dx_auth->_encode($this->conf_password)); 
				$key = md5(rand().microtime());            
				$this->users->newpass($this->uid, $encode, $key);
				$this->users->activate_newpass($this->uid, $key);							

            }
            
        
            
            $uid     = $this->mdlMain->usernameToID($this->username);
            $data['name']        = $this->name;
            $data['divisionID']  = $this->division;
            $data['branchID']    = $this->branch;
            $data['levelID']     = $this->level;
            $data['phone']       = $this->phone;
            
            $user_profile = $this->mdlMain->updateUser($data,$uid);
            
            $error = array("error" => 0,
               "data" => array("    " => 1));
            
            echo json_encode($error);
            

        }
        //print_r($_POST);
        
    }
    
    
    function blockappuser(){
       
        $this->block      = $this->input->post('block');
        $this->id      = $this->input->post('id');
        
        
        $this->mdlMain->blockUser($this->block ,$this->id);
        
        die('{"sts":"00","desc":"success"}'); 
    }
    
    function deleteappuser(){
        
        $this->id      = $this->input->post('id');
        
        
        $this->mdlMain->deleteUser($this->id);
        
        die('{"sts":"00","desc":"success"}'); 
    }
    
    function addappuserlevel(){
        
        $this->name  = $this->input->post('level_desc');
        
        $this->load->model('dx_auth/roles', 'roles');
        
      $role_id=  $this->roles->create_role($this->name);
         
			$this->load->model('dx_auth/permissions', 'permissions'); 
        
		 
		 $ctl = $this->__getAllController();
		//var_dump($ctl);die();
        $ctr_arr = explode(",",$ctl);
        
        foreach($ctr_arr as $record){
             //$role_id = $this->session->userdata('DX_role_id');
             $permission_data = $this->permissions->get_permission_data($role_id);
        
             $permission_data[trim($record)] = "1";
             //echo $record;
        	
		     // Set permission data for role_id
		     $this->permissions->set_permission_data($role_id, $permission_data);   
                
        }
		 
        die('{"sts":"00","desc":"success"}'); 
    }
    function __getAllController(){  
        
        $controller = FCPATH . "application\\controllers\\";
                 
        //get all files in specified directory
        $files = glob($controller . "*");
        //var_dump($files); die();
        //print each file name
        foreach($files as $file)
        {
         //check to see if the file is a folder/directory
         if(is_dir($file))
         {
            $folder = $file;
            $handle = opendir($folder);     
            while (false !== ($file = readdir($handle))) {                  
             
                if(substr(strrchr($file,'.'),1) == "php"){                
                    $f_arr[] = substr($file,0,strlen($file)-4);
                }       
                 
            }
         }
        }
        
        
        //echo "<pre>";print_r($f_arr);
        
        return implode(",",$f_arr);
    }
    
    function updateappuserlevel(){
        
        $this->name  = $this->input->post('level_desc');
        $this->id  = $this->input->post('level_id');
        
        $this->load->model('dx_auth/roles', 'roles');
        
        $this->roles->update_role($this->id,$this->name);
        
        die('{"sts":"00","desc":"success"}'); 
    }
    
    function addappuserdiv(){
        
        $this->name  = $this->input->post('div_desc');
        
       
        $this->mdlMain->addDivision($this->name);
        
        die('{"sts":"00","desc":"success"}'); 
    }
    
    function updateappuserdiv(){

        
        $this->name  = $this->input->post('div_desc');
        $this->id  = $this->input->post('div_id');
        
       
        $this->mdlMain->updateDivision($this->id,$this->name);
        
        die('{"sts":"00","desc":"success"}'); 
    }
    
    function deleteappuserdiv(){

        
        $this->id  = $this->input->post('div_id');
 
       
        $check = $this->mdlMain->checkField('ccs_user_profile','divisionID',$this->id);
        //echo $check; die();
        if($check > 0){
            die('{"sts":"Error => ","desc":" Division Not Empty."}');
        } else {
            $this->mdlMain->deleteDivision($this->id);
        
            die('{"sts":"00","desc":"success"}'); 
        }
        
    }
    
    function updateLevelMenutype(){ 
	
        $ids  = $this->input->post('ids');
        $level_id  = $this->input->post('level_id'); 
        $check = $this->mdlMain->updatePermissionMenutype($ids,$level_id); 
        die('{"sts":"00","desc":"success"}'); 
        
    }
    function getAllMenu(){
        header('Content-Type: application/json');
        
        
        $mr = $this->mdlMain->getAllMenuType();
        
        
        
        $count0 = count($mr['data']);
        $h = 0;
        echo '[';
        
        foreach($mr['data'] as $r){
            echo '{"title": "'.str_replace("'"," ",$r->title).'", "pid": "'.$r->id.'", "isFolder": true,"hideCheckbox": true,"unselectable": true, "key": "'.$r->menutype.'"';
            echo ',"children": [';
            
            
            $records = $this->mdlMain->getAllMenu($r->id);
            
            $count = count($records['data']);
            $i = 0;
            foreach($records['data'] as $record){
               //echo $record->title . ' >>> ' . $record->alias . '<br />';
               $is_folder = ($record->note != 'folder')? '':'"isFolder": true,';
               $is_link = ($record->link == " ")? '':'"url": "'.$record->link.'",';
               $is_icon = ($record->img == " ")? '':', "icon": "'.$record->img.'"';
               $is_check = ($record->published == 0)? ', "select": false ':', "select": true ';
               
               echo '{"title": "'.str_replace("'"," ",$record->title).'", '.$is_link.' "pid": "'.$record->id.'", '. $is_folder .'"key": "'.$record->alias.'"' . $is_icon . $is_check;
               
                    
                    $childs = $this->mdlMain->getAllChildMenu($record->id);
                    $count2 = count($childs['data']);
                    
                    
                    if($count2 > 0){
                        echo ',"children": [';
                        $j = 0;
                        // child loop start
                        foreach($childs['data'] as $child){
                            $is_icon = ($child->img == " ")? '':', "icon": "'.$child->img.'"';
                            $is_check = ($record->published == 0)? ', "select": false ':', "select": true ';
                            echo '{"title": "'.str_replace("'"," ",$child->title).'", "url": "'.$child->link.'", "pid": "'.$child->id.'", "key": "'.$child->alias.'" ' . $is_icon . $is_check;      
                            
                            
                            $grandChilds = $this->mdlMain->getAllChildMenu($child->id);
                            $count3 = count($grandChilds['data']);
                            
                            if($count3 > 0){
                                echo ',"children": [';
                                
                                $k = 0;
                                // grandchild loop start
                                foreach($grandChilds['data'] as $grandChild){
                                    $is_icon = ($grandChild->img == " ")? '':', "icon": "'.$grandChild->img.'"';
                                    $is_check = ($record->published == 0)? ', "select": false ':', "select": true ';
                                    
                                    echo '{"title": "'.str_replace("'"," ",$grandChild->title).'", "url": "'.$grandChild->link.'", "pid": "'.$grandChild->id.'", "key": "'.$grandChild->alias .'"'. $is_icon . $is_check;                    
                                    
                                    
                                    $gGrandChilds = $this->mdlMain->getAllChildMenu($grandChild->id);
                                    $count4 = count($gGrandChilds['data']);
                                    
                                    if($count4 > 0){
                                        echo ',"children": [';
                                        
                                        $l = 0;
                                        // grandgrandchild loop start
                                        foreach($gGrandChilds['data'] as $gGrandChild){
                                            $is_icon = ($gGrandChild->img == " ")? '':', "icon": "'.$gGrandChild->img.'"';
                                            $is_check = ($record->published == 0)? ', "select": false ':', "select": true ';
                                            echo '{"title": "'.str_replace("'"," ",$gGrandChild->title).'", "url": "'.$gGrandChild->link.'", "pid": "'.$gGrandChild->id.'", "key": "'.$gGrandChild->alias.'"' . $is_icon . $is_check;                    
                                            
                                            $l++;
                                            if ($l < $count4){
                                              echo '},';
                                            } else {
                                              echo '}';   
                                            }
                                        }
                                        // grandgrandchild loop end
                                        
                                        $l = 0;
                                        
                                        echo ']';
                                    }
                                    
                                    
                                    
                                    $k++;
                                    if ($k < $count3){
                                      echo '},';
                                    } else {
                                      echo '}';   
                                    }
                                }
                                // grandchild loop end
                                
                                $k = 0;
                                
                                echo ']';
                            }
                            
                                          
                            $j++;
                            if ($j < $count2){
                              echo '},';
                            } else {
                              echo '}';   
                            }
                        }
                        // child loop end
                        $j = 0;
                        
                        echo ']';
                    }
                    
                    
               
               $i++;
               if ($i < $count){
                 echo '},';
               } else {
                 echo '}';   
               }
               
               
            }
           // child loop end
           $i = 0;
            
           echo ']';
           
           $h++;
           if ($h < $count0){
             echo '},';
           } else {
             echo '}';   
           }
               
        }
        echo ']';
        
    }
    
}