MOON
Server: Apache
System: Linux nserver.cafsindia.com 4.18.0-553.104.1.lve.el8.x86_64 #1 SMP Tue Feb 10 20:07:30 UTC 2026 x86_64
User: cafsindia (1002)
PHP: 8.2.30
Disabled: NONE
Upload Files
File: //home/cafsindia/uds.cafsinfotech.in/application/controllers/Employees.php
<?php if ( ! defined('BASEPATH')) exit('No direct script is allowed');
require_once("Action_controller.php");
require('./application/libraries/PHPSpreadsheet/autoload.php');
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
class Employees  extends Action_controller{	
	public function __construct(){
		parent::__construct('employees');
	}
	// LOAD PAGE QUICK LINK,FILTERS AND TABLE HEADERS
	public function index(){
		$this->page_info();
		$data['module_sts']       = (int)$this->module_sts;
		$data['quick_link']       = $this->quick_link;
		$data['pick_list']        = $this->pick_list;
		$data['form_info']        = $this->form_info;
		$data['table_head']       = $this->table_head;
		$data['fliter_list']      = $this->fliter_list;
		$data['freeze_list']      = $this->freeze_list;
		$data['encKey']       	  = $this->generateKey();	
		//for edit button hide and show function
		//end
		$com_qry    = 'select * from cw_company_information where cw_company_information.trans_status = 1';
		$com_info   = $this->db->query("CALL sp_a_run ('SELECT','$com_qry')");
		$com_result = $com_info->result();
		$com_info->next_result();

		$data['comp_info'] = $com_result[0];
		$this->load->view("$this->control_name/manage",$data);
	}
	
	//LOAD TABEL WITH FILTERS
	//LOAD TABEL WITH FILTERS
	public function search(){
		$dec_data         = $this->cryptoDecrypt($_POST['Payload']);
		$_POST            = $dec_data['data'];
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'Invalid Request..'));
			exit(0);
		}		
		//SEARCH INFO FUNCTION
		$this->search_info();
		$module_sts       = (int)$this->module_sts;
		if(!$module_sts){
			echo json_encode(array('success' => FALSE, 'message' => "Search  Info Query Process Error..!"));
			exit(0);
		}else{
			$draw             = $this->input->post('draw');
			$start            = $this->input->post('start');
			$per_page         = $this->input->post('length');
			$order            = $this->input->post('order');
			$order_col        = $this->input->post('columns');
			$search           = $this->input->post('search');
			$column           = $order[0]['column'];
			$order_sor        = $order[0]['dir'];
			$order_col        = $order_col[$column]['data'];
			$search           = trim($search['value']);
			$search_query     = str_replace("@SELECT@",$this->select_query,$this->base_query);
		
			$search_result    = array();
			//ADDED BASIC,FILTER,COMMON QUERY HERE 
			$role_condition   = "";
			if($this->role_condition){
				$role_condition = $this->role_condition;
			}
			
			$fliter_query = "";
			//DR COMMAND CODE FOR WAITING TO ADD A NEW CHANGES
			foreach($this->fliter_list as $fliter){
				$label_id         = $fliter->label_name;
				$field_isdefault  = (int)$fliter->field_isdefault;
				$field_type       = (int)$fliter->field_type;
				$prime_form_id 	  = $fliter->prime_form_id;

				if($field_isdefault === 1){
					$column_name = $this->prime_table .".$label_id";
					$search_val  = $this->input->post("$label_id");
					if($search_val){
						if($field_type === 4){
							$search_val    = date('Y-m-d',strtotime($search_val));
							$fliter_query .= ' and '.$column_name.' = "'.$search_val.'"';
						}else
						if(($field_type === 5) || ($field_type === 7)){
							$search_val    = trim(implode('","',$search_val ?? []));
							$fliter_query .= ' and '.$column_name.' in ("'.$search_val.'")';  
						}else
						if($field_type === 9){
							$search_id     = 'filter_'.$label_id.'_hidden_'.$prime_form_id;
							$search_val    = $this->input->post("$search_id");
							$fliter_query .= ' and '.$column_name.' in ("'.$search_val.'")';  
						}else
						if($field_type === 13){
							$search_val    = date('Y-m-d H:i:s',strtotime($search_val));
							$fliter_query .= ' and '.$column_name.' = "'.$search_val.'"';
						}else{
							$fliter_query .= ' and '.$column_name.' LIKE "'.$search_val.'%"';
						}
					}
				}
			}
			$common_search = "";
			if($search){
				foreach($this->table_head as $setting){
					$prime_form_id      = $setting->prime_form_id;
					$field_type         = (int)$setting->field_type;
					$pick_list          = $setting->pick_list;
					$pick_table         = $setting->pick_table;
					$pick_list_type     = $setting->pick_list_type;
					$input_view_type    = (int)$setting->input_view_type;
					$auto_prime_id      = $setting->auto_prime_id;
					$auto_dispaly_value = $setting->auto_dispaly_value;
					$label_id           = strtolower(str_replace(" ","_",$setting->label_name));
					$field_isdefault    = (int)$setting->field_isdefault;
					if($field_isdefault === 1){
						if(($input_view_type === 1) || ($input_view_type === 2)){
							$search_label = "$this->prime_table.$label_id";
							$search_val   = "";
							if($field_type === 4){ // having issues in date search
								if(strtotime($search)){
									$search_val = date('Y-m-d',strtotime($search));
									$common_search .= ' or '. $search_label .' like "'.$search_val.'%"';
								}
							}else
							if(($field_type === 5) || ($field_type === 7) || ($field_type === 9)){
								$result = array_filter($this->pick_list[$label_id]['array_list'] ?? [], function ($item) use ($search) {
									if (stripos($item, $search) !== false) {
										return true;
									}
									return false;
								});
								if($result){
									$pick_key = implode('", "', array_keys($result ?? []) ?? []);
									$common_search .= ' or '. $search_label .' in("'.$pick_key.'")';
								}
							}else{
								$common_search .= ' or '. $search_label .' like "'.$search.'%"';
							}
						}
					}
				}
				if($common_search){
					$common_search = ltrim($common_search,' or ');
					$common_search = " and ($common_search)";
					$common_search = str_replace("(,","(",$common_search);
					$common_search = str_replace("()","(0)",$common_search);
				}
			}
			$count_all_query    = str_replace("@SELECT@","count(*) as allcount",$this->base_query);
			$count_query        = $count_all_query.' where '.$this->prime_table.'.trans_status = 1 and cw_employees.entry_flag = "e" '.$role_condition.$fliter_query.$common_search;
			
			$search_query      .= " where $this->prime_table.trans_status = 1 and $this->prime_table.prime_employees_id != 1 and $this->prime_table.entry_flag = 'e' $role_condition $fliter_query $common_search";
			$search_query      .= " ORDER BY  $order_col $order_sor";
			if((int)$per_page !== -1){
				$search_query  .= " LIMIT  $start,$per_page";
			}	
	

			$search_pro_qry     = [];
			$search_pro_qry[]   = array("return"=>"total_count","qry"=>$count_all_query);
			$search_pro_qry[]   = array("return"=>"filtered_count","qry"=>$count_query);
			$search_pro_qry[]   = array("return"=>"search_result","qry"=>$search_query);

			$search_info_rslt   = $this->run_multi_qry($search_pro_qry);
			$total_count        = $search_info_rslt->rslt->total_count[0]->allcount;
			$filtered_count     = $search_info_rslt->rslt->filtered_count[0]->allcount;
			
			$search_result      = json_decode(json_encode($search_info_rslt->rslt->search_result),true);

			if($search_result === null || $search_result === ''){
				$search_result  = [];
			}
			echo json_encode(array("draw" => intval($draw),"recordsTotal" => $total_count,"recordsFiltered" => $filtered_count,"data" => $search_result));	
		}	
	}
	//LOAD MODEL PAGE VIEW WITH DATA
	public function view($form_view_id=-1){
		$data['primeId']     = $form_view_id;
		if($form_view_id !== -1){
			//Decrypt prime id from URL
			$decRslt          = $this->cryptoDecrypt(base64_decode(urldecode($form_view_id)));
			$form_view_id     = $decRslt['prime_id'];
			if(!$form_view_id){
				echo json_encode(array('success' => false,'message' => 'Invalid Request..','table_data' => ""));
				exit(0);
			}
		}
		//VIEW INFO FUNCTION
		$this->view_info($form_view_id);
		$data['module_sts']            = (int)$this->module_sts;
		//VIEW, FORM INPUT
		$data['view_info']             = $this->view_info;
		$data['form_info']             = $this->form_info;
		$data['formula_result']        = $this->formula_result;//for label color change
		$data['role_based_condition']  = $this->role_based_condition;//for label name readonly options
		$data['all_pick']              = $this->pick_list;//all pick result			
		$data['condition_list']        = $this->form_condition_list;

		//DR CODE FOR DATA COME FROM TIME SHEET
		$data['personal_code']         = $this->input->post("personal_code");
		$data['project_id']            = $this->input->post("project_id");
		$data['comp_info']             = $this->company_info[0];
		//AUTO COMPLTE,PICK LIST AND CONDITION
		/*foreach($this->form_info as $from){
			$prime_form_id      = (int)$from->prime_form_id;
			$field_type         = (int)$from->field_type;
			$pick_table         = $from->pick_table;
			$auto_prime_id      = $from->auto_prime_id;
			$auto_dispaly_value = $from	->auto_dispaly_value;
			$label_id           = $from->label_name;
			if($field_type === 9){
				if($view_result[0]){
					$get_value = $view_result[0]->$label_id;
					if($get_value){
						$pick_query = 'select '.$auto_dispaly_value.' from '.$pick_table.' where '.$auto_prime_id.' = "'.$get_value.'" and trans_status = 1';
						$pick_data   = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
						$pick_result = $pick_data->result();
						$pick_data->next_result();
						$this->pick_list[$label_id]['array_list'] = $pick_result[0]->$auto_dispaly_value;
					}					
				}
			}
		}*/	
		
		//VIEW DATA
		$base_query          = str_replace("@SELECT@",$this->view_select,$this->base_query);
		$form_view_qry       = $base_query .' where '.$this->prime_table.'.'.$this->prime_id.' = '.$form_view_id.' and '.$this->prime_table.'.trans_status = 1';
		$row_view_qry        = 'select * from cw_form_view_setting where  prime_view_module_id = "'.$this->control_name.'" and  form_view_type = "3" and trans_status = 1';
		
		$view_pro_qry        = [];
		$view_pro_qry[]      = array("return"=>"form_view","qry"=>$form_view_qry);
		$view_pro_qry[]      = array("return"=>"row_view_list","qry"=>$row_view_qry);	

		$view_info_rslt      = $this->run_multi_qry($view_pro_qry);
		$form_view_rslt      = $view_info_rslt->rslt->form_view[0];			
		$row_view_rslt       = $view_info_rslt->rslt->row_view_list;

		$data['form_view']   = $form_view_rslt;
		
		$row_view_list       = array();
		foreach($row_view_rslt as $view){
			$prime_form_view_id   = $view->prime_form_view_id;
			$row_set_data         = $this->get_row_set_data($prime_form_view_id,$form_view_id);
			$row_view_list[$prime_form_view_id] = $row_set_data;
		}
		$data['row_view_list']   = $row_view_list;
		
		/*============ UDY EMPLOYEE CUSTOME BLOCK ============*/
		$arr = array();
		foreach($this->Module->get_all_modules($this->control_name) as $module){
			$module->module_id = $this->xss_clean($module->module_id);
			$module->grant     = $this->xss_clean($this->Module->has_grant($this->control_name,$module->module_id, $form_view_id));
			$module->access    = $this->xss_clean($this->Module->has_access($this->control_name,$module->module_id, $form_view_id));
			$menu = str_replace(" ","_",strtolower($module->menu_name)); //."_".$module->menu_id
			$submenu = str_replace(" ","_",strtolower($module->sub_menu_name));		
			if(!$submenu){
				$submenu = "sub_".$menu;
			}
			$arr[$menu][$submenu][] = $module;	
		}

		$data['all_modules'] = $arr;
		/*============ UDY EMPLOYEE CUSTOME BLOCK ============*/
		$data['edit_id']       = $form_view_id;

		//Get unique fields
		$uniq_field_qry  = 'select CONCAT("#",label_name) as label_name from cw_form_setting inner join cw_sap_employee_validation on cw_sap_employee_validation.smart_field_name = cw_form_setting.label_name where cw_form_setting.prime_module_id = "employees" and input_view_type IN(1,2) and cw_sap_employee_validation.sap_unique = "Y" and cw_sap_employee_validation.trans_status = 1';

		$uniq_field_info = $this->db->query("CALL sp_a_run ('SELECT','$uniq_field_qry')");
		$uniq_field_rslt = $uniq_field_info->result_array();
		$uniq_field_info->next_result();
		$data['unique_lables']  = implode(",",array_column($uniq_field_rslt ?? [], 'label_name') ?? []);
		$data['encKey']       	  = $this->generateKey();	
		$this->load->view("$this->control_name/form",$data);
	}
	
	//SAVE MODEL DATA TO DATA BASE
	public function save(){
		//Encryption
		$encString      = file_get_contents('php://input');
		$_POST          = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'Invalid Request..','table_data' => ""));
			exit(0);
		}
		//SAVE INFO FUNCTION
		$this->save_info();	
		$module_sts          = (int)$this->module_sts;
		if(!$module_sts){
			echo json_encode(array('success' => FALSE, 'message' => "Save Info Query Process Error...!"));
			exit(0);
		}else{
			$unq_chk              = array();
			$prime_qry_key        = "";
			$prime_qry_value      = "";
			$prime_upd_query      = "";
			$cf_has               = false;
			$form_id              = (int)$this->input->post($this->prime_id);
			$form_post_data       = array();	
			$emp_log              = array();
			$post_data            = array();
			$emp_log['prime_employees_id'] = $form_id;
			$post_array           = array('emp_name','date_of_birth','stop_pay_code','father_name','aadhar_card_no','pan_number','emp_uan','mobile_number','emp_esi_location','emp_esi_no','emp_pf_no','husband_name','resignation_date','bank_key','bank_account_number','ifsc_code');
			$prev_array           = array('emp_name','date_of_birth','stop_pay_code','father_name','aadhar_card_no','pan_number','emp_uan','mobile_number','emp_esi_location','emp_esi_no','emp_pf_no','husband_name','resignation_date');
			//--------------- BANK VERIFACTION ARRAY CREATION START--------------------
			//DR CODE FOR BANK VERIFICATION INPUTS ARRAY QUERY
			$bank_verify_qry      = 'select cw_form_setting.label_name from cw_form_setting where cw_form_setting.prime_module_id in ("bank_details_verification") and cw_form_setting.label_name not in ("bank_app_status","employee_code","emp_name","role","bank_remarks") and cw_form_setting.trans_status = "1"';
			$bank_verify_data     = $this->db->query("CALL sp_a_run ('SELECT','$bank_verify_qry')");
			$bank_verify_rslt     = $bank_verify_data->result_array();
			$bank_verify_data->next_result();
			//BANK VERIFY INPUTS ARRAY 
			$bank_verify_arr      = array_column($bank_verify_rslt ?? [],"label_name","label_name");
			
			//ARRAY FOR DEFAULT BANK COLUMNS(MANDATORY COLUMNS) GET

			//--------------- BANK VERIFACTION ARRAY CREATION END--------------------
			$bank_val_line        = "";
			$bank_ins_col_arr     = array();
			//$bank_details_arr     = array();
			foreach($this->form_info as $setting){
				$field_type      = $setting->field_type;
				$input_view_type = (int)$setting->input_view_type;
				$label_id        = strtolower(str_replace(" ","_",$setting->label_name));
				$field_isdefault = $setting->field_isdefault;
				$date_type       = $setting->date_type;

				if((int)$field_type === 5){
					$value = trim($this->input->post($label_id));
					$pick_array[$label_id]  = $value;
				}else
				if((int)$field_type === 7){
					$multi_name = $label_id."[]";
					$multi_val_arr   = $this->input->post($multi_name);
					//EMPTY VALUES REMOVE FROM ARRAY
					if(!is_string($multi_val_arr)){ // [MS 07-12-2024]
						$multi_val_arr   = array_filter($multi_val_arr, function($value) { return !is_null($value) && $value !== ''; });
						$value = implode(",",$multi_val_arr ?? []);
					}else{
						$value = $multi_val_arr.',';
					}
				}else{
					$value = $this->input->post($label_id);
				}			
				if((int)$field_type === 4){
					if((int)$date_type === 1){
						if($value){
							$value = date('Y-m-d',strtotime($value));
						}					
					}else{
						$value = $value;
					}
				}else
				if((int)$field_type === 11){
					$value = trim($this->input->post($label_id));
					$pick_array[$label_id]  = $value;
				}else
				if((int)$field_type === 13){
					$value = date('Y-m-d H:i:s',strtotime($value));
				}else
				if((int)$field_type === 10){//File Upload
					$value 		 		 = $value;
					$remove_upload_fname = "old_".$label_id;
					$remove_upload_file  = $this->input->post($remove_upload_fname);
					if($value !== $remove_upload_file){
						unlink($remove_upload_file);  
					}
				}
				$value = str_replace('"',"~",$value);
				$value = str_replace("'","`",$value);
				$value = str_replace("&","^",$value);
				//Sanitize SQL InJection chars
			$value = $this->sanitize_input($value, $field_type);

			if(($input_view_type === 1) || ($input_view_type === 2)){
				if((int)$field_isdefault === 1){
						if($label_id !== "employee_code" && $label_id !== "sap_status"){
							$prime_qry_key     .= $label_id.",";
							$prime_qry_value   .= '"'.$value.'",';
							//FOR ONLY BANK INPUT MODIFY THEN UPDATE BY BANK STATUS
							if($label_id !== "bank_app_status"){
								$prime_upd_query   .= $label_id.' = "'.$value.'",';
							}
						}					
					}
					if($label_id === "emp_name"){
						$emp_name       = $value;
					}
					if($label_id === "ifsc_code"){
						$ifsc_code_hidden_329       = $value;
					}
					if($label_id === "bank_key"){
						$bank_key       = $value;
					}
					if($label_id === "role"){
						$role           = $value;
					}
					if($label_id === "sap_status"){
						$sap_status     = (int)$value;
					}
					$emp_log[$label_id]   = $value;
					$post_data[$label_id] = $value;
				}
				if($label_id === "emp_cost_center_code"){
					$cost_center_code = $value;
				}
				if($label_id === "stop_pay_code"){
					$stop_pay_code    = $value;
				}
				if($label_id === "hold_reason"){
					$hold_reason      = $value;
				}
				
				if(in_array($label_id,$bank_verify_arr)){
					if($label_id === "date_of_birth" || $label_id === "date_of_joining"){
						$get_cell_value = date('Y-m-d',strtotime($value));
						$bank_details_arr[$label_id]=$value;
					}else{
						$bank_details_arr[$label_id]=$value;
					}	
				}
			}
			
			//----------- STOP PAY AND HOLD REMARKS BASED VALIDATIONS CHECK START ----------
			if($stop_pay_code === "Y"){//STOP PAYMENT
				if($hold_reason === ""){
					echo json_encode(array('success' => FALSE, 'check' => "", 'message' => "Reason For Hold Input should not Empty.!"));
					exit(0);
				}
			}else
			if($stop_pay_code === "N"){//NO STOP PAYMENT
				if($hold_reason){
					echo json_encode(array('success' => FALSE, 'check' => "", 'message' => "Reason For Hold Input should be Empty.!"));
					exit(0);
				}
			}
			if(!$sap_status){
				echo json_encode(array('success' => FALSE, 'check' => "", 'message' => "SAP Status Should not be Empty..Please contact Admin..!"));
				exit(0);
			}
			if((int)$bank_key !== 9200){   //NB
				if(!$ifsc_code_hidden_329){ 
					echo json_encode(array('success' => FALSE, 'check' => "", 'message' => "Please choose IFSC code..!"));
					exit(0);
				}	
			}
			//----------- STOP PAY AND HOLD REMARKS BASED VALIDATIONS CHECK END -----------
			$payroll        = 0;
			if($cost_center_code === "" || $cost_center_code === "0"){
				$payroll    = 1;
			}
			$termination_status = (int)$this->input->post('termination_status');
			if($termination_status === 1){
				$resignation_date = $this->input->post('resignation_date');
				$separation_type  = $this->input->post('separation_type');
				if($resignation_date){
					if(!$separation_type){
						echo json_encode(array('success' => FALSE, 'check' => "", 'message' => "Seperation Type Should not Empty.!"));
						exit(0);
					}
				}
			}
			/*============ UDY EMPLOYEE CUSTOME BLOCK ============*/
			$user_name = $this->input->post('user_name');
			
			/*============ BSK EMPLOYEE CODE EXIST CHECK CUSTOME BLOCK START============*/
			$exist     = $this->is_exist($this->input->post('employee_code'));
			$exist     = explode("/",$exist ?? "");
			$id        = $exist[0];
			$num_rows  = $exist[1];
			if(((int)$id !== (int)$form_id) && ((int)$num_rows >= 1)){
				$emp_code   = $this->get_digits($this->input->post('role'));
				$user_name  = $emp_code;
				$code_exist = 1;
			}else{
				$emp_code = $this->input->post('employee_code');
				$code_exist = 2;
			}
			
			// $post_data['password']         = $password;
			$post_data['employee_code']    = $emp_code;
			$post_data['aadhar_no']        = $this->input->post('aadhar_card_no');
			/*============ BSK EMPLOYEE CODE EXIST CHECK CUSTOME BLOCK END============*/
			if($user_name !== '' && $user_name){
				$post_data['user_name']    = $user_name;
				$prime_qry_key     	      .= "user_name,";
				$prime_qry_value   	      .= '"'.$user_name.'",';
				$prime_upd_query   	      .= 'user_name = "'.$user_name.'",';
			}

			$access_data = $this->input->post('access') != NULL ? $this->input->post('access') : array();
			$grants_data = $this->input->post('grants') != NULL ? $this->input->post('grants') : array();		
			/*============ UDY EMPLOYEE CUSTOME BLOCK ============*/	

			/* =========== BSK Amendment Posting ================*/
			//Get Previous Data
			$from_query  = 'select '.implode(",",$post_array ?? []).' from cw_employees where cw_employees.trans_status = 1 and '. $this->prime_id .' = "'. $form_id .'" ';
			$form_data   = $this->db->query("CALL sp_a_run ('SELECT','$from_query')");
			$form_result = $form_data->result_array();
			$form_data->next_result();			
			$prev_data       = $form_result[0];
			$prev_bank_data  = array();
			foreach($prev_data as $key => $val){
				if(in_array($key,$prev_array)){
					if($key === 'resignation_date'){
						if($val === '0000-00-00' || $val === NULL){
							$previous_data[$key]="";						
						}
					}else{
						$previous_data[$key]=$val;
					}
				}else{
					$prev_bank_data[$key]=$val;
				}				
			}
			if($previous_data){
				$result          = array_intersect_key($post_data ?? [],$previous_data);		
				$arraycompare 	 = array_diff_assoc($result ?? [],$previous_data);	
			}
			if($prev_bank_data){
				$bank_result     = array_intersect_key($post_data ?? [],$prev_bank_data);		
				$bankcompare 	 = array_diff_assoc($bank_result ?? [],$prev_bank_data);	
			}

			//------------------------ FOR BANK APPROVAL PROCESS START ------------------
			$bank_app_status       = $this->input->post('bank_app_status');
			$old_bank_details_qry  = 'select bank_account_number,bank_key,ifsc_code,personal_code,project_id,date_of_birth,date_of_joining,aadhar_card_no,wbs_element,position,activity_no from cw_employees where employee_code ="'.$emp_code.'"';
			$old_bank_info         =  $this->db->query("CALL sp_a_run ('SELECT','$old_bank_details_qry')");
			$old_bank_rslt         = $old_bank_info->result();
			$old_bank_info->next_result();
			//------------------------ FOR BANK APPROVAL PROCESS END ------------------
			/* =========== BSK Amendment Posting ================*/
			$created_on = date("Y-m-d H:i:s");
			$emp_data = array();
			if($this->check_emp_code($emp_code,$form_id)){
				if((int)$form_id === 0){
					$post_json_data     = json_encode($post_data);
					//if sap status completed then only should insert
					//function for validate a unique and mandatory field via mysql stored procedure
					$error_sts_arr      = $this->unique_procedure_valid($post_json_data);
					if($error_sts_arr[0] === 1){
						$prime_qry_key     .= "employee_code,sap_status,payroll,trans_created_by,trans_created_date";
						$prime_qry_value   .= '"'.$emp_code.'","'.$sap_status.'","'.$payroll.'","'.$this->logged_id.'",'.'"'.$created_on.'"';
						$prime_insert_query = "insert into $this->prime_table ($prime_qry_key) values ($prime_qry_value)";
						$insert_info        = $this->db->query("CALL sp_a_run ('INSERT','$prime_insert_query')");
						$insert_result      = $insert_info->result();
						$insert_info->next_result();

						$insert_id = $insert_result[0]->ins_id;		

						/*== UDY CUSTOME BLOCK ==*/
						if($grants_data){
							$this->Module->update_grants($this->control_name,$insert_id,$grants_data,$access_data);
						}
						/*== UDY CUSTOME BLOCK ==*/
						$this->esi_statutory_elig($role,$emp_code);
						
						echo json_encode(array('success' => TRUE, 'check' => "", 'message' => "Successfully added.. Your Employee Code is $emp_code $send_mail_status", 'insert_id' => $insert_id,'code_exist'=>$code_exist,'emp_code'=>$emp_code));
					}else{
						echo json_encode(array('success' => FALSE, 'check' => "Procedure", 'message' => "Validation Check Error..?","table_info" => $error_sts_arr));
						exit(0);
					}
				}else{
					$post_json_data     = json_encode($post_data);
					//if sap status completed then only should update					
					//function for validate a unique and mandatory field via mysql stored procedure
					$error_sts_arr      = $this->unique_procedure_valid($post_json_data);

					if($error_sts_arr[0] === 1){
						//log inserted for employee table
						$this->employee_log($form_id,$emp_log);	
						//BANK DETAILS INSERT QUERY START
						if(!empty($bankcompare) || (int)$bank_app_status === 3){
							$qry         = 'SELECT employee_code,emp_name,role FROM `cw_employees` where employee_code = "'.$emp_code.'" and trans_status = 1';
							$code_info   = $this->db->query("CALL sp_a_run ('SELECT','$qry')"); // [MS 10-12-2024]
							$code_result = $code_info->result();
							$code_info->next_result();
							 $this->bank_details_verification_upd($old_bank_rslt,$bank_details_arr,$code_result);
							//COLUMNS FOR USING FOR EMPLOYEE MASTER UPDATE QUERY
							$bank_app_stat_qry  = ',bank_app_status = "1"';
						}
						//BANK DETAILS INSERT QUERY END		
						if($arraycompare){
							$sap_upd_status  = 'sap_upd_status="1",';
						}else{
							$sap_upd_status  = '';
						}			
						$prime_upd_query    .= 'employee_code = "'.$emp_code.'",sap_status = "'.$sap_status.'",payroll = "'.$payroll.'",trans_updated_by = "'. $this->logged_id .'",'.$sap_upd_status.' trans_updated_date = "'.$created_on.'"'.$bank_app_stat_qry;
						$prime_update_query  = 'UPDATE '. $this->prime_table .' SET '. $prime_upd_query .' WHERE '. $this->prime_id .' = "'. $form_id .'"';

						$this->db->query("CALL sp_a_run ('UPDATE','$prime_update_query')");
						/*== UDY CUSTOME BLOCK ==*/  
						if($grants_data){
							$this->Module->update_grants($this->control_name,$form_id,$grants_data,$access_data);
						}
						if($arraycompare){
							$sap_post_qry = 'INSERT INTO uds_middleware.cw_employees_update(employee_code,'.implode(",",array_keys($arraycompare ?? []) ?? []).') VALUES("'.$emp_code.'","'.implode('","',array_values($arraycompare ?? []) ?? []).'")';
							$this->db->query("CALL sp_a_run ('RUN','$sap_post_qry')");
						}
						echo json_encode(array('success' => TRUE, 'message' => "Successfully updated $send_mail_status",'insert_id' => $form_id,'code_exist'=>$code_exist,'emp_code'=>$emp_code, 'check' => ""));
					}else{
						echo json_encode(array('success' => FALSE, 'check' => "Procedure", 'message' => "Validation Check Error..?","table_info" => $error_sts_arr));
						exit(0);
					}
				}
			}else{
				echo json_encode(array('success' => FALSE, 'check' => "", 'message' => "Employee Code Already Exists",'category_status'=>TRUE, 'check' => ""));
			}
		}		
	}	
	
	public function check_print_design_exists(){
		$design_query  = 'SELECT count(*) rlst_count FROM cw_print_design inner join cw_print_info on cw_print_info.prime_print_info_id = cw_print_design.print_design_for WHERE print_info_module_id = "employees" and cw_print_design.trans_status = 1 and cw_print_info.print_type IN ("4","5","6","7")';
		$design_query   = $this->db->query("CALL sp_a_run ('SELECT','$design_query')");
		$design_result  = $design_query->result();
		$design_query->next_result();
		$rlst_count  = $design_result[0]->rlst_count;
		if((int)$rlst_count === 4){
			return true;
		}else{
			return false;
		}
	}
	// public function load_print_info($category,$emp_code,$print_type,$view_id,$unpunched_date){
	// 	$design_query  = 'SELECT prime_print_info_id,print_design,print_info_for,print_info_module_id,print_type,print_info_name FROM cw_print_design inner join cw_print_info on cw_print_info.prime_print_info_id = cw_print_design.print_design_for WHERE FIND_IN_SET("'.$category.'",print_info_for) and print_info_module_id = "employees" and cw_print_design.trans_status = 1 and cw_print_info.print_type = "'.$print_type.'"';
	// 	$design_query   = $this->db->query("CALL sp_a_run ('SELECT','$design_query')");
	// 	$design_result  = $design_query->result();
	// 	$design_query->next_result();
	// 	echo "";
	// 	$print_doc_id  = $design_result[0]->prime_print_info_id;
	// 	$print_design  = $design_result[0]->print_design;
	// 	$print_type    = $design_result[0]->print_type;
	// 	$style  = "<style>
	// 	table{
	// 		border: 1px !important;
	// 		border-collapse: collapse !important;
	// 		empty-cells: show !important;
	// 		max-width: 100% !important;
	// 		font-size: 13px !important;
	// 	}
	// 	tbody {
	// 		border: 1px !important;
	// 		border-collapse: collapse !important; 
	// 		empty-cells: show !important;
	// 		max-width: 100% !important;
	// 		font-size: 13px !important;
	// 	}
	// 	td, th {
	// 		border: 1px solid #000 !important;
	// 		font-size: 13px !important;
	// 	}
	// 	td.fr-thick,th.fr-thick {
	// 		border-width: 2px !important;
	// 	}
	// 	table.fr-dashed-borders td, table.fr-dashed-borders th {
	// 		border-style: dashed !important;
	// 	}
	// 	</style>";
	// 	$print_design  = $style."".$print_design;
	// 	$print_design  = str_replace('~','"',$print_design);
	// 	$block_qry    = 'select * from cw_print_block where print_block_for = "'.$print_doc_id.'" and trans_status = 1';
	// 	$block_data   = $this->db->query("CALL sp_a_run ('SELECT','$block_qry')");
	// 	$block_result = $block_data->result();
	// 	$block_data->next_result();
	// 	foreach($block_result as $block){
	// 		$prime_print_block_id  = $block->prime_print_block_id;
	// 		$print_block_name      = $block->print_block_name;
	// 		$print_block_type      = (int)$block->print_block_type;
	// 		$print_block_table     = $block->print_block_table;
	// 		$print_block_column    = $block->print_block_column;
	// 		$suppressed_data       = $block->suppressed_data;
	// 		$cumulative_data       = $block->cumulative_data;
			
	// 		$table_qry    = 'select * from cw_print_table where print_table_for_id = "'.$prime_print_block_id.'" and trans_status = 1';
	// 		$table_data   = $this->db->query("CALL sp_a_run ('SELECT','$table_qry')");
	// 		$table_result = $table_data->result();
	// 		$table_data->next_result();
	// 		$line_table_query = "";
	// 		$cutome_table_check = array('transactions'=>'cw_transactions');
	// 		foreach($table_result as $table){
	// 			$line_prime_table      = $table->line_prime_table;
	// 			$line_prime_col        = $table->line_prime_col;
	// 			$line_join_type        = $table->line_join_type;
	// 			$line_join_table       = $table->line_join_table;
	// 			$line_join_col         = $table->line_join_col;
	// 			$line_sort             = $table->line_sort;
	// 			$module_name           = str_replace("cw_","",$line_prime_table);
	// 			$prime_id              = "prime_".$module_name."_id";
	// 			$cf_id                 = "prime_".$module_name."_cf_id";
	// 			$cf_table_name         = $this->db->dbprefix($module_name."_cf");
	// 			$join_module_name      = str_replace("cw_","",$line_join_table);
	// 			$join_prime_id         = "prime_".$join_module_name."_id";
	// 			$join_cf_id            = "prime_".$join_module_name."_cf_id";
	// 			$join_cf_table_name    = $this->db->dbprefix($join_module_name."_cf");	
	// 			if((int)$line_sort === 1){
	// 				if($cutome_table_check[$module_name]){
	// 					$line_prime_table = " $line_prime_table ";
	// 				}else{
	// 					$line_prime_table = " $line_prime_table inner join $cf_table_name on $line_prime_table.$prime_id = $cf_table_name.$prime_id ";
	// 				}
	// 				if($cutome_table_check[$join_module_name]){
	// 					$line_join_table = " $line_join_table on $line_join_col = $line_prime_col";
	// 				}else{
	// 					$line_join_table = " $line_join_table on $line_join_col = $line_prime_col inner join  $join_cf_table_name on $line_join_table.$join_prime_id = $join_cf_table_name.$join_prime_id ";
	// 				}
	// 				$line_table_query .= " $line_prime_table  $line_join_type join $line_join_table"; 
	// 			}else{
	// 				if($cutome_table_check[$join_module_name]){
	// 					$line_table_query .= " $line_join_type join $line_join_table on $line_join_col = $line_prime_col "; 
	// 				}else{
	// 					$line_table_query .= " $line_join_type join $line_join_table on $line_join_col = $line_prime_col inner join  $join_cf_table_name on $line_join_table.$join_prime_id = $join_cf_table_name.$join_prime_id "; 
	// 				}
	// 			}
	// 		}
	// 		if(!$line_table_query){
	// 			$module_name      = str_replace("cw_","",$print_block_table);
	// 			$prime_id         = "prime_".$module_name."_id";
	// 			$cf_id            = "prime_".$module_name."_cf_id";
	// 			$cf_table_name    = "cw_".$module_name."_cf";
	// 			$line_table_query = " $print_block_table ";
	// 		}
	// 		if(!$print_block_column){
	// 			$print_block_column = "*";
	// 		}else{
	// 			$select_query = "";
	// 			$select_ytd_query = "";
	// 			$pick_query   = "";
	// 			$map_column = explode(",",$print_block_column);
	// 			foreach($map_column as $table_column){
	// 				$map_column   = explode(".",$table_column);
	// 				$table_name   = $map_column[0];
	// 				$column 	  = $map_column[1];
	// 				$control_name = str_replace('cw_',"",$table_name);
	// 				if($control_name === "transactions"){
	// 					$control_name = "employees";
	// 				}
	// 				$form_qry    = 'select prime_form_id,view_name,label_name,field_type,pick_list_type,pick_list,pick_table,auto_prime_id,auto_dispaly_value from cw_form_setting where prime_module_id = "'.$control_name.'" and  label_name = "'.$column.'"  and trans_status = "1"';
	// 				$form_data   = $this->db->query("CALL sp_a_run ('SELECT','$form_qry')");
	// 				$form_result = $form_data->result();
	// 				$form_data->next_result();
	// 				foreach($form_result as $form){
	// 					$prime_form_id  = (int)$form->prime_form_id;
	// 					$view_name      = $form->view_name;
	// 					$label_name     = $form->label_name;
	// 					$field_type     = (int)$form->field_type;
	// 					$pick_list_type = (int)$form->pick_list_type;
	// 					$pick_list      = $form->pick_list;
	// 					$pick_table     = $form->pick_table;
	// 					$auto_prime_id      = $form->auto_prime_id;
	// 					$auto_dispaly_value = $form->auto_dispaly_value;
	// 					if((int)$field_type === 4){
	// 						$select_query .= 'DATE_FORMAT('.$table_name.'.'.$label_name.', "%d-%m-%Y") as '.$label_name.' , ';
	// 					}else
	// 					if(($field_type === 5) || ($field_type === 7)){
	// 						if($pick_list_type === 1){
	// 							$pick_list_val   = explode(",",$pick_list ?? "");
	// 							$pick_list_val_1 = $pick_list_val[0];
	// 							$pick_list_val_2 = $pick_list_val[1];
								
	// 							$pick_query_as = $pick_table."_".$prime_form_id;
	// 							$select_query .= "$pick_query_as.$pick_list_val_2 as $label_name , ";
	// 							$pick_query .= " left join $pick_table as $pick_query_as on $pick_query_as.$pick_list_val_1 = $table_name.$label_name ";
	// 						}else
	// 						if($pick_list_type === 2){ 
	// 							$pick_list_val_1 = $pick_table."_id";
	// 							$pick_list_val_2 = $pick_table."_value";
	// 							$pick_list_val_3 = $pick_table."_status";
								
	// 							$pick_query_as = $pick_table."_".$prime_form_id;
	// 							$select_query .= "$pick_query_as.$pick_list_val_2 as $label_name , ";
	// 							$pick_query   .= " left join $pick_table as $pick_query_as on $pick_query_as.$pick_list_val_1 = $table_name.$label_name ";
	// 						}
	// 					}else
	// 					if($field_type === 9){
	// 						$pick_query_as = $pick_table."_".$prime_form_id;
	// 						$select_query .= "$pick_query_as.$auto_dispaly_value as $label_name,";
	// 						$pick_query .= " left join $pick_table as $pick_query_as on $pick_query_as.$auto_prime_id = $table_name.$label_name ";
	// 					}else
	// 					if(($field_type === 2) || ($field_type === 3)){
	// 						$label_ytd  =	$label_name."_ytd";
	// 						$select_ytd_query .= "sum($table_name.$label_name) as $label_ytd, ";
	// 						$select_query .= "$table_name.$label_name , ";
	// 					}else{
	// 						$select_query .= "$table_name.$label_name , ";
	// 					}
	// 				}					
	// 			}
	// 		}
	// 		$where_trans = "";
	// 		$where_trans_info = explode(",",$print_block_table);
	// 		foreach($where_trans_info as $trans_info){
	// 			if($trans_info === "cw_transactions"){
	// 				$select_query .= "cw_transactions.transactions_month , ";
	// 			}				
	// 			$where_trans .= "$trans_info.trans_status = 1 and ";
	// 		}
	// 		$where_trans = rtrim($where_trans,'and ');
	// 		$where_qry    = 'select * from cw_print_table_where where where_for_id = "'.$prime_print_block_id.'" and trans_status = 1';
	// 		$where_data   = $this->db->query("CALL sp_a_run ('SELECT','$where_qry')");
	// 		$where_result = $where_data->result();
	// 		$where_data->next_result();
	// 		$where_condition = "";
	// 		if($where_result){
	// 			$where_condition = str_replace('^','"',$where_result[0]->where_condition);
	// 			$where_condition = str_replace('@logged_id@',$view_id,$where_condition);				
	// 			$session_date_list  = array("logged_DMY"=>"d-m-Y","logged_YMD"=>"Y-m-d","logged_MY"=>"m-Y","logged_YM"=>"Y-m","logged_Y"=>"Y"); 
	// 			$session_query      = 'select session_value from cw_session_value where session_for = 1 and trans_status = "1"';
	// 			$session_data       = $this->db->query("CALL sp_a_run ('SELECT','$session_query')");
	// 			$session_result     = $session_data->result();
	// 			$session_data->next_result();
	// 			foreach($session_result as $rslt){
	// 				$session_value 	   = $rslt->session_value;
	// 				if($session_value !== "access_data"){
	// 					$exist_val = "@".$session_value."@";
	// 					if($session_date_list[$session_value]){
	// 						$date_formate      = $session_date_list[$session_value];
	// 						$saved_session_val = date($date_formate);
	// 					}else{
	// 						$saved_session_val = $this->session->userdata($session_value);
	// 					}
	// 					$where_condition  = str_replace($exist_val,$saved_session_val,$where_condition);
	// 				}
	// 			}
	// 		}else{
	// 			$where_condition  = " and cw_employees.employee_code = $emp_code";
	// 		}
	// 		$select_query = rtrim($select_query,',');
	// 		$select_query = rtrim($select_query,' , ');
	// 		if((int)$cumulative_data === 1){
	// 			$start_fin_date = $this->financial_info[0]->start_date;
	// 			$start_fin_date = date('m-Y',strtotime($start_fin_date));
	// 			$end_fin_date   = $this->financial_info[0]->end_date;
	// 			$end_fin_date   = date('m-Y',strtotime($end_fin_date));
	// 			$select_ytd_query = rtrim($select_ytd_query,',');
	// 			$select_ytd_query = rtrim($select_ytd_query,' , ');
	// 			$where_ytd_condition  = ' and date_format(str_to_date(transactions_month, "%m-%Y") , "%Y-%m")  >= date_format(str_to_date("'.$start_fin_date.'", "%m-%Y"), "%Y-%m") and date_format(str_to_date(transactions_month, "%m-%Y") , "%Y-%m")  <= date_format(str_to_date("'.$end_fin_date.'", "%m-%Y"), "%Y-%m")';
	// 			$final_ytd_qry = "select $select_ytd_query from $line_table_query $pick_query  where $where_trans $where_condition  $where_ytd_condition";
	// 			$final_ytd_data   = $this->db->query("CALL sp_a_run ('SELECT','$final_ytd_qry')");
	// 			$final_ytd_result = $final_ytd_data->result();
	// 			$final_ytd_data->next_result();
	// 			foreach($final_ytd_result as $ytd_rslt){
	// 				$map_column = explode(",",$print_block_column);
	// 				foreach($map_column as $table_column){
	// 					$map_column   = explode(".",$table_column);
	// 					$ytd_column 	  = $map_column[1]."_ytd";
	// 					$ytd_value        = $ytd_rslt->$ytd_column;
	// 					$replace_ytd_val  = "@".$ytd_column."@";
	// 					$print_design     = str_replace($replace_ytd_val,$ytd_value,$print_design);
	// 				}
	// 			}
	// 		}
	// 		$final_qry = "select $select_query from ".$line_table_query." $pick_query where $where_trans $where_condition";
	// 		$final_data   = $this->db->query("CALL sp_a_run ('SELECT','$final_qry')");
	// 		$final_result = $final_data->result();
	// 		$final_data->next_result();
	// 		$tr_line = "";
	// 		$th_line = "";
	// 		$count = 0;
	// 		$assign_date_formate_list  = array("DMY"=>"d-m-Y","YMD"=>"Y-m-d","DFY"=>"d F Y","MY"=>"F-Y","YM"=>"Y-F","D"=>"d","M"=>"M","Y"=>"Y");
	// 		$split_qry    = 'select * from cw_print_split where trans_status = 1 and split_table_info ="'.$print_doc_id.'"';
	// 		$split_data   = $this->db->query("CALL sp_a_run ('SELECT','$split_qry')");
	// 		$split_result = $split_data->result();
	// 		$split_data->next_result();
	// 		$split_array = array();
	// 		foreach($split_result as $split){
	// 			$split_info  = $split->split_info;
	// 			$split_colum = $split->split_colum;
	// 			$split_array[$split_colum] = $split_info;
	// 		}		
	// 		if($final_result){
	// 			$data['print_sts'] = true;
	// 			foreach($final_result as $rslt){
	// 				$count++;
	// 				$map_column = explode(",",$print_block_column);
	// 				$td_line = "";
	// 				foreach($map_column as $table_column){
	// 					$map_column   = explode(".",$table_column);
	// 					$column 	  = $map_column[1];
	// 					$value        = $rslt->$column;
	// 					$replace_val  = "@".$column."@";
	// 					//amount number is changed to in words for net pays--07SEP2019
	// 					if($column == 'net_pay'){
	// 						$value         = $rslt->$column;
	// 						$print_design  = str_replace($replace_val,$value,$print_design);
	// 						$net_pay_val   = $value;
	// 						$net_pay_words = $this->numbertowords($net_pay_val);
	// 						$net_pay_words = strtoupper($net_pay_words);
	// 						$print_design  = str_replace("@net_pay_words@",$net_pay_words,$print_design);
	// 					}else
	// 					if($column == 'employee_name'){
	// 						$value         = ucwords($rslt->$column);
	// 						$print_design  = str_replace($replace_val,$value,$print_design);
	// 					}else
	// 					if($column == 'reporting_person'){
	// 						$value         = ucwords($rslt->$column);
	// 						$print_design  = str_replace($replace_val,$value,$print_design);
	// 					}else
	// 					if($column == 'salary'){
	// 						$value         = $rslt->$column;
	// 						$print_design  = str_replace($replace_val,$value,$print_design);
	// 						$salary_val   = $value;
	// 						$salary_words = $this->numbertowords($salary_val);
	// 						$salary_words = ucwords($salary_words);
	// 						$print_design  = str_replace("@salary_words@",$salary_words,$print_design);
	// 					}
						
	// 					if(isset($split_array[$replace_val])){
	// 						//Process split informtion 
	// 						$process_function = $split_array[$replace_val];
	// 						if((int)$process_function === 1){
	// 							$transactions_month = $final_result[0]->transactions_month;
	// 							$employee_code      = $final_result[0]->employee_code;
	// 							$loan_info = $this->get_loan_value($transactions_month,$employee_code);
	// 							$print_design = str_replace($replace_val,$loan_info,$print_design);
	// 						}
	// 					}else{
	// 						if($print_block_type === 1){
	// 							$print_design = str_replace($replace_val,$value,$print_design);
	// 							foreach($assign_date_formate_list as $key=>$formate){
	// 								if($column == 'transactions_month'){//transactions month static updated
	// 									$start         = "@".$key."_";
	// 									$end           = "_".$key."@";
	// 									$replace_val   = $start.$column.$end;
	// 									$value         = date('Y-m-d',strtotime("01-".$rslt->$column));
	// 									$date_value    = date_create($value);
	// 									$replace_value = strtoupper(date_format($date_value,$formate));
	// 									$print_design  = str_replace($replace_val,$replace_value,$print_design);
	// 								}else{//not static month updated
	// 									$start         = "@".$key."_";
	// 									$end           = "_".$key."@";
	// 									$replace_val   = $start.$column.$end;
	// 									$replace_val   = $start.$column.$end;
	// 									$date_value    = date_create($value);
	// 									$replace_value = date_format($date_value,$formate);
	// 									$print_design  = str_replace($replace_val,$replace_value,$print_design);
	// 								}
	// 							}
	// 						}else
	// 						if($print_block_type === 2){
	// 							$td_line .= "<td style='text-align:center;'>$value</td>";
	// 						}
	// 						if($count === 1){
	// 							$head_name = ucwords(str_replace("_"," ",$column));
	// 							$th_line .= "<th style='text-align:center;'>$head_name</th>";
	// 						}
	// 					}
	// 				}
	// 				if($print_block_type === 2){
	// 					if($count === 1){
	// 						$th_line  = "$th_line";
	// 					}
	// 					$tr_line .= "<tr>$td_line</tr>";
	// 				}
	// 			}
	// 			if($print_block_type === 2){
	// 				$table_list  = "<table style='width:100%;'><thead>$th_line</thead><tbody>$tr_line</tbody></table>";
	// 				$replce_block = "@".strtolower(str_replace(" ","_",$print_block_name))."@";
	// 				$print_design = str_replace($replce_block,$table_list,$print_design);
	// 			}
	// 		}
	// 	}
	// 	$print_design = str_replace("<br>","",$print_design);
	// 	$print_design = str_replace("@today_date@",$unpunched_date,$print_design);
	// 	$table_data = "<!DOCTYPE html><html> <body>".$print_design."</body></html>";
		
	// 	// Load pdf library
    //     $this->load->library('pdf');
	// 		// Load HTML content 
	// 	$this->dompdf->loadHtml($table_data);
	// 		// Render the HTML as PDF
	// 	$this->dompdf->render();
	// 		// Output the generated PDF (1 = download and 0 = preview)
	// 	$output = $this->dompdf->output();
		
	// 	$design_name = strtolower(str_replace(" ","_",$design_result[0]->print_info_name));
		
	// 	//new permission changes
	// 	$folder     = "time_office_mail";
	// 	$folder1    = $design_name;
	// 	$pdf_name   = $emp_code;
	// 	$final_html = $output;
	// 	$oldmask = umask(0);
	// 	if (!file_exists($folder)){
	// 		mkdir($folder, 0777, true);
	// 	}
	// 	if (!file_exists($folder."/".$folder1)){
	// 		mkdir($folder."/".$folder1, 0777, true);
	// 	}
	// 	//Check File Exist
	// 	if(file_exists($folder."/".$folder1."/".$pdf_name.".pdf")){
	// 		chmod($folder."/".$folder1."/".$pdf_name.".pdf", 0777);
	// 		unlink($folder."/".$folder1."/".$pdf_name.".pdf");
	// 	}
	// 	file_put_contents($folder."/".$folder1."/".$pdf_name.".pdf" , $final_html);
	// 	chmod($folder."/".$folder1."/".$pdf_name.".pdf", 0777);
	// 	umask($oldmask);
	// 	$path = $folder."/".$folder1."/".$pdf_name.".pdf";
	// 	chmod($path, 0777, true);
	// 	return $path;
	// }
	
	/*============ BSK EMPLOYEE CODE GENERATION CUSTOME BLOCK START============*/
	public function is_exist($employee_code){
		$search_query   = 'select * from cw_employees where employee_code = "'.$employee_code.'"';
		$search_info    = $this->db->query("CALL sp_a_run ('RUN','$search_query')");
		$result  = $search_info->result();		
		$search_info->next_result();
		$num_rows      = $search_info->num_rows();
		$id            = $result[0]->prime_employees_id;
		$data          = "$id/$num_rows";
		return $data;
	}
	
	public function get_employee_code(){
		$encString         = file_get_contents('php://input');
		$_POST             = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'Invalid Request..','table_data' => ""));
			exit(0);
		}
		$role                  = $this->input->post('role');
		$check_code_gen_qry    = 'select code_type from cw_employee_code_auto where trans_status = 1';
		$check_code_gen_data   = $this->db->query("CALL sp_a_run ('SELECT','$check_code_gen_qry')");
		$check_code_gen_result = $check_code_gen_data->result();
		$check_code_gen_data->next_result();
		$code_gen_mode   = $check_code_gen_result[0]->code_type;
		$sts = 0;
		if((int)$code_gen_mode === 1){
			$sts = 1;
			$result = $this->get_digits($role);
			if($result){
				echo json_encode(array('success' => TRUE, 'sts' => $sts, 'digits' => $result));
			}else{
				echo json_encode(array('success' => FALSE, 'sts' => $sts, 'message' => "Employee Code Auto Not Updated for this role"));
			}
		}else{
			echo json_encode(array('sts' => $sts,'message' => "Manually enter the  Employee code"));
		}
	}
	
	public function get_digits($role){
		$select_qry    = 'select * from cw_employee_code_auto where (category = "'.$role.'" or category = "All") and trans_status = 1';

		$select_data   = $this->db->query("CALL sp_a_run ('SELECT','$select_qry')");
		$select_result = $select_data->result();
		$select_data->next_result();
		$num_rows      = $select_data->num_rows();
		$prefix        = $select_result[0]->prefix;
		$start_value   = $select_result[0]->start_value;
		$category      = $select_result[0]->category;
		$prefix_count  = 0;
		$prefix_qry = "";
		if($prefix){
			$prefix = strtoupper($prefix);
			$prefix_count = strlen($prefix);
			$prefix_qry = ' and employee_code like "%'.$prefix.'%"';
		}
		if($category === "All"){
			$emp_count_qry = 'select MAX(employee_code) as employee_code from cw_employees where prime_employees_id != 1 '.$prefix_qry;
		}else{
			$emp_count_qry = 'select MAX(employee_code) as employee_code from cw_employees where role = "'.$role.'" and prime_employees_id != 1 and employee_code != ""'.$prefix_qry;
		}		
		$emp_count_data    = $this->db->query("CALL sp_a_run ('SELECT','$emp_count_qry')");
		$emp_count_result  = $emp_count_data->result();
		$emp_count_data->next_result();
		$max_count         = $emp_count_result[0]->employee_code;	
		if($max_count){
			if((int)$num_rows > 0){
				$max_count = substr($max_count,$prefix_count);
				$digits    = $max_count +1;
				return $prefix."".$digits;
			}else{
				return false;
			}
		}else{
			return $prefix.$start_value;
		}
	}
	
  /*public function digit_check($prefix,$start_value,$max_count){
		$number_of_digits = strlen((string)$max_count);
		$new_count        = $max_count +1;		
		$number_of_digits = "-".$number_of_digits;
		$num              =  substr($start_value, 0, $number_of_digits).$new_count;
		if($prefix){
			return $prefix."".$num;
		}else{
			return $num;
		}		
	}*/
	
	/*============ BSK EMPLOYEE CODE GENERATION CUSTOME BLOCK END============*/

	//UPDATE STATUS TO DELETE IN MODULE PRIMARY TABLE
	public function delete(){
		//Encryption
		$encString      = file_get_contents('php://input');
		$_POST          = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'Invalid Request..','table_data' => ""));
			exit(0);
		}
		$delete_ids    = implode(",",$this->input->post('delete_ids') ?? []);
		$can_process   = TRUE;
		$delete_status = FALSE;
		if($this->check_delete_status()){
			$delete_status = TRUE;
			$check_table_query  = 'SELECT GROUP_CONCAT(prime_module_id) as prime_module_id,GROUP_CONCAT(label_name) as label_name from cw_form_setting WHERE pick_table = "'. $this->prime_table .'" and  trans_status = 1 ';
			$check_table_info   = $this->db->query("CALL sp_a_run ('SELECT','$check_table_query')");
			$check_table_rlst   = $check_table_info->row();
			$check_table_info->next_result();
			if($check_table_rlst->prime_module_id){
				$prime_module_id         = explode(",",$check_table_rlst->prime_module_id ?? "");
				$label_name              = explode(",",$check_table_rlst->label_name ?? "");
				$i                       = 0;
				foreach($prime_module_id as $check_modules){
					$table_name          = "cw_".$check_modules;
					$select_table        = "$table_name.$label_name[$i]";
					$select_where        = " and $table_name.$label_name[$i] in ($delete_ids)";
					$check_module_query  = 'SELECT '.$select_table.' from '.$table_name.' WHERE '.$table_name.'.trans_status = 1 '.$select_where.' LIMIT 0,1'; 
					$check_module_info   = $this->db->query("CALL sp_a_run ('SELECT','$check_module_query')");
					$values_count        = $check_module_info->num_rows();
					$check_module_info->next_result();
					if((int)$values_count > 0){
						$table_names  .= "$check_modules,";
						$can_process   = False;
						$delete_status = False;
					}
					$i++;
				}				
			}
			$table_names = rtrim($table_names,",");
			if($delete_status){
				$delete_query  = 'DELETE FROM '. $this->prime_table .'  WHERE '. $this->prime_id .' in ('. $delete_ids .')';
				if($this->db->query("CALL sp_a_run ('RUN','$delete_query')")){
					$row_set_query   = 'SELECT form_view_label_name from cw_form_view_setting where form_view_type = "3" and prime_view_module_id = "'. $this->control_name .'" and trans_status = 1';
					$row_set_info    = $this->db->query("CALL sp_a_run ('SELECT','$row_set_query')");
					$row_count       = (int)$row_set_info->num_rows();
					$row_set_info->next_result();
					if($row_count !== 0){
						$row_set_result         = $row_set_info->result();
						$delete_table_name      = '';
						$delete_table_condition = '';
						foreach($row_set_result as $row_set){
							$row_set_table_name      = "cw_".$this->control_name."_".$row_set->form_view_label_name;
							$delete_table_name      .= "$row_set_table_name,";
							$delete_table_condition .= " $row_set_table_name.$this->prime_id  in ('$delete_ids') and";
						}
						$delete_table_name           = rtrim($delete_table_name,',');
						$delete_table_condition      = rtrim($delete_table_condition,'and');
						$delete_row_set_query  = 'DELETE FROM '. $delete_table_name .'  WHERE '. $delete_table_condition.'';
						$this->db->query("CALL sp_a_run ('RUN','$delete_row_set_query')");						
					}
					$can_process = False;
				}
				
			}
		}
		if($can_process){
			$created_on = date("Y-m-d h:i:s");
			$prime_upd_query    .= 'trans_deleted_by = "'. $this->logged_id .'",trans_deleted_date = "'.$created_on.'"';
			$prime_update_query  = 'UPDATE '. $this->prime_table .' SET trans_status = 0,'. $prime_upd_query .' WHERE '. $this->prime_id .' in ('. $delete_ids .')';
			if($this->db->query("CALL sp_a_run ('UPDATE','$prime_update_query')")){
				echo json_encode(array('success' => TRUE, 'message' => "Successfully Deleted"));
			}else{
				echo json_encode(array('success' => FALSE, 'message' => "Unable to delete"));
			}
		}else
		if($delete_status){
			echo json_encode(array('success' => TRUE, 'message' => "Successfully Deleted"));
		}else{
			$modules = ucwords($check_table_rlst->prime_module_id);
			echo json_encode(array('success' => FALSE, 'message' => "Unable to delete, This value is already used in $table_names modules"));
		}
	}
	
	//CHECK UNIQUE FIELD STATUS
	public function check_delete_status(){
		$check_delete_query  = 'SELECT GROUP_CONCAT(unique_field) as unique_field from cw_form_setting WHERE prime_module_id = "'. $this->control_name .'" and  trans_status = 1 ';
		$check_delete_info   = $this->db->query("CALL sp_a_run ('SELECT','$check_delete_query')");
		$check_delete_rlst   = $check_delete_info->row();
		$check_delete_info->next_result();
		$unique_info         = explode(",",$check_delete_rlst->unique_field ?? "");
		if(in_array('1', $unique_info)){
			return TRUE;
		}else{
			return FALSE;
		}
	}
	

	//UPDATE STATUS TO DELETE FOR UPLOAD FILES or DOCUMENTS
	public function remove_file(){
		$encString      = file_get_contents('php://input');
		$_POST          = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'Invalid Request..','table_data' => ""));
			exit(0);
		}
		$prime_id_val   = $this->input->post('prime_id_val');
		$is_defult      = (int)$this->input->post('is_defult');
		$input_name     = $this->input->post('input_name');
		$input_val      = $this->input->post('input_val');
		if($input_val){
			chmod($input_val, 0777);
			unlink($input_val);
		}
		$table_name = '';
		if($is_defult === 1){
			$table_name = $this->prime_table;
		}else
		if($is_defult === 2){
			$table_name = $this->cf_table;
		}
		if($table_name){
			$created_on    = date("Y-m-d h:i:s");
			$set_query     = $input_name .' = "" ,trans_updated_by = "'. $this->logged_id .'",trans_updated_date = "'.$created_on.'"';
			$update_query  = 'UPDATE '.$table_name .' SET '. $set_query .' WHERE '. $this->prime_id .' = "'. $prime_id_val .'"';
			$this->db->query("CALL sp_a_run ('UPDATE','$update_query')");
			echo json_encode(array('success' => TRUE, 'message' => "Successfully updated"));
		}else{
			echo json_encode(array('success' => FALSE, 'message' => "Unable to process your request"));
		}
	}
	
	//IMPORT FILE VIEW INFORMATION
	public function import(){
		$data['module_id']     = $this->control_name;
		$data['encKey']        = $this->generateKey();	
		$excel_format_qry = 'select prime_excel_format_id,excel_name from cw_util_excel_format where excel_module_id = "'.$this->control_name.'" and trans_status = 1';
		$excel_format   = $this->db->query("CALL sp_a_run ('SELECT','$excel_format_qry')");
		$excel_result    = $excel_format->result();
		$excel_format->next_result();
		$excel_format_drop[""] = "---- Excel Format ----";
		foreach($excel_result as $excel){
			$prime_excel_format_id = $excel->prime_excel_format_id;
			$excel_name            = $excel->excel_name;
			$excel_format_drop[$prime_excel_format_id] = $excel_name;
		}
		$data['excel_format_drop'] = $excel_format_drop;
		
		$this->load->view("$this->control_name/import",$data);
	}
	//Payroll Config settings
	public function payroll_config(){
		$column_qry    = 'select * from cw_form_setting where prime_module_id = "employees" and trans_status = 1 and transaction_type != 4';
		$column_data   = $this->db->query("CALL sp_a_run ('SELECT','$column_qry')");
		$column_result = $column_data->result();
		$column_data->next_result();
		$data['column_list']   = $column_result;
		$data['encKey']       	  = $this->generateKey();	
		$this->load->view("$this->control_name/payroll",$data);
	}
	
	public function get_permission_list(){
		$encString         = file_get_contents('php://input');
		$_POST             = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'Invalid Request..','table_data' => ""));
			exit(0);
		}
		$role = $this->input->post('user_right');
		/*============ BSK EMPLOYEE CUSTOME BLOCK ============*/
		$modules = array();
		$controller = "employee_permission";//for employee id
		
		foreach($this->Module->get_all_modules($controller) as $module){
			$module->module_id = $this->xss_clean($module->module_id);
			$module->grant     = $this->xss_clean($this->Module->has_grant($controller,$module->module_id, $role));
			$module->access    = $this->xss_clean($this->Module->has_access($controller,$module->module_id, $role));
			$modules[] = $module;
		}		
		$menu_array         = array();
		$menu_data_array    = array();
		$submenu_data_array = array();
		$menu_sts_array     = array();
		$submenu_sts_array  = array();
		$menu_checked       = array();
		foreach($modules as $module){
			$access_add         = $module->access[0]['access_add'];
			$access_update      = $module->access[0]['access_update'];
			$access_delete      = $module->access[0]['access_delete'];
			$access_search      = $module->access[0]['access_search'];
			$access_export      = $module->access[0]['access_export'];
			$access_import      = $module->access[0]['access_import'];
			$grants_menu_id     = $module->access[0]['grants_menu_id'];
			$grants_sub_menu_id = $module->access[0]['grants_sub_menu_id'];
			$check_box_input = form_checkbox("grants[]", $module->module_id, $module->grant, "class='module_$module->module_id'");		
			$menu_input = form_checkbox("menu_id", $module->menu_id, $grants_menu_id,"id='".str_replace(" ","_",strtolower($module->menu_name))."'", "class='menu_id'");
			$sub_menu_input = form_checkbox("sub_menu_id", $module->sub_menu_id, $grants_sub_menu_id,"id='".str_replace(" ","_",strtolower($module->sub_menu_name."_".$module->menu_id))."'", "class='sub_menu_id'");			
			if((int)$module->menu_id === (int)$grants_menu_id){
				$menu_checked[$module->menu_name] = str_replace(" ","_",strtolower($module->menu_name));
			}
			if((int)$module->sub_menu_id === (int)$grants_sub_menu_id){
				$check_sub_menu = str_replace(" ","_",strtolower($module->sub_menu_name))."_".$module->menu_id;
				$sub_menu_checked[$check_sub_menu] = str_replace(" ","_",strtolower($module->sub_menu_name));
			}
			$menu_name       = $module->menu_name;
			$sub_menu_name   = $module->sub_menu_name;
			$module_name     = $module->module_name;		
			$add_id          = $module->module_id ."::add";
			$add_checkbox    = form_checkbox(array("name" =>'access[]',"value" => $add_id, "class" =>'module_'.$module->module_id, "checked" => ($access_add) ? 1 : 0));
			$update_id       = $module->module_id ."::update";
			$update_checkbox = form_checkbox(array("name" =>'access[]',"value" => $update_id, "class" =>'module_'.$module->module_id, "checked" => ($access_update) ? 1 : 0));
			$delete_id       = $module->module_id ."::delete";
			$delete_checkbox = form_checkbox(array("name" =>'access[]',"value" => $delete_id, "class" =>'module_'.$module->module_id, "checked" => ($access_delete) ? 1 : 0));
			$search_id       = $module->module_id ."::search";                                
			$search_checkbox = form_checkbox(array("name" =>'access[]',"value" => $search_id, "class" =>'module_'.$module->module_id, "checked" => ($access_search) ? 1 : 0));
			$export_id       = $module->module_id ."::export";                                
			$export_checkbox = form_checkbox(array("name" =>'access[]',"value" => $export_id, "class" =>'module_'.$module->module_id, "checked" => ($access_export) ? 1 : 0));
			$import_id       = $module->module_id ."::import";                                
			$import_checkbox = form_checkbox(array("name" =>'access[]',"value" => $import_id, "class" =>'module_'.$module->module_id, "checked" => ($access_import) ? 1 : 0));
			
			$access_data  = "<div style='padding:8px 15px;border-bottom:1px dashed #CCCCCC;margin-bottom:15px;background-color: #f2f2f2;'>
								<label class='checkbox-inline'> $add_checkbox Add</label>
								<label class='checkbox-inline'> $update_checkbox Update</label>
								<label class='checkbox-inline'> $delete_checkbox Delete</label>
								<label class='checkbox-inline'> $search_checkbox Search</label>
								<label class='checkbox-inline'> $export_checkbox Export Data</label>
								<label class='checkbox-inline'> $import_checkbox Import Data</label>
							</div>"; 
			$grand_data   = "<label class='checkbox-inline' style='margin-bottom:6px;'>
								$check_box_input  <span class='prime_color'><b>$module_name :</b></span> Add, Update, Delete, and Search $module_name
							</label>";
			$menu_data    = "<label class='checkbox-inline' style='margin-bottom:6px;'>
								$menu_input  <span style='color:#000000;Font-size:16px;'><b>$menu_name</b></span> 
							</label>";
			$sub_menu_data    = "<label class='checkbox-inline' style='margin-bottom:6px;'>
								$sub_menu_input  <span style='color:#4DC147;Font-size:14px;'><b>$sub_menu_name</b></span> 
							</label>";		
			if((int)$form_view->role === 1){
				$sub_menu_name = str_replace(" ","_",strtolower($sub_menu_name."_".$module->menu_id));
				$menu_array[$menu_name][$sub_menu_name][] = array("access_data"=>$access_data,"grand_data"=>$grand_data);
				$menu_data_array[$menu_name]        = $menu_data;
				$submenu_data_array[$sub_menu_name] = $sub_menu_data;
	
				if((int)$module->menu_id === (int)$grants_menu_id){
					$menu_sts_array[$menu_name] = " ";
				}else{
					$menu_sts_array[$menu_name] = "style='display:none;'";
				}
				if((int)$module->sub_menu_id === (int)$grants_sub_menu_id){
					$submenu_sts_array[$sub_menu_name] = " ";
				}else{
					$submenu_sts_array[$sub_menu_name] = "style='display:none;'";
				}
			}else{
				$sub_menu_name = str_replace(" ","_",strtolower($sub_menu_name."_".$module->menu_id));
				$admin_module = array("module_setting"=>true,"tester"=>true,"config"=>true);
				if(!$admin_module[$module->module_id]){
					$menu_array[$menu_name][$sub_menu_name][] = array("access_data"=>$access_data,"grand_data"=>$grand_data);
					$menu_data_array[$menu_name]        = $menu_data;
					$submenu_data_array[$sub_menu_name] = $sub_menu_data;
					if((int)$module->menu_id === (int)$grants_menu_id){
						$menu_sts_array[$menu_name] = " ";
					}else{
						$menu_sts_array[$menu_name] = "style='display:none;'";
					}
					if((int)$module->sub_menu_id === (int)$grants_sub_menu_id){
						$submenu_sts_array[$sub_menu_name] = " ";
					}else{
						$submenu_sts_array[$sub_menu_name] = "style='display:none;'";
					}
				}
			}
		}
		$li_line = "";
		foreach ($menu_array as $menu_name => $value) {
			$menu = $menu_data_array[$menu_name];
			$name = str_replace(" ","_",strtolower($menu_name));
			$menu_sts = $menu_sts_array[$menu_name];
			$sub_line = "";
			foreach ($value as $sub_menu_name => $data) {
				$sub_menu     = $submenu_data_array[$sub_menu_name];
				$sub_menu_sts = $submenu_sts_array[$sub_menu_name];
				$tr_line = "";
				foreach ($data as $key => $tr_value){
					$grand_data  = $tr_value['grand_data'];
					$access_data = $tr_value['access_data'];
					$tr_line .=  "<li>
										$grand_data
										$access_data
									</li>";
				}	
				$tr_line = "<ul id='ul_$sub_menu_name' $sub_menu_sts>$tr_line</ul>";
				$sub_line .= "<li>	
								$sub_menu
								$tr_line
							</li>";
			}	
	
			$sub_line = "<ul id='ul_$name' $menu_sts>$sub_line</ul>";
			$li_line .= "<li>	
							$menu
							$sub_line
						</li>";
		}
		echo json_encode(array("li_line"=>$li_line,"menu_checked"=>$menu_checked,'sub_menu_checked'=>$sub_menu_checked)); 
	}

	//Manually enter the employee code exit checking
	public function employee_code_exit(){	
		$encString         = file_get_contents('php://input');
		$_POST             = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'Invalid Request..','table_data' => ""));
			exit(0);
		}
		$employee_code  = $this->input->post('employee_code');
		$form_id        = $this->input->post('view_id');
		$emp_code_check_qry    = 'select * from cw_employees where employee_code = "'.$employee_code.'" and prime_employees_id !="'.$form_id.'"';
		$emp_code_check_info   = $this->db->query("CALL sp_a_run ('RUN','$emp_code_check_qry')");
		$emp_code_check_result = $emp_code_check_info->result();
		$emp_code_check_info->next_result();
		$num_rows      = $emp_code_check_info->num_rows();
		if((int)$num_rows > 0){
			echo json_encode(array('success' => FALSE, 'message' => "Employee Code already Exit! please enter another code"));
		}else{
			echo json_encode(array('success' => TRUE, 'message' => "Continue to fill further information"));
		}
	}
	public function get_excel_template(){
		$encString         = file_get_contents('php://input');
		$_POST             = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'Invalid Request..','table_data' => ""));
			exit(0);
		}
		$module_id      = $this->input->post('module_id');
		$import_type    = $this->input->post('import_type');
		$excel_format_qry = 'select prime_excel_format_id,excel_name from cw_util_excel_format where excel_module_id = "'.$module_id.'" and import_type="'.$import_type.'" and trans_status = 1';
		$excel_format   = $this->db->query("CALL sp_a_run ('SELECT','$excel_format_qry')");
		$excel_result    = $excel_format->result();
		$excel_format->next_result();
		$excel_format_drop[0] = "---- Excel Format ----";
		foreach($excel_result as $excel){
			$prime_excel_format_id = $excel->prime_excel_format_id;
			$excel_name            = $excel->excel_name;
			$excel_format_drop[$prime_excel_format_id] = $excel_name;
		}
		echo json_encode(array('success' => TRUE, 'excel_format_drop' => $excel_format_drop));
	}
	
	public function tax_range_check(){
		$encString         = file_get_contents('php://input');
		$_POST             = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'Invalid Request..','table_data' => ""));
			exit(0);
		}
		$tax_loc          = $this->input->post('tax_loc');
		$tax_range_qry    = 'select count(*) as rslt_range from cw_professional_tax where trans_status =1 and location = "'.$tax_loc.'"';
		$tax_range_data   = $this->db->query("CALL sp_a_run ('SELECT','$tax_range_qry')");
		$tax_range_data_result = $tax_range_data->result();
		$tax_range_data->next_result();
		$range_count = $tax_range_data_result[0]->rslt_range;
		if((int)$range_count === 0){
			echo json_encode(array('success' => False, 'msg' => "Please set the tax range for this location?"));
		}else{
			echo json_encode(array('success' => TRUE));
		}
	}
	public function emp_excel($Payload){
		//Decryption
		$_POST               = $this->cryptoDecrypt(base64_decode(urldecode($Payload)));
		$module_id           = $this->input->post('module_id');
		$excel_format        = $this->input->post('excel_format');
		$excel_name_qry      = 'select excel_name from cw_util_excel_format where  prime_excel_format_id ="'.$excel_format.'" and excel_module_id = "'.$module_id.'" and trans_status=1';
		$excel_format_name   = $this->db->query("CALL sp_a_run ('SELECT','$excel_name_qry')");
		$excel_name_rslt     = $excel_format_name->result();
		$excel_format_name->next_result();
		$excel_name          = $excel_name_rslt[0]->excel_name;		

		$excel_format_qry 	 = 'select view_name,excel_line_column_name,excel_line_value from cw_util_excel_format_line inner join cw_form_setting on cw_form_setting.label_name = excel_line_column_name where excel_line_module_id = "'.$module_id.'" and cw_form_setting.prime_module_id = "'.$module_id.'" and prime_excel_format_id ="'.$excel_format.'" and cw_util_excel_format_line.trans_status = 1 GROUP BY cw_form_setting.label_name';
		$excel_format_info   = $this->db->query("CALL sp_a_run ('SELECT','$excel_format_qry')");
		$excel_result        = $excel_format_info->result();
		$excel_format_info->next_result();		

		$excel_name          		= $excel_name_rslt[0]->excel_name;	
		$spreadsheet                = new Spreadsheet();
		$worksheet   				= $spreadsheet->getActiveSheet();
		# Set the first row as the header row
		foreach($excel_result as $excel){
			$excel_line_column_name = $excel->view_name;
			$excel_line_value       = $excel->excel_line_value;
			$worksheet->getCell($excel_line_value.'1')->setValue($excel_line_column_name);
		}
		$filename= $module_id."_".$excel_name.".xls";
	    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); 
	    header('Content-Disposition: attachment;filename= "'.$filename.'"'); 
	    header('Cache-Control: max-age=0'); 
		$writer                     = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls');
		$writer->save('php://output');
		echo json_encode(array('success' => TRUE, 'output' => $worksheet));
	    exit(0);
	}
	
	public function esi_statutory_elig($role,$employee_code){
		$get_esi_stat_qry      = 'select esi_limit,esi_eligibilit_formula from cw_statutory where trans_status = 1 and category="'.$role.'"';
		$esi_statutory_data    = $this->db->query("CALL sp_a_run ('SELECT','$get_esi_stat_qry')");
		$esi_statutory_result  = $esi_statutory_data->result();
		$esi_statutory_data->next_result();
		if($esi_statutory_result){
			$esi_limit        = $esi_statutory_result[0]->esi_limit;
			$esi_elig_formula = $esi_statutory_result[0]->esi_eligibilit_formula;
			$esi_elig_formula = str_replace('@', '', $esi_elig_formula);
			$esi_elig_query = 'SELECT '.$esi_elig_formula.' AS esi_elig_amt FROM cw_employees WHERE trans_status = 1 and employee_code = "'.$employee_code.'"';
			$esi_elig_data    = $this->db->query("CALL sp_a_run ('SELECT','$esi_elig_query')");
			$esi_elig_result  = $esi_elig_data->result();
			$esi_elig_data->next_result();
			$esi_elig_amt = $esi_elig_result[0]->esi_elig_amt;
			if($esi_elig_amt > $esi_limit){
				$upd_esi_elig_query  = 'UPDATE cw_employees SET esi_eligibility = 2 WHERE trans_status = 1 and employee_code="'.$employee_code.'"';
			}else{
				$upd_esi_elig_query  = 'UPDATE cw_employees SET esi_eligibility = 1 WHERE trans_status = 1 and employee_code="'.$employee_code.'"';
			}
			$this->db->query("CALL sp_a_run ('UPDATE','$upd_esi_elig_query')");
			return true;
		}
	}
	public function get_last_working(){
		$encString         = file_get_contents('php://input');
		$_POST             = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'Invalid Request..','table_data' => ""));
			exit(0);
		}
		$role             = $this->input->post('role');
		$resignation_date = date("Y-m-d",strtotime($this->input->post('resignation_date')));
		$notice_period_qry     = 'select IFNULL(notice_period,0) as notice_period from cw_notice_period where trans_status = 1';
		$notice_period_data    = $this->db->query("CALL sp_a_run ('SELECT','$notice_period_qry')");
		$notice_period_result  = $notice_period_data->result();
		$notice_period_data->next_result();
		if($notice_period_result){
			$notice = $notice_period_result[0]->notice_period;
			$notice_day        = date('d-m-Y', strtotime($resignation_date. " + $notice days"));
			$notice_day_check  = date('m-Y', strtotime($notice_day));
			//Get Month Days start and end date
			$month_day_qry     = 'select category,day_conditions,day_count,day_start,day_end from cw_month_day where cw_month_day.trans_status = 1 and category ="'.$role.'"';	
			$month_day_data    = $this->db->query("CALL sp_a_run ('SELECT','$month_day_qry')");
			$month_day_result  = $month_day_data->result();
			$month_day_data->next_result();
			if($month_day_result){
				$day_conditions = $month_day_result[0]->day_conditions;
				$day_count      = $month_day_result[0]->day_count;
				$day_start      = $month_day_result[0]->day_start;
				$day_end        = $month_day_result[0]->day_end;
				if((int)$day_conditions === 3){
					$prev_month = date("Y-m-".$day_start,strtotime("-1 month", strtotime($notice_day)));
					$end_month  = date("Y-m-".$day_end, strtotime($notice_day));
				}else{
					$sal_start  = '01';
					if((int)$day_conditions === 2){
						$day_end = date("t");
					}
					$prev_month = date("Y-m-".$sal_start,strtotime($notice_day));
					$end_month  = date("Y-m-".$day_end,strtotime($notice_day));
				}
			}
			$end_date       = strtotime($end_month);
			$start_date     = strtotime($prev_month);
			$notice_date     = strtotime($notice_day);
			$process_month  = date("m-Y",strtotime($notice_date));
			if(($notice_date >= $start_date) && ($notice_date <= $end_date)){
				$payroll_exit_qry  = 'select count(prime_transactions_id) as payroll_rslt from cw_transactions where transactions_month= "'.$process_month.'" and trans_status=1';
				$payroll_exit_data  = $this->db->query("CALL sp_a_run ('SELECT','$payroll_exit_qry')");
				$payroll_exit_result = $payroll_exit_data->result();
				$payroll_exit_data->next_result();
				$payroll_count = $payroll_exit_result[0]->payroll_rslt;
				if((int)$payroll_count > 0){
					echo json_encode(array('success' => FALSE, 'message' => "Already Payroll is proceed for this month, change the date first?"));
				}else{
					echo json_encode(array('success' => TRUE, 'notice_day' => $notice_day));
				}
			}else{
				echo json_encode(array('success' => TRUE, 'notice_day' => $notice_day));
			}
		}else{
			echo json_encode(array('success' => FALSE, 'msg' => "Please set notice period first?"));
		}
	}
	
	/*public function curl($emp_data){
		$postdata = '';
		foreach($emp_data as $key => $val){
			$postdata .= $key . '='.$val.'&';
		}
		$postdata = rtrim($postdata, '&');
		$url_path = base_url();
		$url = $url_path."app/timeoffice_api.php?frm=save_emp";
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_URL,$url);
		curl_setopt($ch, CURLOPT_POST, count($postdata));
		curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		$result= curl_exec($ch);
		curl_close($ch);
	}*/
	
	public function offerno_exit(){
		$offer_no      = $this->input->post('offer_no');
		$mobile_number = $this->input->post('mobile_number');
		$offerno_exit_qry  = 'select count(*) as offer_rslt from cw_offer_letter where employee_mobile_number= "'.$mobile_number.'" and offer_reference_number="'.$offer_no.'"';
		$offerno_exit_data  = $this->db->query("CALL sp_a_run ('SELECT','$offerno_exit_qry')");
		$offerno_exit_result = $offerno_exit_data->result();
		$offerno_exit_data->next_result();
		$offer_count = $offerno_exit_result[0]->offer_rslt;
		if((int)$offer_count === 1){
			echo json_encode(array('success' => TRUE, 'message' => "Ok, Proceed!"));
		}else{
			echo json_encode(array('success' => FALSE, 'message' => "Invalid Offer Reference Number!"));
		}
	}
	
	public function check_payroll(){
		$encString         = file_get_contents('php://input');
		$_POST             = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'Invalid Request..','table_data' => ""));
			exit(0);
		}
		$resignation_date  = $this->input->post('resignation_date');
		$role              = $this->input->post('role');
		//Get Month Days start and end date
		$month_day_qry     = 'select category,day_conditions,day_count,day_start,day_end from cw_month_day where cw_month_day.trans_status = 1 and category ="'.$role.'"';	
		$month_day_data    = $this->db->query("CALL sp_a_run ('SELECT','$month_day_qry')");
		$month_day_result  = $month_day_data->result();
		$month_day_data->next_result();
		if($month_day_result){
			$role           = $month_day_result[0]->category;
			$day_conditions = $month_day_result[0]->day_conditions;
			$day_count      = $month_day_result[0]->day_count;
			$day_start      = $month_day_result[0]->day_start;
			$day_end        = $month_day_result[0]->day_end;
			if((int)$day_conditions === 3){
				$prev_month = date("Y-m-".$day_start,strtotime("-1 month", strtotime($resignation_date)));
				$end_month  = date("Y-m-".$day_end, strtotime($resignation_date));
			}else{
				$sal_start  = '01';
				if((int)$day_conditions === 2){
					$day_end = date("t");
				}
				$prev_month = date("Y-m-".$sal_start,strtotime($resignation_date));
				$end_month  = date("Y-m-".$day_end,strtotime($resignation_date));
			}
		}
		$end_date       = strtotime($end_month);
		$start_date     = strtotime($prev_month);
		$resign_date    = strtotime($resignation_date);
		$process_month  = date("m-Y",strtotime($end_month));
		if(($resign_date >= $start_date) && ($resign_date <= $end_date)){
			$payroll_exit_qry  = 'select count(prime_transactions_id) as payroll_rslt from cw_transactions where transactions_month= "'.$process_month.'" and trans_status = 1 and role ="'.$role.'"';
			$payroll_exit_data  = $this->db->query("CALL sp_a_run ('SELECT','$payroll_exit_qry')");
			$payroll_exit_result = $payroll_exit_data->result();
			$payroll_exit_data->next_result();
			$payroll_count = $payroll_exit_result[0]->payroll_rslt;
			if((int)$payroll_count > 0){
				echo json_encode(array('success' => FALSE, 'message' => "Already Payroll Proceed! Do you want to proceed?"));
			}else{
				echo json_encode(array('success' => TRUE, 'message' => "Ok Proceed!!!"));
			}
		}else{
			echo json_encode(array('success' => TRUE, 'message' => "Ok Proceed!!!"));
		}
	}
	
	public function check_emp_code($emp_code,$form_id = -1){
		if($emp_code){
			$select_tl_qry    = 'select * from cw_employees where employee_code = "'.$emp_code.'" and trans_status = 1';
			if((int)$form_id > 0){
				$select_tl_qry    .= " and prime_employees_id != $form_id";
			}
			$select_tl_data   = $this->db->query("CALL sp_a_run ('SELECT','$select_tl_qry')");
			$count = $select_tl_data->num_rows();
			$select_tl_data->next_result();
			if((int)$count > 0){
				return FALSE;
			}else{
				return TRUE;
			}
		}else{
			return TRUE;
		}
	}
	public function check_payroll_exit(){
		$encString         = file_get_contents('php://input');
		$_POST             = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'Invalid Request..','table_data' => ""));
			exit(0);
		}
		$stop_pay_month     = $this->input->post('stop_pay_month');
		$employee_code      = $this->input->post('employee_code');
		$payroll_exit_qry   = 'select count(prime_transactions_id) as payroll_rslt from cw_transactions where employee_code ="'.$employee_code.'" and trans_status=1 and transactions_month ="'.$stop_pay_month.'"';
		$payroll_exit_data  = $this->db->query("CALL sp_a_run ('SELECT','$payroll_exit_qry')");
		$payroll_exit_result = $payroll_exit_data->result();
		$payroll_exit_data->next_result();
		$payroll_count = $payroll_exit_result[0]->payroll_rslt;
		if((int)$payroll_count === 0){
			echo json_encode(array('success' => TRUE, 'message' => "Ok Proceed!!!"));
		}else{
			echo json_encode(array('success' => FALSE, 'message' => "Already Payroll is completed?"));
		}
	}
	
	//CHECK LOAN INSTALLMENT
	public function check_loan_installment(){
		$encString         = file_get_contents('php://input');
		$_POST             = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'Invalid Request..','table_data' => ""));
			exit(0);
		}
		$employee_code     = $this->input->post('employee_code');
		$emp_data_qry      = 'select count(*) as rslt_count from  cw_loan_installment where emp_code = "'.$employee_code.'" and paid_status = 0 and trans_status =1';
		$emp_data          = $this->db->query("CALL sp_a_run ('SELECT','$emp_data_qry')");
		$emp_result        = $emp_data->result_array();
		$emp_data->next_result();
		$rslt_count        = (int)$emp_result[0]->rslt_count;
		if($rslt_count >= 1){
			echo json_encode(array('success'=>false,'message'=>'Cannot process'));
		}else{
			echo json_encode(array('success'=>true,'message'=>'Can process'));
		}
	}	

	public function get_position(){
		$encString         = file_get_contents('php://input');
		$_POST             = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'Invalid Request..','table_data' => ""));
			exit(0);
		}
		$department      = $this->input->post('department');
		$designation 	 = $this->input->post("designation");
		$position_qry = 'select prime_position_id,position_name from cw_position where department ="'.$department.'" and trans_status = 1';
		$position_info   = $this->db->query("CALL sp_a_run ('SELECT','$position_qry')");
		$position_result = $position_info->result();
		$position_info->next_result();
		$position_list = "<option value=''>--- Select Designation ---</option>";
		foreach($position_result as $result){
			$id        = $result->prime_position_id;
			$position  = $result->position_name;
			if((int)$designation === (int)$id){
				$selected = "selected = selected";
			}else{
				$selected = " ";
			}
			$position_list .= "<option value='$id' $selected>$position</option>";
		}
		echo $position_list;
	}

	public function remove_file_upload(){
		$table_name     = $this->input->post('table_name_set');
		$row_id         = (int)$this->input->post('row_id');
		$input_name     = $this->input->post('input_name');		
		if($table_name){
			$created_on    = date("Y-m-d h:i:s");
			$set_query     = $input_name .' = "" ,trans_updated_by = "'. $this->logged_id .'",trans_updated_date = "'.$created_on.'"';
			$update_query  = 'UPDATE '.$table_name .' SET '. $set_query .' WHERE prime_employees_employment_history_id = "'. $row_id .'"';
			$this->db->query("CALL sp_a_run ('UPDATE','$update_query')");
			//$this->get_rowset_form_info();
			echo json_encode(array('success' => TRUE, 'message' => "Successfully updated"));
		}else{
			echo json_encode(array('success' => FALSE, 'message' => "Unable to process your request"));
		}
	}

	//DR CODE START
	public function employee_approval_change(){
		$employee_code              = $this->input->post('employee_code');
		$employee_approval_qry      = 'select count(*) as count from cw_increment_approval where employees = "'.$employee_code.'" and approve_status = 1 and trans_status = 1';
		$employee_approval_data     = $this->db->query("CALL sp_a_run ('SELECT','$employee_approval_qry')");
		$employee_approval_result   = $employee_approval_data->result();
		$employee_approval_data->next_result();
		$increment_pending_count    = $employee_approval_result[0]->count;
		if((int)$pending_count > 0) {
			echo json_encode(array('success'=>false,'message'=>'Cannot Change Because Our Increment Status was Pending'));
		}else{
			echo json_encode(array('success'=>true,'message'=>'proceed'));
		}
	}
	public function employee_leave_approval_change(){
		$encString         = file_get_contents('php://input');
		$_POST             = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'Invalid Request..','table_data' => ""));
			exit(0);
		}
		$employee_code     = $this->input->post('employee_code');
		$employee_approval_qry      = "select leave_status from cw_request where employee_code = ".$employee_code." and trans_status=1";
		$employee_approval_data     = $this->db->query("CALL sp_a_run ('SELECT','$employee_approval_qry')");
		$employee_approval_result   = $employee_approval_data->result_array();
		$employee_approval_data->next_result();
		$count = 0;
		foreach ($employee_approval_result as $key => $value) {
			if((int)$value['leave_status'] === 1){
				$count++;
			}
		}
		if((int)$count > 0) {
			echo json_encode(array('success'=>false,'message'=>'Cannot Change Because Our Leave Approval Status was Pending'));
		}else{
			echo json_encode(array('success'=>true,'message'=>'proceed'));
		}
	}
	public function change_income_tax_type(){
		$income_tax_type 	= $this->input->post("income_tax_type");
		$view_id 			= $this->input->post("view_id");
		$employee_code 		= $this->input->post("employee_code");
		$finance_arr 		= $this->financial_info;
		$finance_id 		= $finance_arr[0]->prime_financial_setting_id;
		$income_tax_qry     = 'select count(*) as it_count from cw_tax_calculation where fin_set_id = "'.$finance_id.'" and emp_code = "'.$employee_code.'" and trans_status=1';
		$income_tax_info    = $this->db->query("CALL sp_a_run ('SELECT','$income_tax_qry')");
		$income_tax_rslt   	= $income_tax_info->result();
		$income_tax_info->next_result();
		$it_count 			= $income_tax_rslt[0]->it_count;
		if((int)$it_count > 0) {
			echo json_encode(array('success'=>false,'message'=>'Income Tax Already processed this financial year'));
		}else{
			echo json_encode(array('success'=>true,'message'=>'Income Tax Type Changed Successfully'));
		}
	}

	//SAVE MODEL DATA TO DATA BASE
	public function save_onboard(){
		//SAVE INFO FUNCTION
		$this->save_info();	
		$module_sts          = (int)$this->module_sts;
		$created_on          = date("Y-m-d h:i:s");
		if(!$module_sts){
			echo json_encode(array('success' => FALSE, 'message' => "Save Info Query Process Error...!"));
			exit(0);
		}else{
			$unq_chk             = array();
			$prime_qry_key       = "";
			$prime_qry_value     = "";
			$prime_upd_query     = "";
			$cf_has              = false;
			$form_id             = (int)$this->input->post($this->prime_id);
			$form_post_data      = array();	
			$emp_log             = array();
			$post_data           = array();
			$emp_log['prime_employees_id'] = $form_id;	
			foreach($this->form_info as $setting){
				$field_type      = $setting->field_type;
				$input_view_type = (int)$setting->input_view_type;
				$label_id        = strtolower(str_replace(" ","_",$setting->label_name));
				$field_isdefault = $setting->field_isdefault;
				$date_type       = $setting->date_type;
				$onboard_order   = (int)$setting->onboard_order;
				if((int)$field_type === 5){
					$value = trim($this->input->post($label_id));
					$pick_array[$label_id]  = $value;
				}else
				if((int)$field_type === 7){
					$multi_name = $label_id."[]";
					$value = implode(",",$this->input->post($multi_name) ?? []);
				}else{
					$value = $this->input->post($label_id);
				}			
				if((int)$field_type === 4){
					if((int)$date_type === 1){
						if($value){
							$value = date('Y-m-d',strtotime($value));
						}					
					}else{
						$value = $value;
					}
				}else
				if((int)$field_type === 11){
					$value = trim($this->input->post($label_id));
					$pick_array[$label_id]  = $value;
				}else
				if((int)$field_type === 13){
					$value = date('Y-m-d H:i:s',strtotime($value));
				}else
				if((int)$field_type === 8){//textbox only
					$value = str_replace('"',"~",$value);
					$value = str_replace("'","`",$value);
					$value = str_replace("&","^",$value);
				}else
				if((int)$field_type === 10){//File Upload
					$value 		 		 = $value;
					$remove_upload_fname = "old_".$label_id;
					$remove_upload_file  = $this->input->post($remove_upload_fname);
					if($value !== $remove_upload_file){
						unlink($remove_upload_file);  
					}
				}
				//Sanitize SQL InJection chars
			$value = $this->sanitize_input($value, $field_type);

			if(($input_view_type === 1) || ($input_view_type === 2)){
				if((int)$field_isdefault === 1){
						if($label_id !== "employee_code" && $label_id !== "sap_status" && $label_id !== "hr_status" && $onboard_order !== 0 && $onboard_order !== ""){
							$prime_qry_key     .= $label_id.",";
							$prime_qry_value   .= '"'.$value.'",';
							$prime_upd_query   .= $label_id.' = "'.$value.'",';
						}					
					}
					if($label_id === "sap_status"){
						$sap_status     = (int)$value;
					}
					if($label_id === "entry_flag"){
						$entry_flag     = $value;
					}
					if($label_id === "user_right"){
						$user_right     = $value;
					}				
					//ONBORD FIELDS RELATED FIELDS ONLY CHECK
					if($onboard_order !== 0 && $onboard_order !== ""){
						if($value === null || $value === 'null'){
							$value    = "";
						}
						$post_data[$label_id] = $value;
					}
				}
			}
			
			/*============ UDY EMPLOYEE CUSTOME BLOCK ============*/
			$user_name = $this->input->post('user_name');
			$password  = $this->input->post('password');
			
			/*============ BSK EMPLOYEE CODE EXIST CHECK CUSTOME BLOCK START============*/
			$exist     = $this->is_exist($this->input->post('employee_code'));
			$exist     = explode("/",$exist ?? "");
			$id        = $exist[0];
			$num_rows  = $exist[1];
			
			if(((int)$id !== (int)$form_id) && ((int)$num_rows >= 1)){
				$emp_code   = $this->get_digits($this->input->post('role'));
				$user_name  = $emp_code;
				$code_exist = 1;
			}else{			
				$emp_code = $this->input->post('employee_code');
				$code_exist = 2;
			}

			if($user_name === "" || $user_name === null){
				$user_name   = $emp_code;
			}			
			
			/*============ BSK EMPLOYEE CODE EXIST CHECK CUSTOME BLOCK END============*/
			if($user_name !== ''){
				$post_data['user_name']        = $user_name;
				$prime_qry_key     .="user_name,";
				$prime_qry_value   .= '"'.$user_name.'",';
				$prime_upd_query   .= 'user_name = "'.$user_name.'",';
			}
			/*if($password !== ''){
				$post_data['password']         = $password;
				$prime_qry_key     .="password,";
				$prime_qry_value   .= '"'.md5($password).'",';
				$prime_upd_query   .= 'password = "'.md5($password).'",';
			}*/
				
			/*============ UDY EMPLOYEE CUSTOME BLOCK ============*/			

			$emp_data = array();
			if($this->check_emp_code($emp_code,$form_id)){
				if((int)$form_id === 0 && $entry_flag === "c"){
					$post_json_data     = json_encode($post_data);

					//function for validate a unique and mandatory field via mysql stored procedure
					$error_sts_arr      = $this->unique_procedure_valid($post_json_data);			
					if($error_sts_arr[0] === 1){
						//sp procedure for validate 
						$prime_qry_key     .= "employee_code,sap_status,hr_status,trans_created_by,trans_created_date";
						$prime_qry_value   .= '"'.$emp_code.'","2","3","'.$this->logged_id.'",'.'"'.$created_on.'"';
						$prime_insert_query = "insert into $this->prime_table ($prime_qry_key) values ($prime_qry_value)";
						$insert_info        = $this->db->query("CALL sp_a_run ('INSERT','$prime_insert_query')");
						$insert_result      = $insert_info->result();
						$insert_info->next_result();
						$insert_id          = '"'.$insert_result[0]->ins_id.'"';		
						//function for insert a user based permission control insert to grants frm permission 
						$perm_ins_rslt      = $this->grants_permission_ins_fun($emp_code,$insert_id,$user_right);

						echo json_encode(array('success' => TRUE, 'message' => "Successfully added.. Your Employee Code is $emp_code $send_mail_status", 'insert_id' => $insert_id,'code_exist'=>$code_exist,'emp_code'=>$emp_code, 'check' => ""));
					}else{
						echo json_encode(array('success' => FALSE, 'check' => "Procedure", 'message' => "Validation Check Error..?","table_info" => $error_sts_arr));
						exit(0);
					}
				}else{
					$post_json_data     = json_encode($post_data);				
					$prime_upd_query    .= 'employee_code = "'.$emp_code.'",sap_status = "2",hr_status = "3",trans_updated_by = "'. $this->logged_id .'",trans_updated_date = "'.$created_on.'"';
					$prime_update_query  = 'UPDATE '. $this->prime_table .' SET '. $prime_upd_query .' WHERE '. $this->prime_id .' = "'. $form_id .'"';
					$this->db->query("CALL sp_a_run ('UPDATE','$prime_update_query')");

					//function for insert a user based permission control insert to grants frm permission 
					// $perm_ins_rslt      = $this->grants_permission_ins_fun($emp_code,$form_id,$user_right);

					echo json_encode(array('success' => TRUE, 'message' => "Successfully updated $send_mail_status",'insert_id' => $form_id,'code_exist'=>$code_exist,'emp_code'=>$emp_code, 'check' => ""));
				}
			}else{
				echo json_encode(array('success' => FALSE, 'check' => "", 'message' => "Employee Code Already Exists",'category_status'=>TRUE, 'check' => ""));
			}
		}		
	}

	//PROCEDURE USED TO INSERT AND UPDATE A EMPLOYEE ONBOARD DATA
	public function master_data_sp_fun($action,$post_json_data){
		$valid_unique                = $this->db->query("CALL sp_master_ins_upd ('$action,$post_json_data')");
		$valid_unique_rslt           = $valid_unique->result_array();
		$valid_unique->next_result();
	}

	//FUNCTION FOR INSERT A GRANTS PERMISSION IN USER BASED
	// public function grants_permission_ins_fun($employee_code,$prime_id,$user_right){	
	// 	$ins_per_grants_qry    = 'INSERT INTO cw_grants(permission_id,prime_employees_id,grants_menu_id,grants_sub_menu_id,access_add,access_update,access_delete,access_search,access_export,access_import) SELECT permission_id,"'.$prime_id.'",grants_menu_id,grants_sub_menu_id,access_add,access_update,access_delete,access_search,access_export,access_import FROM cw_employee_permission WHERE cw_employee_permission.trans_status = 1 and cw_employee_permission.role = "'.$user_right.'"';
	// 	$ins_per_grants_info   = $this->db->query("CALL sp_a_run ('INSERT','$ins_per_grants_qry')");
	// 	$ins_per_grants_rslt   = $ins_per_grants_info->result();
	// 	$ins_per_grants_info->next_result();
	// }

	//function for validate a unique fields via procedure
/*	public function unique_procedure_valid($post_json_data){
		$validation_sts_arr  = array();
		//unique procedure call
		$valid_unique        = $this->db->query("CALL sp_validate_unique ('$post_json_data')");
		$valid_unique_rslt   = $valid_unique->result_array();
		$valid_unique->next_result();
		if($valid_unique_rslt[0]){
			$validation_sts_arr = $valid_unique_rslt;
			return $validation_sts_arr;
		}else{
			return $validation_sts_arr = array(1);
		}
	}	*/
	//EMPLOYEE PAY STYRUCTURE DETAILS GET
	public function activity_no_fetch(){
		$encString         = file_get_contents('php://input');
		$_POST             = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'Invalid Request..','table_data' => ""));
			exit(0);
		}
		$role              = $this->input->post('role');
		$personal_code     = $this->input->post('personal_code');
		$wbs_element       = $this->input->post('wbs_element');
		$position          = $this->input->post('position');
		//and cw_pay_structure.category = "'.$role.'"
		$pay_struct_qry    = 'select cw_pay_structure.activity_no,cw_pay_structure.tax_location,category from cw_pay_structure where cw_pay_structure.personal_code = "'.$personal_code.'" and cw_pay_structure.wbs_element = "'.$wbs_element.'" and cw_pay_structure.position = "'.$position.'" and cw_pay_structure.status = 1 and cw_pay_structure.trans_status = 1';
		$pay_struct_data   = $this->db->query("CALL sp_a_run ('SELECT','$pay_struct_qry')");
		$pay_struct_rslt   = $pay_struct_data->result_array();
		$pay_struct_data->next_result();

		if(!count($pay_struct_rslt ?? [])){
			echo json_encode(array('success' => FALSE,'message' => 'Pay Structure not found.!', 'rslt_data' => $pay_struct_rslt));	
		}else{
			echo json_encode(array('success' => TRUE,'message' => 'Proceed.!', 'rslt_data' => $pay_struct_rslt));	
		}
	}
	public function project_pay_struct(){
		$encString         = file_get_contents('php://input');
		$_POST             = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'Invalid Request..','table_data' => ""));
			exit(0);
		}
		$personal_code     = $this->input->post('personal_code');
		$wbs_element       = $this->input->post('wbs_element');
		$pro_qry           = 'SELECT wbs_project_id FROM cw_sap_wbs WHERE  wbs_id = "'.$wbs_element.'" and trans_status = 1 ';
		$pro_data   = $this->db->query("CALL sp_a_run ('SELECT','$pro_qry')");
		$pro_rslt   = $pro_data->result_array();
		$pro_data->next_result();

		if(!count($pro_rslt ?? [])){
			echo json_encode(array('success' => FALSE,'message' => 'project not found for this wbs.!', 'rslt_data' => $pro_rslt));	
		}else{
			echo json_encode(array('success' => TRUE,'message' => 'Proceed.!', 'rslt_data' => $pro_rslt));	
		}
	}
	//FETCH GROSS WITH POSITION NAME ONLOAD
	public function position_gross(){
		$encString         = file_get_contents('php://input');
		$_POST             = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'Invalid Request..','table_data' => ""));
			exit(0);
		}
		$wbs_element       = $this->input->post('wbs_element');
		$position          = $this->input->post('position');
		//pay structure select qry 
		$pay_position_qry  = 'SELECT cw_sap_position.position_code,cw_sap_position.position_name,cw_sap_position.prime_sap_position_id,gross FROM cw_pay_structure inner join cw_sap_position on cw_pay_structure.position = cw_sap_position.position_code WHERE cw_pay_structure.wbs_element = "'.$wbs_element.'"  and cw_pay_structure.trans_status = 1 and cw_sap_position.trans_status = 1 and cw_pay_structure.status = 1 GROUP BY cw_pay_structure.position,cw_sap_position.position_code,cw_sap_position.position_name,
        cw_sap_position.prime_sap_position_id, cw_pay_structure.gross'; 
		$pay_position_info = $this->db->query("CALL sp_a_run ('SELECT','$pay_position_qry')");
		$pay_position_rslt = $pay_position_info->result_array();
		$pay_position_info->next_result();
		
		$pos_list          = "<option value = ''>---- Select Position ----</option>";
		foreach($pay_position_rslt as $for){
			$prime_id           = $for['prime_id'];
			$position           = $for['position_code'];
			$position_name      = $for['position_name'];
			$gross              = $for['gross'];
			$pos_list          .= "<option value = '$position'>$position - $position_name - $gross</option>";
		}
		echo $pos_list;
	}

//FUNCTION FOR EMPLOYEES LOGIN TAB RESET PASSWORD(FOR UPDATE PASSWORD AND SEND PASSWORD THROUGH SMS)
	public function reset_pass(){
		$encString         = file_get_contents('php://input');
		$_POST             = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'Invalid Request..','table_data' => ""));
			exit(0);
		}
		$employee_code     = $this->input->post('employee_code');
		$select_qry        = 'select aadhar_card_no,mobile_number from cw_employees where employee_code ="'.$employee_code.'"';
		$select_data       = $this->db->query("CALL sp_a_run ('SELECT','$select_qry')");
		$select_rslt       = $select_data->result_array();
		$select_data->next_result();
		$mobile_number     = $select_rslt[0]['mobile_number'];
		$aadhar_no         = $select_rslt[0]['aadhar_card_no'];
		$aadhar_pass       = substr($aadhar_no, -4);
		$random_number     = rand(100,999);
		$default_password  = $aadhar_pass.$random_number;
		$upd_pass          = md5($default_password);
		$otp_for           = "reset";
		$otp_code_msg      = $this->Module->send_sms($mobile_number,$employee_code,$default_password,$resend,$otp_for);
		if($otp_code_msg['success'] === true){
			$emp_update_query = 'update cw_employees set password="'.$upd_pass.'" where employee_code="'.$employee_code.'" and trans_status=1';
			$update_info      = $this->db->query("CALL sp_a_run ('UPDATE','$emp_update_query')");

			echo json_encode(array('success' =>true, 'message' =>"SMS send and Password Reset Successfully..!!" ));
			
		}else{
			echo json_encode(array('success' => $otp_code_msg['success'], 'message' => $otp_code_msg['message']));
		}

	}

	public function wbs_suggest(){
		$search_term    = $this->input->post_get('term');		
		$personal_code  = $this->input->post_get('personal_code');
		$final_qry = 'SELECT DISTINCT wbs_id,wbs_desc FROM cw_sap_wbs inner join cw_pay_structure on cw_pay_structure.wbs_element = cw_sap_wbs.wbs_id and status = 1 where cw_sap_wbs.trans_status = 1 and wbs_personal_area_id = "'.$personal_code.'"  and (wbs_id like "'.$search_term.'%"  OR wbs_desc LIKE "'.$search_term.'%")' ;
		$final_data   = $this->db->query("CALL sp_a_run ('SELECT','$final_qry')");
		$final_result = $final_data->result();
		$final_data->next_result();
		foreach($final_result as $rslt){
			$employee_code = $rslt->wbs_id;
			$emp_name      = $rslt->wbs_desc;
			$suggestions[] = array('value' => "$employee_code", 'label' => "$employee_code - $emp_name");
		}
		if(empty($suggestions)){
			$suggestions[] = array('value' => "0", 'label' => "No data found for this search");
		}
		echo json_encode($suggestions);	
	}
}
?>