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/cpaqua.cafsinfotech.in/application/controllers/Time_entry.php
<?php if ( ! defined('BASEPATH')) exit('No direct script is allowed');
require_once("Action_controller.php");
class Time_entry  extends Action_controller{	
	public function __construct(){
		parent::__construct('time_entry');
	}
	// LOAD PAGE QUICK LINK,FILTERS AND TABLE HEADERS
	public function index(){
		$data['encKey']        = $this->generateKey();
		$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['company_info']  = $this->company_info;
		//Employee code picklist conditions
		$employee_info_query = 'SELECT employee_code,emp_name FROM `cw_employees` where trans_status = 1 and prime_employees_id != 1';
		$employee_info   = $this->db->query("CALL sp_a_run ('SELECT','$employee_info_query')");
		$employee_result = $employee_info->result();
		$employee_info->next_result();
		$employee_list[""] = "---- Select Employee ----";
		foreach($employee_result as $for){
			$emp_code    = $for->employee_code;
			$emp_name    = $for->emp_name;
			$employee_list[$emp_code] = $emp_code." - ".$emp_name;
		}
		$data['employee_list'] = $employee_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{
			$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']);
			$month_filter = $this->input->post("month_filter");	
			//Get Salary Date
			$salary_arr        = $this->tos_sal_strt_end_info("4",$month_filter);
			$salary_start_date = date("Y-m-d",strtotime($salary_arr['salary_start_date']));
			$salary_end_date   = date("Y-m-d",strtotime($salary_arr['salary_end_date']));
			$month_filter_qry = " and $this->prime_table.att_date between '$salary_start_date' and '$salary_end_date'";
			//echo $month_filter_qry; die;
			$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 = "";
			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 '.$month_filter_qry.' '.$role_condition.$fliter_query.$common_search;
			
			$search_query      .= " where $this->prime_table.trans_status = 1 $month_filter_qry $role_condition $fliter_query $common_search";
			$search_query      .= " ORDER BY  att_date ASC";
			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){
		$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' => 'Url Expired.. Please refresh the page and try again....','table_data' => ""));
				exit(0);
			}
		}
		//VIEW INFO FUNCTION
		$this->view_info($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';
		$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;
		//FOR DEPENDENT
		$data['get_depend_prime_id']   = $this->get_depend_fun();
		$data['depend_label_id']   	   = $this->depend_label_fun();	
		$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' => 'Url Expired.. Please refresh the page and try again....','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 = "";
			//Decrypt Form 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];
			$form_post_data  = 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;
				$unique_field    = (int)$setting->unique_field;
				$view_name       = $setting->view_name;
				$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 = trim(implode(",",$this->input->post($multi_name) ?? []));
				}else{
					$value = trim($this->input->post($label_id));
				}
				
				if((int)$field_type === 4){
					if((int)$date_type === 1){
						$value = date('Y-m-d',strtotime($value));
					}else{
						$value = $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);  
					}
				}		
				
			//For replace special character
				$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){
						$prime_qry_key     .= $label_id.",";
						$prime_qry_value   .= '"'.$value.'",';
						$prime_upd_query   .= $label_id.' = "'.$value.'",';
						if($unique_field === 1){
							$prime_unq_chk = $label_id.'= "'.$value.'"';
							$query = "select count(*) as rslt_count from $this->prime_table where $this->prime_id != $form_id and $prime_unq_chk";
							$unq_chk[] = array('label_id'=>$label_id,'view_name'=>$view_name,'query'=>$query,);
						}
					}
				}
			}
			$rslt_count = 0;
			$can_process = array();
			foreach($unq_chk as $unq_rslt){
				$query       = $unq_rslt['query'];
				$label_id    = $unq_rslt['label_id'];
				$view_name   = $unq_rslt['view_name'];
				$unq_info    = $this->db->query("CALL sp_a_run ('RUN','$query')");
				$unq_result  = $unq_info->result();
				$unq_info->next_result();
				if($unq_result){
					$rslt_count = (int)$unq_result[0]->rslt_count;
					if($rslt_count !== 0){
						$can_process[] = $view_name." already exist";
					}
				}
			}
			if(count($can_process) > 0){
				$can_process  = array_values($can_process);				
				$can_process  = implode(",<br/>", $can_process);
				echo json_encode(array('success' => false, 'message' => $can_process,));
			}else{
				$created_on = date("Y-m-d h:i:s");
				if((int)$form_id === 0){
					$prime_qry_key     .= "trans_created_by,trans_created_date";
					$prime_qry_value   .= '"'.$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;	
					$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' => "Successfully added $send_mail_status", 'insert_id' => $insert_id));
				}else{
					$prime_upd_query    .= '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')");
					$send_mail_status = "";
					if((int)$this->email_count > 0){
						$send_mail_status = $this->dynamic_mail_sent($form_id,$pick_array,$previous_data);
					}
					echo json_encode(array('success' => TRUE, 'message' => "Successfully updated $send_mail_status",'insert_id' => $form_id));
				}
			}
		}
	}
	//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') ?? []);
		$delete_count            = count($this->input->post('delete_ids'));
		// print_r($delete_ids  );die;
   
		//GET DEFAULT FINANCIAL YEAR
		$financial_info          = $this->get_leave_financial_details();
		$prime_financial_id      = $financial_info[0]->prime_leave_financial_year_id;	
		$starting_date           = date('Y-m-d',strtotime($financial_info[0]->starting_date));	
		$ending_date             = date('Y-m-d',strtotime($financial_info[0]->ending_date));

		//Check leaves not exist in the system
		$check_cond              = '""';
		//"O","M","L","FL","SL","LP","PL","LM","ML","OL","LO","LL","WL","LW","UL","LU","MP","PM"
		//Check Delete Process is correct
		$check_table_query       = 'SELECT count(*) as check_count from cw_time_entry WHERE whole_day_status not in ('.$check_cond.') and trans_status = 1 and prime_time_entry_id in ('.$delete_ids.') AND att_date >= "'.$starting_date.'" AND att_date <= "'.$ending_date.'" ';
		print_r($check_table_query );
		$check_table_info        = $this->db->query("CALL sp_a_run ('SELECT','$check_table_query')");
		$check_table_rlst        = $check_table_info->result();
		$check_table_info->next_result();
		$check_count             = $check_table_rlst[0]->check_count;

		if((int)$delete_count  === (int)$check_count){
			$delete_insert_query = 'INSERT INTO cw_time_entry_dlt SELECT * FROM cw_time_entry WHERE whole_day_status not in ('.$check_cond.') and trans_status = 1 and prime_time_entry_id in ('.$delete_ids.')';
			$delete_insert_info  = $this->db->query("CALL sp_a_run ('INSERT','$delete_insert_query')");
			$delete_insert_rlst  = $delete_insert_info->result();
			$delete_insert_info->next_result();
			if($delete_insert_rlst){
				$delete_query    = 'DELETE FROM '. $this->prime_table .' WHERE whole_day_status not in ('.$check_cond.') and trans_status = 1 and '. $this->prime_id .' in ('. $delete_ids .')';
				$delete_info 	 = $this->db->query("CALL sp_a_run ('RUN','$delete_query')");
				if($delete_info){
					echo json_encode(array('success' => TRUE, 'message' => "Successfully Deleted"));
				}else{
					echo json_encode(array('success' => FALSE, 'message' => "Unable to Delete"));
				}
			}else{
				echo json_encode(array('success' => FALSE, 'message' => "Unable to Delete"));
			}
		}else{
			echo json_encode(array('success' => FALSE, 'message' => "Failed - Full Day Attendance OR Leave Approved in the list OR Date is not within the current financial year."));
		}
	}
	//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');
		$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);
	}
	//TIME ENTRY TABLE LOG FOR EVERY UPDATE OF THE TIME ENTRY
	public function time_entry_log($entry_id,$entry_log){
		$created_on        = date("Y-m-d H:i:s");
		$logged_id         = $this->logged_id;
		$entry_label_name  = array_keys($entry_log);
		$entry_label_value = implode(",",$entry_label_name);
		$entry_data_qry    = "select $entry_label_value from cw_time_entry where prime_time_entry_id = $entry_id";
		$entry_data_info   = $this->db->query("CALL sp_a_run ('SELECT','$entry_data_qry')");
		$entry_data_result = $entry_data_info->result_array();
		$entry_data_info->next_result();
		$ins_entry_result  = $entry_data_result[0]; 

		$emp_code          = $ins_entry_result['employee_code'];
		$att_date          = $ins_entry_result['att_date'];
		$entry_data_dif    = array_diff_assoc($ins_entry_result,$entry_log);

		$prime_qry_value   = "";
		$prime_qry_key     = "prime_time_entry_id,employee_code,att_date,label_name,old_value,new_value,trans_created_by,trans_created_date";
		foreach($entry_data_dif as $entry_key=>$entry_value){
			$old_label_val  = $ins_entry_result[$entry_key];
			$new_label_val  = $entry_log[$entry_key];
			
			if(($old_label_val != $new_label_val) && ($old_label_val !=='0.00' && $new_label_val !='') && ($old_label_val !=='0000-00-00' && $new_label_val !='' || $old_label_val !=='0000-00-00 00:00:00' && $new_label_val !='' && (int)strpos($old_label_val, '01-01-1970') !== 0 && (int)strpos($old_label_val, '30-11--0001') !== 0 && (int)strpos($old_label_val, '00-00-0000') !== 0)){
				$prime_qry_value .= "(\"$entry_id\",\"$emp_code\",\"$att_date\",\"$entry_key\",\"$old_label_val\",\"$new_label_val\",\"$logged_id\",\"$created_on\"),";
			}
		}
		if(!empty($prime_qry_value)){
			$prime_qry_value = rtrim($prime_qry_value,',');
			$prime_insert_query = "insert into cw_time_entry_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();
		}
	}
	//Function For Insert a Time Entry Table
	public function insert_time_entry(){
		//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);
		}
		$check_query = "SELECT IF(COUNT(DISTINCT sm.prime_shift_master_id) = (SELECT COUNT(*) FROM cw_shift_master WHERE trans_status = 1),1,0) AS is_all_exists FROM cw_shift_master sm JOIN cw_permission_setting ps ON ps.trans_status = 1
		AND FIND_IN_SET(sm.prime_shift_master_id, ps.shift_name) WHERE sm.trans_status = 1
		";
		$check_info = $this->db->query("CALL sp_a_run ('SELECT', '$check_query')");
		$check_result = $check_info->row();
		$check_info->next_result();

		$is_all_exists = $check_result->is_all_exists;
		if((int)$is_all_exists !== 1){
			echo json_encode(array('success' => FALSE, 'message' => "Please Map All Shifts On Permission Settings.."));
			exit;
		}

		$process_mode    = $this->input->post('process_mode');
		$employee_code   = $this->input->post('employee_code');
		$db_name         = $this->config->item("db_name");
		$from_date       = date("Y-m-d",strtotime($this->input->post('from_date')));
		$to_date         = date("Y-m-d",strtotime($this->input->post('to_date')));	

		if($db_name === 'pothys_hrms_db'){
			$info    = $this->db->query("CALL itsp_prcatt ('$from_date','$to_date','$employee_code')");
			$result  = $info->result();
			$info->next_result();
			$this->process_ilop($from_date,$to_date,$employee_code);
		}else{
			$rslt        = $this->update_missing_shifts($from_date,$to_date,$employee_code);
			if($rslt){
				$info    = $this->db->query("CALL itsp_prcatt ('$from_date','$to_date','$employee_code')");
				$result  = $info->result();
				$info->next_result();
			}
		}	
		if($result){
			echo json_encode(array('success' => TRUE, 'message' => "Successfully Processed..!!"));
		}else{
			echo json_encode(array('success' => FALSE, 'message' => "Please try Aftersometime..!!"));
		}		
	}
	//Update default shifts for missing shifts
	public function update_missing_shifts($from_date,$to_date,$employee_code){
		//get active financial id
		$leave_financial_info  = $this->get_leave_financial_details();
		$financial_id          = $leave_financial_info[0]->prime_leave_financial_year_id;

		//Shift Update start - BSK
		//Get Existing Shifts
		$shift_import_exist_qry  = 'select cw_employees.employee_code,shift_date,prime_shift_import_id as prime_id from cw_shift_import inner join cw_employees on cw_employees.employee_code = cw_shift_import.employee_code where cw_shift_import.trans_status = 1 and shift_date between "'.$from_date.'" and "'.$to_date.'" and financial_setting_id ="'.$financial_id.'"';
		//echo "BSK $shift_import_exist_qry"; die;
		$shift_info   = $this->db->query("CALL sp_a_run ('SELECT','$shift_import_exist_qry')");
		$shift_result = $shift_info->result_array();
		$shift_info->next_result();

		$shift_import_arr = array();
		foreach ($shift_result as $key => $value){
			$shift_import_arr[$value['employee_code']][$value['shift_date']] = $value;
		}	
		//Get Eligible Employees List
		$emp_query = 'SELECT employee_code,emp_name,date_of_joining FROM cw_employees WHERE  termination_status = 0 AND cw_employees.date_of_joining <= "'.$to_date.'" AND role != 1';
		$emp_info   = $this->db->query("CALL sp_a_run ('SELECT','$emp_query')");
		$emp_result = $emp_info->result_array();
		$emp_info->next_result();
		//print_r($emp_result); die;
		/*$emp_details = array();
		foreach ($emp_result as $key => $value){
			$emp_details[$value['employee_code']] = $value['date_of_joining'];
		}*/
		$prime_qry_value     = "";		
		$updated_on          = date("Y-m-d H:i:s");
		$current             = $from_date;
		$end                 = $to_date;

		// DEFAULT SHIFT GETTING QUERY
		$shift_qry			 = 'select default_shift from cw_company_information';
		$shift_qry_info		 = $this->db->query($shift_qry);
		$shift_qry_result	 = $shift_qry_info->result_array();
		$shift_qry_info->next_result();
		$default_shift 		 = $shift_qry_result[0]['default_shift']; 

		foreach($emp_result as $key => $value){
			$employee_code   = $value['employee_code'];
			$emp_name        = $value['emp_name'];
			$date_of_joining = $value['date_of_joining'];
			$current         = $from_date;	
			if(strtotime($current) < strtotime($date_of_joining)){
				$current  = $date_of_joining;
			}	
			while($current <= $end){
				if(!$shift_import_arr[$employee_code][$current]){
					$prime_qry_value   .= '("'.$employee_code.'","'.$emp_name.'","'.$current.'","'.$current.'","'.$current.'","'.$default_shift.'","'.$financial_id.'","1",'.'"'.$updated_on.'"),';
					$i = $i+1;
				}
				$current     = date('Y-m-d', strtotime('+1 day', strtotime($current)));
			}
		}
		
		if($prime_qry_value){
			$shift_qry      = 'INSERT INTO cw_shift_import(employee_code,employee_name, from_date, to_date,shift_date,shift_name,financial_setting_id,trans_created_by,trans_created_date) VALUES '.rtrim($prime_qry_value,",");
			// echo $shift_qry; die;
			$shift_ins_info = $this->db->query($shift_qry);
		}
		return true;
	}
	//Process Intervening LOP
	public function process_ilop($from_date,$to_date,$employee_code){
		$start_date = date('Y-m-d',strtotime($from_date." -3 days"));
		$end_date   = date('Y-m-d',strtotime($to_date." +3 days"));

		$where_qry = "";
		if($employee_code){
			$where_qry = ' and employee_code = "'.$employee_code.'"';
		}
		$time_entry_qry   = 'SELECT employee_code,att_date,whole_day_status from cw_time_entry where trans_status = 1 and att_date between "'.$start_date.'" and "'.$end_date.'" '.$where_qry;
		$time_entry_info  = $this->db->query("CALL sp_a_run ('RUN','$time_entry_qry')");
		$time_entry_result = $time_entry_info->result_array();
		$time_entry_info->next_result();
		$time_entry_result_arr       = array_reduce($time_entry_result, function($result, $arr){			
		    $result[$arr['employee_code']][$arr['att_date']] = $arr['whole_day_status'];
		    return $result;
			}, array());

		$weekoff_qry   = 'SELECT employee_code,date_sub(weekoff.att_date,INTERVAL 3 day) as prev3,date_sub(weekoff.att_date,INTERVAL 2 day) as prev,date_sub(weekoff.att_date,INTERVAL 1 day) as previous,att_date,date_add(weekoff.att_date,INTERVAL 1 day) as next_dt,date_add(weekoff.att_date,INTERVAL 2 day) as next,date_add(weekoff.att_date,INTERVAL 3 day) as next3,whole_day_status from (SELECT employee_code,att_date,whole_day_status FROM `cw_time_entry` WHERE (whole_day_status = "W" || whole_day_status = "H") and total_work_hours <= 0 and att_date BETWEEN "'.$from_date.'" and "'.$to_date.'" '.$where_qry.') as weekoff';
		$weekoff_info  = $this->db->query("CALL sp_a_run ('RUN','$weekoff_qry')");
		$weekoff_result = $weekoff_info->result();
		$weekoff_info->next_result();
		$leave_arr = array("L"=>1,"LL"=>1,"U"=>1);
		$off_arr   = array("W"=>1,"H"=>1);
		$ilop_dates = array();
		$insert_qry = "";
		foreach($weekoff_result as $code => $value){
			$employee_code  = $value->employee_code;
			$previous3      = $value->prev3;
			$previous2      = $value->prev;
			$previous1      = $value->previous;
			$next1          = $value->next_dt;
			$next2          = $value->next;
			$next3          = $value->next3;
			$att_date       = $value->att_date;
			$previous1_sts  = $time_entry_result_arr[$employee_code][$previous1];
			$previous2_sts  = $time_entry_result_arr[$employee_code][$previous2];
			$previous3_sts  = $time_entry_result_arr[$employee_code][$previous3];
			$next1_sts      = $time_entry_result_arr[$employee_code][$next1];
			$next2_sts      = $time_entry_result_arr[$employee_code][$next2];
			$next3_sts      = $time_entry_result_arr[$employee_code][$next3];
			if($leave_arr[$previous1_sts] && $leave_arr[$next1_sts]){ //if previous and next day leave
				if(!$ilop_dates[$employee_code][$att_date]){
					$insert_qry .= '("'.$employee_code.'","'.$att_date.'","L","0","L","ILOP","ILOP","0.50","0.50"),';
				}
				$ilop_dates[$employee_code][$att_date] = $att_date;
			}else
			if($off_arr[$previous1_sts] && !$off_arr[$previous2_sts]){ //if previous1 leave and previous2 not
				//echo "YES2";
				if($leave_arr[$previous2_sts] && $leave_arr[$next1_sts]){
					if(!$ilop_dates[$employee_code][$att_date]){
						$insert_qry .= '("'.$employee_code.'","'.$att_date.'","L","0","L","ILOP","ILOP","0.50","0.50"),';
					}
					if(!$ilop_dates[$employee_code][$previous1]){
						$insert_qry .= '("'.$employee_code.'","'.$previous1.'","L","0","L","ILOP","ILOP","0.50","0.50"),';
					}
					$ilop_dates[$employee_code][$att_date] = $att_date;
					$ilop_dates[$employee_code][$previous1] = $previous1;
				}
			}else
			if($off_arr[$next1_sts] && !$off_arr[$next2_sts]){  //if next1 leave and next2 not
				//echo "YES3";
				if($leave_arr[$previous1_sts] && $leave_arr[$next2_sts]){
					if(!$ilop_dates[$employee_code][$att_date]){
						$insert_qry .= '("'.$employee_code.'","'.$att_date.'","L","0","L","ILOP","ILOP","0.50","0.50"),';
					}
					if(!$ilop_dates[$employee_code][$next1]){
						$insert_qry .= '("'.$employee_code.'","'.$next1.'","L","0","L","ILOP","ILOP","0.50","0.50"),';
					}
					$ilop_dates[$employee_code][$att_date] = $att_date;
					$ilop_dates[$employee_code][$next1] = $next1;
				}
			}else
			if($off_arr[$next1_sts] && $off_arr[$next2_sts]){   //if next1 and next2 day leave
				//echo "YES4"; 
				if($leave_arr[$previous1_sts] && $leave_arr[$next3_sts]){
					if(!$ilop_dates[$employee_code][$next1]){
						$insert_qry .= '("'.$employee_code.'","'.$next1.'","L","0","L","ILOP","ILOP","0.50","0.50"),';
					}
					if(!$ilop_dates[$employee_code][$next2]){
						$insert_qry .= '("'.$employee_code.'","'.$next2.'","L","0","L","ILOP","ILOP","0.50","0.50"),';
					}
					$ilop_dates[$employee_code][$next1] = $next1;
					$ilop_dates[$employee_code][$next2] = $next2;
				}
			}else
			if($off_arr[$previous1_sts] && $off_arr[$previous2_sts]){ //if previous1 leave and previous2 leave
				//echo "YES5";
				if($leave_arr[$previous3_sts] && $leave_arr[$next1_sts]){
					if(!$ilop_dates[$employee_code][$previous1]){
						$insert_qry .= '("'.$employee_code.'","'.$previous1.'","L","0","L","ILOP","ILOP","0.50","0.50"),';
					}
					if(!$ilop_dates[$employee_code][$previous2]){
						$insert_qry .= '("'.$employee_code.'","'.$previous2.'","L","0","L","ILOP","ILOP","0.50","0.50"),';
					}
					$ilop_dates[$employee_code][$previous1] = $previous1;
					$ilop_dates[$employee_code][$previous2] = $previous2;
				}
			}
		}
		
		if($insert_qry){
			$insert_qry = rtrim($insert_qry,",");
			$drop_qry  = 'DROP TABLE IF EXISTS tbl_ilop_temp';
			$drop_info = $this->db->query("CALL sp_a_run ('RUN','$drop_qry')");
			if($drop_info){
				$run_query = 'CREATE TABLE tbl_ilop_temp (employee_code VARCHAR(100),att_date DATETIME,entry_flag VARCHAR(50),update_flag VARCHAR(50),whole_day_status VARCHAR(50),first_half_status VARCHAR(50),second_half_status VARCHAR(50),first_half_count DECIMAL(10,2),second_half_count DECIMAL(10,2))';
				$run_info  = $this->db->query("CALL sp_a_run ('RUN','$run_query')");
				if($run_info){
					$temp_insert_qry  = 'INSERT INTO tbl_ilop_temp (employee_code,att_date,entry_flag,update_flag,whole_day_status,first_half_status,second_half_status,first_half_count,second_half_count) VALUES '.$insert_qry;
					$temp_insert_info = $this->db->query($temp_insert_qry);
					if($temp_insert_info){
						$result_info = $this->db->query("CALL itsp_ilop()");
						$result      = $result_info->result();
						$result_info->next_result();
						return true;
					}					
				}
			}			
		}else{
			return true;
		}						
	}
}
?>