<?php
	class Roles extends Admin_Controller{

		public function __construct(){
			parent::__construct();
			$this->load->model('hc_roles_model', 'roles');
			$this->load->model('hc_role_rights_model', 'role_rights');
			$this->load->model('hc_modules_model', 'modules');
		}

		public function index(){
			$this->data["meta_title"] = "Roles";
			$this->data["page_name"] = "roles";
			$this->data["access_right"] = "view_right";
			$access_control = $this->admin_user->get_admin_rights($this->data);
			if(!$access_control){
				$this->data['subview'] = $this->config->item('admin_folder').'/access_denied';
				$this->load->view($this->config->item('admin_folder').'/_layout_main', $this->data);
			}else{
				$this->data['subview'] = $this->config->item('admin_folder').'/roles/index';
				$this->load->view($this->config->item('admin_folder').'/_layout_main', $this->data);
			}
		}


		public function ajax_load_data(){
			if(isset($_POST) && !empty($_POST)){

				$search_params = array();
				$like_params = array();

				if(isset($_POST['search']['value']) && !empty($_POST['search']['value'])){
					$like_params = array(
						"hc_role.role_name" => $_POST['search']['value']
					);

					$this->db->group_start();
					foreach ($like_params as $key => $value) {
						$this->db->or_like($key, $value);
					}
					$this->db->group_end();
		        }

				$search_params["hc_role.is_active != "] = 2;
				$this->db->select("hc_role.*");
				$this->db->where($search_params);
				$this->db->limit($_POST['length'], $_POST['start']);
				$result = $this->roles->get();

				$data = array();
	        	$no = $_POST['start'];

				foreach ($result as $key => $value) {
					$no++;
		            $row = array();
		            
		            $row[] = "<strong>".$no.".</strong>";
		            $row[] = $value->role_name;
		            if($value->is_active == 1){
		            	$row[] = '<span class="badge badge-success">Active</span>';
		            }else{
		            	$row[] = '<span class="badge badge-danger">In-active</span>';
		            }

		            $a = "";
		            $a = btn_edit(base_url().$this->config->item('admin_folder').'/roles/edit/'.$value->id);
		            if($value->id != 1){
	            		$a .= ' '.btn_delete($this->config->item('admin_folder').'/roles/delete/'.$value->id);
	            	}
	            	
	            	$row[] = $a;

		            $data[] = $row;
				}

				$output = array(
	                "draw" => $_POST['draw'],
	                "recordsTotal" => $this->roles->get_count($search_params),
	                "recordsFiltered" => $this->roles->get_count($search_params, $like_params),
	                "data" => $data,
	        	);
		        //output to json format
		        echo json_encode($output);

			}
		}

		public function edit($id = NULL){
			if($id){
				$this->data['roles'] = $this->roles->get_by(array("hc_role.id" => $id), TRUE);
				$this->data["meta_title"] = "Edit Role";

				//------------------------------------Activity logs--------------------------------------
				$logs_data["action_type"] = "Edit Role";
				$logs_data["action_identifier"] = "admin_role_logs";

				$this->data["access_right"] = "edit_right";

			}else{
				$this->data['roles'] = $this->roles->get_new();
				$this->data["meta_title"] = "Add Role";

				//------------------------------------Activity logs--------------------------------------
				$logs_data["action_type"] = "Add role";
				$logs_data["action_identifier"] = "admin_role_logs";

				$this->data["access_right"] = "create_right";
			}

			
			$this->data["page_name"] = "roles";
			$access_control = $this->admin_user->get_admin_rights($this->data);
			if(!$access_control){
				$this->data['subview'] = $this->config->item('admin_folder').'/access_denied';
				$this->load->view($this->config->item('admin_folder').'/_layout_main', $this->data);
			}else{
				//Get the modules
				$this->db->where(array("is_active" => 1));
				$this->db->order_by("sorting_order", "asc");
				$this->data["modules"] = $this->modules->get();

				//Module rights
				if($id){
					foreach ($this->data["modules"] as $key => $value) {
						$this->data["modules"][$key]->role_rights = $this->role_rights->get_by(array("role_id" => $id, "module_id" => $value->id), TRUE);
					}
				}

				if(isset($_POST) && !empty($_POST)){
					// Set up the form
					$rules = $this->roles->rules;
					
					$this->form_validation->set_rules($rules);

					if($this->form_validation->run() === TRUE){
						$data = $this->roles->array_from_post(array('role_name', 'is_active'));

						if(!$id){
							$data["created_at"] = Date('Y-m-d H:i:s');
							$data["created_by"] = isset($_SESSION["id"]) ? $_SESSION["id"] : 0;
						}

						$data["updated_at"] = Date('Y-m-d H:i:s');
						$data["updated_by"] = isset($_SESSION["id"]) ? $_SESSION["id"] : 0;

						$logs_data["request"] = json_encode($data, TRUE);

						$result_id = $this->roles->save($data, $id);
						$returnArr = array();

						if($result_id){

							//if($result_id != 1){

								foreach ($this->data["modules"] as $key => $value) {

									$update_role_rights["role_id"] = $result_id;
									$update_role_rights["module_id"] = $value->id;
									$update_role_rights["create_right"] = isset($_POST['create'.$value->id]) && $_POST['create'.$value->id] == 'on' ? 1 : 0;
									$update_role_rights["view_right"] = isset($_POST['list'.$value->id]) && $_POST['list'.$value->id] == 'on' ? 1 : 0;
									$update_role_rights["edit_right"] = isset($_POST['edit'.$value->id]) && $_POST['edit'.$value->id] == 'on' ? 1 : 0;
									$update_role_rights["delete_right"] = isset($_POST['delete'.$value->id]) && $_POST['delete'.$value->id] == 'on' ? 1 : 0;

									$role_rights_row = $this->role_rights->get_by(array("role_id" => $result_id, "module_id" => $value->id), TRUE);
									$role_rights_id = NULL;
									if($role_rights_row){
										$role_rights_id = $role_rights_row->id;
									}else{
										$update_role_rights["created_at"] = Date('Y-m-d H:i:s');
										$update_role_rights["created_by"] = isset($_SESSION["id"]) ? $_SESSION["id"] : 0;
									}

									$update_role_rights["updated_at"] = Date('Y-m-d H:i:s');
									$update_role_rights["updated_by"] = isset($_SESSION["id"]) ? $_SESSION["id"] : 0;

									$this->role_rights->save($update_role_rights, $role_rights_id);
									
								}
							//}

							$returnArr["status"] = TRUE;
							$returnArr["message"] = "Details saved successfully.";
							if($id){
								$returnArr["redirect_url"] = base_url().$this->config->item('admin_folder').'/roles/index';
							}else{
								$returnArr["redirect_url"] = base_url().$this->config->item('admin_folder').'/roles/edit/'.$result_id;
							}

						}else{
							$returnArr["status"] = FALSE;
							$returnArr["message"] = "Failed to perform this action.";
						}

						//--------------------------------------------Save Activity Logs-----------------------------
						$logs_data["response"] = json_encode($returnArr, TRUE);
						$log_id = $this->logs->add_log($logs_data);

	    				echo json_encode($returnArr);
		            	exit;

					}else{
						$returnArr["status"] = false;
						$returnArr["message"] = "Validation Failed.";
						$returnArr["errors"] = validation_errors();

						//--------------------------------------------Save Activity Logs-----------------------------
						$logs_data["response"] = json_encode($returnArr, TRUE);
						$log_id = $this->logs->add_log($logs_data);

		    			echo json_encode($returnArr);
		            	exit;
					}
				}else{
					$this->data['subview'] = $this->config->item('admin_folder').'/roles/edit';
					$this->load->view($this->config->item('admin_folder').'/_layout_main', $this->data);
				}
			}
		}

		public function delete($id){

        	$returnArr = array();

        	$this->data["page_name"] = "roles";
			$this->data["access_right"] = "delete_right";
			$access_control = $this->admin_user->get_admin_rights($this->data);
			if(!$access_control){
				$returnArr["status"] = FALSE;
				$returnArr["message"] = "Access denied!";

				echo json_encode($returnArr, TRUE);
			}else{

	        	//------------------------------------Activity logs--------------------------------------
				$logs_data["action_type"] = "Delete Admin Role";
				$logs_data["action_identifier"] = "admin_role_logs";

	        	if($id && $id != 1){
	        		$update_val["is_active"] = 2;
					$result = $this->roles->save($update_val,$id);

					if($result){
						$returnArr["status"] = TRUE;
						$returnArr["message"] = "Row deleted successfully.";
						$returnArr["redirect"] = base_url().$this->config->item('admin_folder').'/roles/index';
					}else{

						$returnArr["status"] = FALSE;
						$returnArr["message"] = "Failed to delete row.";
						$returnArr["redirect"] = base_url().$this->config->item('admin_folder').'/roles/index';
					}
				}else{

			    	$returnArr["status"] = FALSE;
					$returnArr["message"] = "Validation Error";
					$returnArr["errors"] = "ID is required/Invalid ID";
					
				}

				//--------------------------------------------Save Activity Logs-----------------------------
				$logs_data["response"] = json_encode($returnArr, TRUE);
				$log_id = $this->logs->add_log($logs_data);
				
				echo json_encode($returnArr, TRUE);
			}
		}
	}
?>