<?php
	class Distributors extends Admin_Controller{
		public function __construct(){
			parent::__construct();

			$this->load->model("Hc_distributors", "distributors");
			$this->load->model('sendmails_model', 'send_mail');
		}

		public function index(){

			$this->data["access_right"] = "view_right";
			$this->data["page_name"] = "distributors";
			$this->data['meta_title'] = 'Manage distributors';

			$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').'/distributors/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_distributors.first_name" => $_POST['search']['value'],
						"hc_distributors.last_name" => $_POST['search']['value'],
						"hc_distributors.email" => $_POST['search']['value'],
						"hc_distributors.mobile_number" => $_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_distributors.is_active != "] = 2;
				$this->db->select("hc_distributors.*");
				$this->db->where($search_params);
				$this->db->limit($_POST['length'], $_POST['start']);
				$this->db->order_by("created_at", "desc");
				$result = $this->distributors->get();

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

				foreach ($result as $key => $value) {

					
					$no++;
		            $row = array();
		            
		            $row[] = "<strong>".$no.".</strong>";
		            $row[] = $value->first_name." ".$value->last_name;
		            $row[] = $value->email;
		            $row[] = $value->mobile_number;
		            
		            if($value->is_active == 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').'/distributors/edit/'.$value->id);
		            $a .= ' '.btn_delete($this->config->item('admin_folder').'/distributors/delete/'.$value->id);
	            	
	            	
	            	$row[] = $a;

		            $data[] = $row;
				}

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

			}
		}

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

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

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

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

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

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

			
			$this->data["page_name"] = "distributors";
			$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)){
					// Set up the form
					$rules = $this->distributors->rules;
					
					$this->form_validation->set_rules($rules);

					$updated_password = "";

					if($this->form_validation->run() === TRUE){
						$data = $this->distributors->array_from_post(array('first_name', 'last_name', 'email', 'mobile_number', 'company_name', 'expiry_date', 'is_active'));

						$data['expiry_date'] = Date('Y-m-d', strtotime($data['expiry_date']));
						$data['two_fa_enabled'] = 1;

						//Check for duplicate emnail ids
						if($id){
							$this->db->where("id != ". $id);
						}
						$distributor_details = $this->distributors->get_by(array("email" => $data['email']), TRUE);
						if(!empty($distributor_details)){
							$returnArr["status"] = false;
							$returnArr["message"] = "Email Id already exists.";

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

			    			echo json_encode($returnArr);
			            	exit;
						}
						

						if(!$id){
							$updated_password = $this->input->post('password');
							$data['email_otp'] = random_numeric_string(4);
							$data['password'] = my_hash($this->input->post('password'));
							$data["created_at"] = Date('Y-m-d H:i:s');
							$data["created_by"] = isset($_SESSION["id"]) ? $_SESSION["id"] : 0;
						}else{
							if(isset($_POST['password']) && $_POST['password'] != ""){
								$updated_password = $this->input->post('password');
								$data['password'] = my_hash($this->input->post('password'));
							}
						}

						$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->distributors->save($data, $id);
						$returnArr = array();

						if($result_id){

							if($updated_password != "" && $_POST['send_email'] == 'on'){
								//Send an email to admin
								$email_data['email'] = $data['email'];
								$email_data['email_view'] = "emails/send_distributor_password";
								$email_data['subject'] = "Distributor's Account";
								$email_data['data'] = $data;
								$email_data['password'] = $updated_password;
								$email_result = $this->send_mail->htmlmail($email_data);

								$returnArr['email_result'] = $email_result;
							}

							$returnArr["status"] = TRUE;
							$returnArr["message"] = "Details saved successfully.";
							$returnArr["redirect_url"] = base_url().$this->config->item('admin_folder').'/distributors/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').'/distributors/edit';
					$this->load->view($this->config->item('admin_folder').'/_layout_main', $this->data);
				}
			}
		}


		public function delete($id){

        	$returnArr = array();

        	$this->data["page_name"] = "distributors";
			$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 distributors";
				$logs_data["action_identifier"] = "distributors";

	        	if($id){
	        		$update_val["is_active"] = 2;
	        		$update_val["deleted_date"] = Date("Y-m-d H:i:s");
					$result = $this->distributors->save($update_val,$id);

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

						$returnArr["status"] = FALSE;
						$returnArr["message"] = "Failed to delete row.";
						$returnArr["redirect"] = base_url().$this->config->item('admin_folder').'/distributors/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);
			}
		}

	}
?>