<?php
	class Admin_data extends Admin_Controller{
		public function __construct(){
			parent::__construct();
			$this->load->model('sendmails_model', 'send_mail');
		}

		public function index(){

			$this->data["access_right"] = "view_right";
			$this->data["page_name"] = "admin_users";
			$this->data['meta_title'] = 'Admin Users';

			$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').'/admin_data/index';
				$this->load->view($this->config->item('admin_folder').'/_layout_main', $this->data);

			}
		}

		public function login(){

			$dashboard = base_url().$this->config->item('admin_folder').'/dashboard';

			if(isset($_POST) && !empty($_POST)){

				// Set Form
				$rules = $this->admin_user->rules;
				$this->form_validation->set_rules($rules);

				// Process form
				if($this->form_validation->run() === TRUE){
					//We can login and redirect

					$user_details = $this->admin_user->get_by(array(
						'email' => $this->input->post('email'),
						'password' => $this->admin_user->hash($this->input->post('password'))
					), TRUE);

					if(!empty($user_details)){
						//Update the token and OTP
						$update_data["email_otp"] = random_numeric_string(4);
						$update_data["email_token"] = $this->admin_user->hash(random_numeric_string(16));

						$this->admin_user->save($update_data, $user_details->id);

						//Send an OTP Email
						$email_data['email'] = $user_details->email;
						$email_data['email_view'] = "emails/admin_send_otp";
						$email_data['subject'] = "Your Admin OTP is: ".$update_data["email_otp"];
						$email_data['data'] = $user_details;
						$email_data['email_otp'] = $update_data["email_otp"];
						$email_result = $this->send_mail->htmlmail($email_data);

						$dashboard = base_url().$this->config->item('admin_folder').'/verify-email?token='.$update_data["email_token"];

						$returnArr["status"] = true;
						$returnArr["message"] = "Success";
						$returnArr["redirect_url"] = $dashboard;

						echo json_encode($returnArr);
						exit;

					}else{
						$returnArr["status"] = false;
						$returnArr["message"] = "That email/password combination does not exist.";

						echo json_encode($returnArr);
						exit;
					}

				}else{
					$returnArr["status"] = false;
					$returnArr["message"] = "Validation error";
					$returnArr["errors"] = $this->form_validation->error_array();

					echo json_encode($returnArr);
					exit;
				}

			}


			// Redirect a user if he's already logged in 
			$this->admin_user->loggedin() == FALSE || redirect($dashboard); 

			// Load view
			$this->load->view($this->config->item('admin_folder').'/login/index');
		}

		public function verify_email(){
			$token = "";
			if(isset($_GET['token']) && !empty($_GET['token'])){
				$token = $_GET['token'];
			}

			if($token){
				if(isset($_POST) && !empty($_POST)){
					$user_details = $this->admin_user->get_by(array(
						'email_token' => $token
					), TRUE);

					if(!empty($user_details)){
						if($user_details->email_otp === $_POST['email_otp']){
							$data = array(
								'name' => $user_details->name,
								'email' => $user_details->email,
								'id' => $user_details->id,
								'role_id' => $user_details->role_id,
								'loggedin' => TRUE
							);

							$this->session->set_userdata($data);

							$dashboard = base_url().$this->config->item('admin_folder').'/dashboard';

							$update_data["email_otp"] = random_numeric_string(4);
							$update_data["email_token"] = $this->admin_user->hash(random_numeric_string(16));

							$this->admin_user->save($update_data, $user_details->id);

							$returnArr["status"] = true;
							$returnArr["message"] = "Success";
							$returnArr["redirect_url"] = $dashboard;

							echo json_encode($returnArr);
							exit;
						}else{
							$returnArr["status"] = false;
							$returnArr["message"] = "Invalid OTP. Please try again.";

							echo json_encode($returnArr);
							exit;
						}
					}else{
						$returnArr["status"] = false;
						$returnArr["message"] = "Invalid admin token.";

						echo json_encode($returnArr);
						exit;
					}

				}
			}


			$this->load->view($this->config->item('admin_folder').'/login/verify_email');
		}

		public function logout(){
			$this->admin_user->logout();
			redirect(base_url().$this->config->item('admin_folder'));
		}

		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(
						"admin_users.name" => $_POST['search']['value'],
						"admin_users.email" => $_POST['search']['value'],
						"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["admin_users.status != "] = 2;
				$this->db->join("hc_role", "hc_role.id = admin_users.role_id");
				$this->db->select("admin_users.*, hc_role.role_name");
				$this->db->where($search_params);
				$this->db->limit($_POST['length'], $_POST['start']);
				$result = $this->admin_user->get();

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

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

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

		            $data[] = $row;
				}

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

			}
		}

		public function edit($id = NULL){
			$this->data["access_right"] = "edit_right";
			$this->data["page_name"] = "admin_users";
			if($id){
				$this->data['meta_title'] = 'Edit admin user';
				$this->data['admin_user'] = $this->admin_user->get_admin_user(array("admin_users.id" => $id));

				//------------------------------------Activity logs--------------------------------------
				$logs_data["action_type"] = "Edit Admin User";
				$logs_data["action_identifier"] = "admin_user_logs";

				$this->data["access_right"] = "edit_right";
			}else{
				$this->data['admin_user'] = $this->admin_user->get_new();
				$this->data["meta_title"] = "Add Admin User";

				//------------------------------------Activity logs--------------------------------------
				$logs_data["action_type"] = "Add Admin User";
				$logs_data["action_identifier"] = "admin_user_logs";

				$this->data["access_right"] = "create_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{

				//

				if(isset($_POST) && !empty($_POST)){
					$rules = $this->admin_user->admin_user_rules;
					if(!$id){
						$rules["email"]["rules"] .= '|is_unique[admin_users.email]';
					}
					$this->form_validation->set_rules($rules);

					if($this->form_validation->run() === TRUE){
						$data = $this->admin_user->array_from_post(array('name', 'email', 'password', 'role_id'));

						$data["email_otp"] = random_numeric_string(4);
						$data["email_token"] = $this->admin_user->hash(random_numeric_string(16));

						if($data['password'] != ""){
							$data["password"] = $this->admin_user->hash($data["password"]);
						}else{
							unset($data["password"]);
						}

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

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

						if($result_id){

							$returnArr["status"] = TRUE;
							$returnArr["message"] = "Details saved successfully.";
							if($id){
								$returnArr["redirect_url"] = base_url().$this->config->item('admin_folder').'/admin_data/index';
							}else{
								$returnArr["redirect_url"] = base_url().$this->config->item('admin_folder').'/admin_data/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;
					}
				}

				$this->data["roles"] = $this->db->select(" hc_role.* FROM hc_role")->get()->result();
				$this->data['subview'] = $this->config->item('admin_folder').'/admin_data/edit';
				$this->load->view($this->config->item('admin_folder').'/_layout_main', $this->data);

			}
		}


		public function delete($id){

        	$returnArr = array();

        	$this->data["page_name"] = "admin_users";
			$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);
				exit;
			}else{

	        	//------------------------------------Activity logs--------------------------------------
				$logs_data["action_type"] = "Delete Admin User";
				$logs_data["action_identifier"] = "admin_user_logs";

	        	if($id){
	        		$update_val["status"] = 2;
					$result = $this->admin_user->save($update_val,$id);

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

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

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

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

	}
?>