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/hrms_allyindian_com/application_bk/controllers/Employee_self_portal.php
<?php if ( ! defined('BASEPATH')) exit('No direct script is allowed');
require_once("Action_controller.php");
class Employee_self_portal  extends Action_controller{	
	public function __construct(){
		parent::__construct('employee_self_portal');
	}
	
	// LOAD PAGE QUICK LINK,FILTERS AND TABLE HEADERS
	public function index(){
		//PAGE INFO FUNCTION
		$this->page_info();	
		$data['encKey']          = $this->generateKey();	
		$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;

		// $table_head_qry          = 'select * from cw_form_setting where prime_module_id = "audit_trial" and table_show = "1" and input_view_type != "3" and trans_status = "1" and FIND_IN_SET("'.$this->logged_user_role.'",user_right_for)';
		// $table_head_info         = $this->db->query("CALL sp_a_run ('SELECT','$table_head_qry')");
		// $table_head_rslt         = $table_head_info->result();
		// $table_head_info->next_result();

		// $this->table_head        = $table_head_rslt;
		$data['table_head']      = $this->table_head;
		$data['fliter_list']     = $this->fliter_list;
		$data['freeze_list']     = $this->freeze_list;
		$this->load->view("$this->control_name/manage",$data);
	}

	//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' => 'Url Expired.. Please refresh the page and try again....'));
			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{
			$logged_id        = $this->logged_id;
			$employee_code    = $this->logged_emp_code;
			$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);
			//DR STATC CODE START
			$this->prime_table = "cw_audit_trial";
			$search_query      = str_replace("employee_self_portal","audit_trial",$search_query);
			$search_result     = array();

			//DR STATC CODE END
			//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;
					$input_view_type    = (int)$setting->input_view_type;
					$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);
			//DR STATC CODE START
			$count_all_query    = str_replace("employee_self_portal","audit_trial",$count_all_query);
			$count_query        = $count_all_query.' where '.$this->prime_table.'.trans_status = 1 and '.$this->prime_table.'.prime_employees_id != 1 and '.$this->prime_table.'.employee_code = "'.$employee_code.'" '.$role_condition.$fliter_query.$common_search;
			//echo $count_query; die;
			//ONLY LOGGED EMPLOYEE ENTRY SHOULD SELECT
			$search_query      .= " where $this->prime_table.trans_status = 1 and $this->prime_table.prime_employees_id != 1 and $this->prime_table.employee_code = \"$employee_code\" $role_condition $fliter_query $common_search";
			$search_query      .= " ORDER BY prime_audit_trial_id $order_sor";
			//DR STATC CODE END
			if((int)$per_page !== -1){
				$search_query  .= " LIMIT  $start,$per_page";
			}
			//echo $search_query; die;
			$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){
		$form_view_id                   = $this->logged_id; //Only Update fetch from employee table
		$this->prime_id                 = "prime_employees_id";
		//VIEW INFO FUNCTION
		$this->view_info($form_view_id);
		$data['primeId']                = $form_view_id;
		$data['encKey']                 = $this->generateKey();
		$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
		//DEPENDENT AUTO PICKLIST
		$data['auto_pick']              = $this->depen_auto_list;//dependent auto result		
		$data['condition_list']         = $this->form_condition_list;

		//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';
		$form_view_qry       = str_replace("cw_employee_self_portal","cw_employees",$form_view_qry);
		$form_view_qry       = str_replace("prime_employee_self_portal_id","prime_employees_id",$form_view_qry);

		// $row_view_qry        = 'select * from cw_custom_design inner join cw_form_setting on cw_form_setting.label_name = cw_custom_design.label_name and cw_form_setting.prime_module_id = cw_custom_design.prime_module_id and cw_form_setting.input_for = cw_custom_design.input_for where cw_custom_design.prime_module_id = "employees" and cw_custom_design.input_view = "3"';
		$row_view_qry        = 'select cw_form_view_setting.* from cw_custom_design inner join cw_form_view_setting on cw_form_view_setting.prime_view_module_id = cw_custom_design.prime_module_id and cw_form_view_setting.prime_form_view_id = cw_custom_design.input_for where cw_custom_design.prime_module_id = "employees" and cw_custom_design.input_view = "3"';

		// $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;		

		$data['edit_id']       = $form_view_id;
		
		$emp_details_columns = 'select employee_code,emp_name from `cw_employees` where trans_status =1';
		$emp_details_info   = $this->db->query("CALL sp_a_run ('SELECT','$emp_details_columns')");
		$emp_details_result = $emp_details_info->result();
		$emp_details_info->next_result();
		$emp_details[""] = "---- Select Column ----";
		foreach($emp_details_result as $emp_column){
			$employee_code  = $emp_column->employee_code;
			$emp_name       = $emp_column->emp_name;
			$emp_details[$this->xss_clean($employee_code)] = $this->xss_clean($emp_name);
		}		
		$data['emp_details'] = $emp_details;
		$minimum_age 		 = $this->company_info[0]->minimum_age;
		$maximum_age 		 = $this->company_info[0]->maximum_age;
		$data['minimum_age'] = $minimum_age;
		$data['maximum_age'] = $maximum_age;
		$allow_past_date		= $this->company_info[0]->allow_past_date;
		$allow_future_date		= $this->company_info[0]->allow_future_date;
		$data['aadhar_validation'] 	= $this->company_info[0]->aadhar_validation;
		$data['allow_past_date']	= date("d-m-Y", strtotime(date('Y-m-d') . " -$allow_past_date day"));
		$data['allow_future_date']	= date("d-m-Y", strtotime(date('Y-m-d') . " +$allow_future_date day"));
		$data['confirm_period']     = $this->company_info[0]->confirm_period;
		//FOR DEPENDENT
		$data['get_depend_prime_id']   = $this->get_depend_fun();
		$data['depend_label_id']   	   = $this->depend_label_fun();	

		//Get unique fields
		$uniq_field_qry  = 'select CONCAT("#",label_name) as label_name from  cw_form_setting where cw_form_setting.prime_module_id = "employees" and input_view_type IN(1,2) and field_show = 1 and unique_field = 1 and 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'));

		$this->load->view("employee_self_portal/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' => 'Url Expired.. Please refresh the page and try again....','table_data' => ""));
			exit(0);
		}
		//SAVE INFO FUNCTION
		$employee_code       = $this->session->userdata('logged_emp_code');
		$created_on          = date("Y-m-d h:i:s");
		$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 = "";			
			$this->prime_id  = "prime_employees_id";
			$form_id         = $this->input->post($this->prime_id);
			if($form_id !== '-1'){ //Decryption
				$decRslt     = $this->cryptoDecrypt(base64_decode(urldecode($form_id)));
				$form_id     = (int)$decRslt['prime_id'];
				if(!$form_id){
					echo json_encode(array('success' => false,'message' => 'Url Expired.. Please refresh the page and try again....','table_data' => ""));
					exit(0);
				}
			}else{
				$form_id = 0;
			}
			$previous_data   = $this->get_previous_view($form_id);

			$previous_data   = $previous_data[0];
			// $rms_code        = $this->input->post("rms_code");
			$post_data       = array();	
			$emp_log         = array();
			$emp_log['prime_employees_id'] = $form_id;
			$emp_log['employee_code']      = $employee_code;
			$post_data['employee_code']    = $employee_code;
			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."[]";
					$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 === 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);  
					}
				}
				
				if(($input_view_type === 1) || ($input_view_type === 2)){
					/*if((int)$field_isdefault === 1){
						if($label_id !== "employee_code"){
							$prime_qry_key     .= $label_id.",";
							$prime_qry_value   .= '"'.$value.'",';
							$prime_upd_query   .= $label_id.' = "'.$value.'",';
						}					
					}*/
					if($label_id === "emp_name"){
						$emp_name  = $value;
					}
					if($label_id === "med_status"){
						$value   = 1;
					}
					$emp_log[$label_id]    = $value;
					$post_data[$label_id]  = $value;
				}				
			}
			$minimum_age 		= $this->company_info[0]->minimum_age;
			$maximum_age 		= $this->company_info[0]->maximum_age;
			if((int)$minimum_age === 0 || (int)$maximum_age === 0){
				echo json_encode(array('success' => false, 'message' => "Please set age limit"));
				exit(0);
			}
			$date_of_birth 		= $this->input->post("date_of_birth");
			$date_of_joining 	= $this->input->post("date_of_joining");
			$minimum_date 		= date("d-m-Y", strtotime($date_of_birth. " + $minimum_age year"));
			$maximum_date 		= date("d-m-Y", strtotime($date_of_birth. " + $maximum_age year"));
			if(strtotime($date_of_joining) <= strtotime($minimum_date)){
				echo json_encode(array('success' => false, 'message' => "Date of joining and date of birth minimum difference is $minimum_age years, please change the date?"));
				exit(0);
			}else
			if(strtotime($date_of_joining) >= strtotime($maximum_date)){
				echo json_encode(array('success' => false, 'message' => "Date of joining and date of birth maximum difference is $maximum_age years, please change the date?"));
				exit(0);
			}

			$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');
			}		
			
			/*============ BSK EMPLOYEE CODE EXIST CHECK CUSTOME BLOCK END============*/
			$emp_data = array();
			//EMPLOYEE PREVIOUS EDITED DATA STILL PENDING OR NOT(LIKE CHECKER STATUS)
			$pend_count_qry    = 'select count(cw_audit_trial.prime_audit_trial_id) as pending_count from cw_audit_trial where cw_audit_trial.employee_code = "'.$employee_code.'" and cw_audit_trial.audit_status = 1 and cw_audit_trial.trans_status = 1';
			$pend_count_info   = $this->db->query("CALL sp_a_run ('SELECT','$pend_count_qry')");
			$pend_count_rslt   = $pend_count_info->result();
			$pend_count_info->next_result();
			$pending_count     = (int)$pend_count_rslt[0]->pending_count;
			// echo "pending_count => $pending_count";

			//JSON DATA FOR CHECK UNIQUE BASED ON UNIQUE PROCEDURE
			$post_json_data    = json_encode($post_data);
			$error_sts_arr     = array();
			if((int)$form_id !== 0){
				if($pending_count === 0){
					//function for vaidate a unique and mandate fields via procedure
					$error_sts_arr      = $this->unique_procedure_valid($post_json_data);
					$error_count 	    = count($error_sts_arr);
					if($error_sts_arr[0] === 1){
						//IF ANY CHANGES IN PREVIOUS DATA AND CURRENT DATA
						$emp_label_name    = array_keys($emp_log);
						$emp_label_value   = implode(",",$emp_label_name);
						$emp_data_qry      = "select $emp_label_value from cw_employees where prime_employees_id = $form_id";
						$emp_data          = $this->db->query("CALL sp_a_run ('SELECT','$emp_data_qry')");
						$emp_result        = $emp_data->result_array();
						$emp_data->next_result();

						$fin_emp_result    = $emp_result[0]; 
						$emp_code          = $fin_emp_result['employee_code'];
						$emp_name          = $fin_emp_result['emp_name'];
						$emp_data_dif      = array_diff_assoc($fin_emp_result,$emp_log);
						$change_count      = 0;

						foreach($emp_data_dif as $emp_key=>$emp_value){
							$old_label_val  = $fin_emp_result[$emp_key];
							$new_label_val  = $emp_log[$emp_key];

							if($old_label_val !== $new_label_val){
								//INPUT CHANGE CONDITIONS
								if($new_label_val !== '' || (($new_label_val === '' || $new_label_val === '0' || $new_label_val === '0') && ($old_label_val !== '' && $old_label_val !== '0' && $old_label_val !== 0 && $old_label_val !== '0.00' && $old_label_val !== 0.00 && $old_label_val !== '0000-00-00'))){
									$change_count++;
								}
								// if((($old_label_val === '0' || $old_label_val === 0) && $new_label_val !== '') || (($old_label_val === '0.00' || $old_label_val === 0.00) && $new_label_val !== '') || ($old_label_val === '0000-00-00' && $new_label_val !== '') || (($old_label_val === '') && $new_label_val !== '') || ($old_label_val)){
								// 	$change_count++;
								// }
							}
						}
						if($change_count > 0){
							//AUDIT TRIAL TABLE INSERT QRY
							$prime_qry_key     .= "prime_employees_id,employee_code,emp_name,audit_status,trans_created_by,trans_created_date";
							$prime_qry_value   .= '"'.$form_id.'","'.$employee_code.'","'.$emp_name.'","1","'.$this->logged_id.'",'.'"'.$created_on.'"';
							$prime_insert_query = "insert into cw_audit_trial ($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          = (int)$insert_result[0]->ins_id;	
							
							//EMPLOYEES SELF LOG TABLE INSERT FUNCTION
							if($insert_id){
								//EMPLOYEES LOG CREATE FUNCTION
								$this->employee_log($form_id,$emp_log,$insert_id,$fin_emp_result);

								//EMAIL SEND PROCESS
								$send_mail_status = "";
								if((int)$this->email_count > 0){
									$send_mail_status = $this->dynamic_mail_sent($insert_id,$pick_array,$previous_data);
								}	
								echo json_encode(array('success' => TRUE, 'message' => "Details Successfully Added $send_mail_status..!"));
							}
						}else{
							echo json_encode(array('success' => False, 'message' => "You Didn't Made any Changes..!"));
							exit(0);
						}
						
					}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' => "Your Previous Transaction Status was Pending..!","table_info" => $error_sts_arr));
					exit(0);
				}
			}else{
				echo json_encode(array('success' => FALSE, 'check' => "", 'message' => "You are not Autorized Employee Please Contact Admin..!","table_info" => $error_sts_arr));
				exit(0);
			}
				
		}	
	}
	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(){
		$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(CONVERT(SUBSTRING_INDEX(replace(employee_code,"'.$prefix.'",""),"-",-1),UNSIGNED INTEGER)) as employee_code from cw_employees where prime_employees_id != 1 '.$prefix_qry;
		}else{
			$emp_count_qry = 'select MAX(CONVERT(SUBSTRING_INDEX(replace(employee_code,"'.$prefix.'",""),"-",-1),UNSIGNED INTEGER)) 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();
		//$emp_count       = $emp_count_data->num_rows();
		$max_count         = $emp_count_result[0]->employee_code;	
		if($max_count){
			if((int)$num_rows > 0){
				/*$digits        = $this->digit_check($prefix,$start_value,$max_count);*/
				// $max_count   = substr($max_count,$prefix_count);
				$max_count = substr($max_count,0);
				if($max_count < $start_value){
					$max_count	= $start_value-1;
				}
				$digits      = $max_count +1;
				$max_digit   = strlen($max_count);
				$final_digit = strlen($digits);
				$check_digit = $max_digit - $final_digit;
				if($check_digit === 0){
					return $prefix."".$digits;
				}else{
					$digits  = str_pad($digits,$max_digit,"0",STR_PAD_LEFT);
					return $prefix."".$digits;
				}				
			}else{
				return false;
			}
		}else{
			return $prefix."".$start_value;
		}
	}
	
	/*============ 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' => 'Url Expired.. Please refresh the page and try again....','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{
			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(){
		//Encryption
		$encString     = file_get_contents('php://input');
		$_POST         = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'Url Expired.. Please refresh the page and try again....','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['encKey']        = $this->generateKey();
		$data['module_id']     = $this->control_name;		
		$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;
		$this->load->view("$this->control_name/payroll",$data);
	}
	
	//Sheet Name display in import page
	public function sheet_name(){
		$file_path  = $this->input->post('file_path');
		$filename = dirname(__FILE__)."/php_excel/PHPExcel/IOFactory.php";
		include($filename);
		$excel_obj   = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_path);
		$sheet_count = $excel_obj->getSheetCount();
		$sheet_name  = array();
		for($i= 0; $i< $sheet_count; $i++){
			$sheet        = $excel_obj->getSheet($i);
			$sheet_name[] = $sheet->getTitle();
		}
		echo json_encode(array('sheet_name' =>$sheet_name));
	}

	
	//Manually enter the employee code exit checking
	public function employee_code_exit(){	
		$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(){
		$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(){
		$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 excel($module_id,$excel_format){
	// 	$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   = $this->db->query("CALL sp_a_run ('SELECT','$excel_format_qry')");
	// 	$excel_result    = $excel_format->result();
	// 	$excel_format->next_result();		
	// 	//require_once APPPATH."/third_party/PHPExcel.php";
	// 	// require_once APPPATH."/controllers/php_excel/PHPExcel.php";;
	// 	$obj = new Spreadsheet();		
	// 	//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;
	// 		$obj->getActiveSheet()->setCellValue($excel_line_value."1", $excel_line_column_name);
	// 	}	
	// 	ob_end_clean();	
	// 	// Rename worksheet name
	// 	$filename= $module_id.".xls"; //save our workbook as this file name
	// 	header('Content-Type: application/vnd.ms-excel'); //mime type
	// 	header('Content-Disposition: attachment;filename="'.$filename.'"'); //tell browser what's the file name
	// 	header('Cache-Control: max-age=0'); //no cache
	// 	ob_end_clean();
		
	// 	//save it to Excel5 format (excel 2003 .XLS file), change this to 'Excel2007' (and adjust the filename extension, also the header mime type)
	// 	 //if you want to save it as .XLSX Excel 2007 format
	// 	$objWriter = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($obj, 'Excel5');
	// 	 //force user to download the Excel file without writing it to server's HD
	// 	$objWriter->save('php://output');
	// 	echo json_encode(array('success' => TRUE, 'output' => $excelOutput));
	// }
	
	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(){
		$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 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(){
		$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_termination_status(){
		$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 termination_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]->prime_transactions_id;
		if((int)$payroll_count > 0){
			echo json_encode(array('success' => FALSE, 'message' => "Already separation is completed, not possible to release?"));
		}else{
			echo json_encode(array('success' => TRUE, 'message' => "Employee resignation is revoked!!!"));
		}
	}
	
	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(){
		$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?"));
		}
	}
	
	//EMPLOYEES TABLE LOG FOR EVERY UPFDATE OF THE EMPLOYEES
	public function employee_log($emp_id,$emp_log,$insert_id,$fin_emp_result){
		$module_name       = "employee_self_portal";
		$created_on        = date("Y-m-d H:i:s");
		$logged_id         = $this->logged_id;
		// echo "</pre>";
		// print_r($emp_result);die;
		// $fin_emp_result    = $emp_result[0]; 
		$emp_code          = $fin_emp_result['employee_code'];
		$emp_name          = $fin_emp_result['emp_name'];
		$emp_data_dif      = array_diff_assoc($fin_emp_result,$emp_log);
		$prime_qry_value   = "";
		$prime_qry_key     = "prime_audit_trial_id,prime_employees_id,employee_code,emp_name,label_name,old_value,new_value,module_name,trans_created_by,trans_created_date";
		foreach($emp_data_dif as $emp_key=>$emp_value){
			$old_label_val  = $fin_emp_result[$emp_key];
			$new_label_val  = $emp_log[$emp_key];
			
			// if($old_label_val !== $new_label_val){
			// 	if((($old_label_val === '0' || $old_label_val === 0) && $new_label_val !== '') || (($old_label_val === '0.00' || $old_label_val === 0.00) && $new_label_val !== '') || ($old_label_val === '0000-00-00' && $new_label_val !== '')){
			if($old_label_val !== $new_label_val){
				if($new_label_val !== '' || (($new_label_val === '' || $new_label_val === '0' || $new_label_val === '0') && ($old_label_val !== '' && $old_label_val !== '0' && $old_label_val !== 0 && $old_label_val !== '0.00' && $old_label_val !== 0.00 && $old_label_val !== '0000-00-00'))){
					$prime_qry_value .= "(\"$insert_id\",\"$emp_id\",\"$emp_code\",\"$emp_name\",\"$emp_key\",\"$old_label_val\",\"$new_label_val\",\"$module_name\",\"$logged_id\",\"$created_on\"),";
				}
			}
		}
		if(!empty($prime_qry_value)){
			$prime_qry_value    = rtrim($prime_qry_value,',');
			$prime_insert_query = "insert into cw_employees_self_log ($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();
		}
	}
	
	//CHECK LOAN INSTALLMENT
	public function check_loan_installment(){
		$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 check_file_exists(){
		$month        = $this->input->post('month');
		$emp_code     = $this->input->post('emp_code');
		$payslip_url  = "./payslip/consultant/".$month."_consultant_payslip/".$emp_code.".pdf";
		if (file_exists($payslip_url)) {  
			echo json_encode(array('success'=>true,'message'=>'Can process','url'=>$payslip_url));
		}else{
			echo json_encode(array('success'=>false,'message'=>'Cannot process'));
		}
	}
	public function get_position(){
		$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')");
			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(){
		$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'=>success,'message'=>'Income Tax Type Changed Successfully'));
		}
	}
	public function exp_ref_no(){
		$termination_status = $this->input->post("termination_status");
		$emp_qry    = 'select count(*) as count_exist from cw_employees where cw_employees.trans_status = 1 and cw_employees.termination_status = "'.$termination_status.'"';
		$emp_info   = $this->db->query("CALL sp_a_run ('SELECT','$emp_qry')");
		$emp_rslt 	= $emp_info->result();
		$emp_info->next_result();
		$num_rows   = $emp_info->num_rows();
		if((int)$num_rows > 0){
			$max_num_qry    = 'select MAX(exp_ref_no) as exp_ref_no from cw_employees where cw_employees.trans_status = 1 and termination_status = "'.$termination_status.'"';
			$max_num_info   = $this->db->query("CALL sp_a_run ('SELECT','$max_num_qry')");
			$max_num_rslt 	= $max_num_info->result();
			$max_num_info->next_result();
			$exp_ref_no		= $max_num_rslt[0]->exp_ref_no;
		}

		$max_count	= (int)$num_rows;
		if($max_count){
			$exp_no = $exp_ref_no+1;
		}else{
			$exp_no = $max_count+1;
		}
		echo json_encode(array('success'=>success,'message'=>'Experience reference no successfully generated...','exp_ref_no'=>$exp_no));
	}

	
	//EMPLOYEE EDIT LOG TABLE CREATE FOR SHOW
	public function audit_edit_log($audit_trial_id){
		if($audit_trial_id !== -1){
			//Decrypt prime id from URL
			$decRslt          = $this->cryptoDecrypt(base64_decode(urldecode($audit_trial_id)));
			$audit_trial_id     = $decRslt['prime_id'];
			if(!$audit_trial_id){
				echo json_encode(array('success' => false,'message' => 'Url Expired.. Please refresh the page and try again....','table_data' => ""));
				exit(0);
			}
		}
		$data['audit_trial_id']   = $audit_trial_id;
		//VIEW INFO FUNCTION CALL
		//$this->view_info($form_view_id);
		//GET EMPLOYEE MASTER PICKLIST
		$master_pick              = $this->pick_list;//all pick result

		// $emp_self_log_qry         = 'select cw_employees_self_log.*,cw_form_setting.field_type,cw_form_setting.view_name from cw_employees_self_log inner join cw_form_setting on cw_form_setting.label_name = cw_employees_self_log.label_name and cw_form_setting.prime_module_id = "employees" where cw_employees_self_log.prime_audit_trial_id = "'.$audit_trial_id.'" and cw_form_setting.trans_status = 1 and cw_employees_self_log.trans_status = 1';

		$emp_self_log_qry         = 'select cw_employees_self_log.*,cw_form_setting.field_type,cw_form_setting.view_name,cw_audit_trial.audit_status from cw_employees_self_log INNER JOIN cw_form_setting ON cw_form_setting.label_name = cw_employees_self_log.label_name and cw_form_setting.prime_module_id = "employees" INNER JOIN cw_audit_trial ON cw_audit_trial.prime_audit_trial_id = cw_employees_self_log.prime_audit_trial_id where cw_employees_self_log.prime_audit_trial_id = "'.$audit_trial_id.'" and cw_form_setting.trans_status = 1 and cw_employees_self_log.trans_status = 1';

		$emp_self_log_info        = $this->db->query("CALL sp_a_run ('SELECT','$emp_self_log_qry')");
		$emp_self_log_rslt        = $emp_self_log_info->result_array();
		$emp_self_log_info->next_result();

		$table_data               = '';
		$table_body               = '';
		$i                        = 1;
		foreach($emp_self_log_rslt as $key => $value){
			$audit_trial_id   = $value['prime_audit_trial_id'];
			$employees_id     =  $value['prime_employees_id'];
			$employee_code    = $value['employee_code'];
			$emp_name         = $value['emp_name'];
			$label_name       = $value['label_name'];
			$old_value        = $value['old_value'];
			$new_value        = $value['new_value'];

			$field_type       = (int)$value['field_type'];
			$view_name        = $value['view_name'];
			$audit_status     = (int)$value['audit_status'];
			if($field_type === 4){
				if($old_value !== "" && $old_value !== "0000-00-00"){
					$old_value   = date('d-m-Y',strtotime($old_value));
				}else{
					$old_value   = "";
				}
				if($new_value !== "" && $new_value !== "0000-00-00"){
					$new_value   = date('d-m-Y',strtotime($new_value));
				}else{
					$new_value   = "";
				}
			}else
			if($field_type === 13){
				if($old_value !== ""){
					$old_value   = date('d-m-Y H:i:s',strtotime($old_value));
				}else{
					$old_value   = "";
				}
				if($new_value !== ""){
					$new_value   = date('d-m-Y H:i:s',strtotime($new_value));
				}else{
					$new_value   = "";
				}
			}else
			if($field_type === 5 || $field_type === 7 || $field_type === 9){
				if($old_value){
					$old_value 	= $master_pick[$label_name]['array_list'][$old_value];
				}
				if($new_value){
					$new_value  = $master_pick[$label_name]['array_list'][$new_value];
				}
			}else
			if($field_type === 10){
				// $updated_value  = str_replace("employee_self_portal","employees",$new_value);
				// $new_value      =  $updated_value;
				if($old_value){
					// $updated_value      = str_replace("employee_self_portal","employees",$old_proof);
					$old_proof          = base_url("$old_value");
					$old_file_name      = explode("/",$old_value);
					$old_file_name      = $old_file_name[2];
					$old_file_ext_type  = explode(".", $old_value);
					$old_file_ext_type  = end($old_file_ext_type);
					$old_value          = "<div onclick=view_upload_file('".$old_proof."','".$old_file_ext_type."'); style = 'color:blue;'>$old_file_name<div>";
				}
				if($new_value){
					//IF STATUS WAS APPROVED THEN FILE WAS MOVED FROM EMPLOYEES SELF PORTAL TO EMPLOYEES FOLDER
					if($audit_status === 2){
						$new_value      = str_replace("employee_self_portal","employees",$new_value);
					}
					$new_proof          = base_url("$new_value");
					$new_file_name      = explode("/",$new_value);
					$new_file_name      = $new_file_name[2];
					$new_file_ext_type  = explode(".", $new_value);
					$new_file_ext_type  = end($new_file_ext_type);
					$new_value          = "<div onclick=view_upload_file('".$new_proof."','".$new_file_ext_type."'); style = 'color:blue;'>$new_file_name<div>";

					// $new_value = "<a href='$new_value' format.pdf='' target='_blank' style='cursor: pointer;''><i class='fa fa-download' style='color:red;' aria-hidden='true'></i></a>";
				}
			}
			// if($i === 1){
				// <td rowspan = '$total_emp_log_count'>$employee_code</td>
				// <td rowspan = '$total_emp_log_count'>$emp_name</td>
				$table_body   .= "<tr>
									<td rowspan = '$total_emp_log_count' style = 'display:none;'>$audit_trial_id</td>
									<td rowspan = '$total_emp_log_count' style = 'display:none;'>$employees_id</td>
									<td>$view_name</td>
									<td>$old_value</td>
									<td>$new_value</td>
								</tr>";
			// }else{
			// 	$table_body   .= "<tr>
			// 						<td>$label_name</td>
			// 						<td>$old_value</td>
			// 						<td>$new_value</td>
			// 					</tr>";
			// }
			$i++;

		}
		// if($table_body){
			// <th>Employee Code</th>
			// <th>Employee Name</th>
			$table_data   = "<table id='emp_log_table' class='table table-striped table-hover' style='width:100% !important;'>
							<thead>
								<tr>
									<th style = 'display:none;'></th>
									<th style = 'display:none;'></th>
									<th>Column Name</th>
									<th>Old Value</th>
									<th>New Value</th>
								</tr>
							</thead>
							<tbody>
								$table_body
							</tbody>
						</table>"; 
		// }

		$data['table_data']       = $table_data;
		$data['employee_code']    = $employee_code;	

		$this->load->view("$this->control_name/audit_log",$data);
	}
}
?>